initial go implementation
This commit is contained in:
41
internal/utils/crypto/encrypt.go
Normal file
41
internal/utils/crypto/encrypt.go
Normal file
@@ -0,0 +1,41 @@
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func Encrypt(plaintext, key, iv string) (string, error) {
|
||||
padded := pkcs7Pad([]byte(plaintext))
|
||||
|
||||
block, err := aes.NewCipher([]byte(key))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("AES init failed: %v", err)
|
||||
}
|
||||
|
||||
if len(iv) != aes.BlockSize {
|
||||
return "", fmt.Errorf("IV must be %d bytes", aes.BlockSize)
|
||||
}
|
||||
|
||||
mode := cipher.NewCBCEncrypter(block, []byte(iv))
|
||||
ciphertext := make([]byte, len(padded))
|
||||
|
||||
mode.CryptBlocks(ciphertext, padded)
|
||||
|
||||
ciphertextB64 := base64.StdEncoding.EncodeToString(ciphertext)
|
||||
|
||||
return ciphertextB64, nil
|
||||
}
|
||||
|
||||
func pkcs7Pad(buf []byte) []byte {
|
||||
bufLen := len(buf)
|
||||
padLen := aes.BlockSize - bufLen%aes.BlockSize
|
||||
padded := make([]byte, bufLen+padLen)
|
||||
copy(padded, buf)
|
||||
for i := range padLen {
|
||||
padded[bufLen+i] = byte(padLen)
|
||||
}
|
||||
return padded
|
||||
}
|
||||
Reference in New Issue
Block a user