From df98b40506b09371a3395c9cbb05848ade6bcb88 Mon Sep 17 00:00:00 2001 From: Peter Sanchez Date: Thu, 7 Mar 2024 18:29:29 -0600 Subject: [PATCH] Adding base64 URL encoding for crypto values and defining custom Encoding objects --- crypto/crypto.go | 41 +++++++++++++++++++++++++++++++++-------- 1 file changed, 33 insertions(+), 8 deletions(-) diff --git a/crypto/crypto.go b/crypto/crypto.go index c23cf10..0f1ba3a 100644 --- a/crypto/crypto.go +++ b/crypto/crypto.go @@ -121,22 +121,47 @@ func DecryptBytes(bytes []byte, key []byte) ([]byte, error) { return plaintext, nil } -// EncryptBytesB64 will encrypt the given bytes with the given key and -// return the base64 encoded result. -func EncryptBytesB64(bytes []byte, key []byte) (string, error) { +// EncryptBytesB64Encoding will encrypt the given bytes with the given key +// and return the base64 encoded result. The base64 encoding will be done +// with the provided *base64.Encoding type. +func EncryptBytesB64Encoding(enc *base64.Encoding, bytes []byte, key []byte) (string, error) { encVal, err := EncryptBytes(bytes, key) if err != nil { return "", err } - return base64.StdEncoding.EncodeToString(encVal), nil + return enc.EncodeToString(encVal), nil + } -// DecryptBytesB64 will base64 decode the given value and decrypt -// decoded bytes with the given key. -func DecryptBytesB64(b64value string, key []byte) ([]byte, error) { - bytes, err := base64.StdEncoding.DecodeString(b64value) +// EncryptBytesB64 will encrypt and encode using the base64.StdEncoding type +func EncryptBytesB64(bytes []byte, key []byte) (string, error) { + return EncryptBytesB64Encoding(base64.StdEncoding, bytes, key) +} + +// EncryptBytesB64URL will encrypt and encode using the base64.URLEncoding type +func EncryptBytesB64URL(bytes []byte, key []byte) (string, error) { + return EncryptBytesB64Encoding(base64.URLEncoding, bytes, key) +} + +// DecryptBytesB64Encoding will base64 decode the given value and decrypt +// decoded bytes with the given key. The base64 decoding will be done +// with the provided *base64.Encoding type. +func DecryptBytesB64Encoding(enc *base64.Encoding, b64value string, key []byte) ([]byte, error) { + bytes, err := enc.DecodeString(b64value) if err != nil { return nil, err } return DecryptBytes(bytes, key) } + +// DecryptBytesB64 will base64 decode using the base64.StdEncoding type +// and decrypt the resulting data. +func DecryptBytesB64(b64value string, key []byte) ([]byte, error) { + return DecryptBytesB64Encoding(base64.StdEncoding, b64value, key) +} + +// DecryptBytesB64URL will base64 decode using the base64.StdEncoding type +// and decrypt the resulting data. +func DecryptBytesB64URL(b64value string, key []byte) ([]byte, error) { + return DecryptBytesB64Encoding(base64.URLEncoding, b64value, key) +} -- 2.45.2