You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
lib/crypto/aes.go

74 lines
1.7 KiB
Go

package crypto
import (
"bytes"
"crypto/aes"
"crypto/cipher"
3 years ago
"github.com/Luzifer/go-openssl/v3"
)
func paddingPKCS7(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
func unpaddingPKCS7(origData []byte) []byte {
length := len(origData)
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}
//EncryptAES 加密函式
func EncryptAES(plaintext, key, iv []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
plaintext = paddingPKCS7(plaintext, blockSize)
blockMode := cipher.NewCBCEncrypter(block, iv)
crypted := make([]byte, len(plaintext))
blockMode.CryptBlocks(crypted, plaintext)
return crypted, nil
}
// DecryptAES 解密函式
func DecryptAES(ciphertext, key, iv []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
blockMode := cipher.NewCBCDecrypter(block, iv[:blockSize])
origData := make([]byte, len(ciphertext))
blockMode.CryptBlocks(origData, ciphertext)
origData = unpaddingPKCS7(origData)
return origData, nil
}
3 years ago
// DecryptAESWithOpenSSL 使用Openssl 解密AES
func DecryptAESWithOpenSSL(value, key string) ([]byte, error) {
o := openssl.New()
dec, err := o.DecryptBytes(key, []byte(value), openssl.DigestMD5Sum)
if err != nil {
return nil, err
}
return dec, nil
}
// EncryptAESWithOpenSSL 使用Openssl 加密AES
func EncryptAESWithOpenSSL(value, key string) ([]byte, error) {
o := openssl.New()
enc, err := o.EncryptBytes(key, []byte(value), openssl.DigestMD5Sum)
if err != nil {
return nil, err
}
return enc, nil
}