service/library/mycrypto/aesCrypto.go

80 lines
2.7 KiB
Go
Raw Normal View History

2023-12-21 22:17:40 +08:00
package mycrypto
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"service/library/configcenter"
"service/library/logger"
)
type AesCrypto struct {
aesPriKey []byte
}
func NewAesCrypto(cryptoConfig *configcenter.CryptoConfig) (aesCrypto *AesCrypto, err error) {
aesCrypto = &AesCrypto{}
//读取私钥
if aesCrypto.readAESPriKey(cryptoConfig) != nil {
logger.Error("read rsa primary key failed!", err)
return
}
return
}
2024-06-15 13:41:03 +08:00
func NewAesCryptoFromString(aesPrivateKeyStr string) (aesCrypto *AesCrypto, err error) {
aesCrypto = &AesCrypto{}
//读取私钥
aesCrypto.aesPriKey = []byte(aesPrivateKeyStr)
return
}
2023-12-21 22:17:40 +08:00
func (aesCrypto *AesCrypto) Encrypt(msg []byte) (encryptedBytes []byte, err error) {
//CBC加密
block, err := aes.NewCipher(aesCrypto.aesPriKey) //block
if err != nil {
logger.Error("AES NewCipher failed!, err: %v", err)
return nil, err
}
blockSize := block.BlockSize() //密钥块长度
paddedData := aesCrypto.pkcs5Padding(msg, blockSize) //填充
blockMode := cipher.NewCBCEncrypter(block, aesCrypto.aesPriKey[:blockSize]) //加密模式
encryptedBytes = make([]byte, len(paddedData)) //创建数组
blockMode.CryptBlocks(encryptedBytes, paddedData) //加密
return
}
func (aesCrypto *AesCrypto) Decrypt(encryptedBytes []byte) (decryptedBytes []byte, err error) {
if len(encryptedBytes) == 0 {
return
}
2023-12-21 22:17:40 +08:00
//CBC解密
block, _ := aes.NewCipher(aesCrypto.aesPriKey) // 分组秘钥
blockSize := block.BlockSize() // 获取秘钥块的长度
blockMode := cipher.NewCBCDecrypter(block, aesCrypto.aesPriKey[:blockSize]) // 加密模式
decryptedBytes = make([]byte, len(encryptedBytes)) // 创建数组
blockMode.CryptBlocks(decryptedBytes, encryptedBytes) // 解密
decryptedBytes = aesCrypto.pkcs5UnPadding(decryptedBytes) // 去除补全码
return
}
func (aesCrypto *AesCrypto) readAESPriKey(cryptoConfig *configcenter.CryptoConfig) (err error) {
//读取私钥
aesCrypto.aesPriKey = []byte(cryptoConfig.AESPrivateKey)
return
}
func (aesCrypto *AesCrypto) pkcs5Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize //判断缺少几位长度。最少1最多 blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding) //补足位数。把切片[]byte{byte(padding)}复制padding个
return append(ciphertext, padtext...)
}
func (aesCrypto *AesCrypto) pkcs5UnPadding(origData []byte) []byte {
length := len(origData)
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}