2023-03-15 16:00:52 +00:00
|
|
|
// Copyright (c) HashiCorp, Inc.
|
|
|
|
// SPDX-License-Identifier: MPL-2.0
|
|
|
|
|
2016-01-09 02:21:02 +00:00
|
|
|
package xor
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/base64"
|
|
|
|
"fmt"
|
|
|
|
)
|
|
|
|
|
2016-01-15 15:41:29 +00:00
|
|
|
// XORBytes takes two byte slices and XORs them together, returning the final
|
|
|
|
// byte slice. It is an error to pass in two byte slices that do not have the
|
|
|
|
// same length.
|
|
|
|
func XORBytes(a, b []byte) ([]byte, error) {
|
2016-01-09 02:21:02 +00:00
|
|
|
if len(a) != len(b) {
|
2016-01-15 15:41:29 +00:00
|
|
|
return nil, fmt.Errorf("length of byte slices is not equivalent: %d != %d", len(a), len(b))
|
2016-01-09 02:21:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
buf := make([]byte, len(a))
|
|
|
|
|
2021-04-08 16:43:39 +00:00
|
|
|
for i := range a {
|
2016-01-09 02:21:02 +00:00
|
|
|
buf[i] = a[i] ^ b[i]
|
|
|
|
}
|
|
|
|
|
|
|
|
return buf, nil
|
|
|
|
}
|
|
|
|
|
2016-01-15 15:41:29 +00:00
|
|
|
// XORBase64 takes two base64-encoded strings and XORs the decoded byte slices
|
|
|
|
// together, returning the final byte slice. It is an error to pass in two
|
|
|
|
// strings that do not have the same length to their base64-decoded byte slice.
|
2016-01-09 02:21:02 +00:00
|
|
|
func XORBase64(a, b string) ([]byte, error) {
|
|
|
|
aBytes, err := base64.StdEncoding.DecodeString(a)
|
|
|
|
if err != nil {
|
2021-05-07 12:53:20 +00:00
|
|
|
return nil, fmt.Errorf("error decoding first base64 value: %w", err)
|
2016-01-09 02:21:02 +00:00
|
|
|
}
|
|
|
|
if aBytes == nil || len(aBytes) == 0 {
|
|
|
|
return nil, fmt.Errorf("decoded first base64 value is nil or empty")
|
|
|
|
}
|
|
|
|
|
|
|
|
bBytes, err := base64.StdEncoding.DecodeString(b)
|
|
|
|
if err != nil {
|
2021-05-07 12:53:20 +00:00
|
|
|
return nil, fmt.Errorf("error decoding second base64 value: %w", err)
|
2016-01-09 02:21:02 +00:00
|
|
|
}
|
|
|
|
if bBytes == nil || len(bBytes) == 0 {
|
|
|
|
return nil, fmt.Errorf("decoded second base64 value is nil or empty")
|
|
|
|
}
|
|
|
|
|
2016-01-15 15:41:29 +00:00
|
|
|
return XORBytes(aBytes, bBytes)
|
2016-01-09 02:21:02 +00:00
|
|
|
}
|