initial go implementation

This commit is contained in:
2025-11-23 12:12:20 +08:00
commit f40ace4058
12 changed files with 368 additions and 0 deletions

View 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
}