...
|
...
|
@@ -13,13 +13,56 @@ func PKCS5Padding(plaintext []byte, blockSize int) []byte { |
|
|
}
|
|
|
|
|
|
//@brief:去除填充数据
|
|
|
func PKCS5UnPadding(origData []byte) []byte {
|
|
|
func PKCS5UnPadding(origData []byte, blockSize int) []byte {
|
|
|
length := len(origData)
|
|
|
unpadding := int(origData[length-1])
|
|
|
return origData[:(length - unpadding)]
|
|
|
}
|
|
|
|
|
|
//@brief:AES加密
|
|
|
// PKCS7Padding right-pads the given byte slice with 1 to n bytes, where
|
|
|
// n is the block size. The size of the result is x times n, where x
|
|
|
// is at least 1.
|
|
|
func PKCS7Padding(b []byte, blockSize int) []byte {
|
|
|
if blockSize <= 0 {
|
|
|
return nil
|
|
|
}
|
|
|
if b == nil || len(b) == 0 {
|
|
|
return nil
|
|
|
}
|
|
|
n := blockSize - (len(b) % blockSize)
|
|
|
pb := make([]byte, len(b)+n)
|
|
|
copy(pb, b)
|
|
|
copy(pb[len(b):], bytes.Repeat([]byte{byte(n)}, n))
|
|
|
return pb
|
|
|
}
|
|
|
|
|
|
// PKCS7UnPadding validates and unpads data from the given bytes slice.
|
|
|
// The returned value will be 1 to n bytes smaller depending on the
|
|
|
// amount of padding, where n is the block size.
|
|
|
func PKCS7UnPadding(b []byte, blockSize int) []byte {
|
|
|
if blockSize <= 0 {
|
|
|
return nil
|
|
|
}
|
|
|
if b == nil || len(b) == 0 {
|
|
|
return nil
|
|
|
}
|
|
|
if len(b)%blockSize != 0 {
|
|
|
return nil
|
|
|
}
|
|
|
c := b[len(b)-1]
|
|
|
n := int(c)
|
|
|
if n == 0 || n > len(b) {
|
|
|
return nil
|
|
|
}
|
|
|
for i := 0; i < n; i++ {
|
|
|
if b[len(b)-n+i] != c {
|
|
|
return nil
|
|
|
}
|
|
|
}
|
|
|
return b[:len(b)-n]
|
|
|
}
|
|
|
|
|
|
// AES加密
|
|
|
func AesEncrypt(origData, key []byte) ([]byte, error) {
|
|
|
block, err := aes.NewCipher(key)
|
|
|
if err != nil {
|
...
|
...
|
@@ -28,14 +71,14 @@ func AesEncrypt(origData, key []byte) ([]byte, error) { |
|
|
|
|
|
//AES分组长度为128位,所以blockSize=16,单位字节
|
|
|
blockSize := block.BlockSize()
|
|
|
origData = PKCS5Padding(origData, blockSize)
|
|
|
origData = PKCS7Padding(origData, blockSize)
|
|
|
blockMode := cipher.NewCBCEncrypter(block, key[:blockSize]) //初始向量的长度必须等于块block的长度16字节
|
|
|
crypted := make([]byte, len(origData))
|
|
|
blockMode.CryptBlocks(crypted, origData)
|
|
|
return crypted, nil
|
|
|
}
|
|
|
|
|
|
//@brief:AES解密
|
|
|
// AES解密
|
|
|
func AesDecrypt(crypted, key []byte) ([]byte, error) {
|
|
|
block, err := aes.NewCipher(key)
|
|
|
if err != nil {
|
...
|
...
|
@@ -47,6 +90,6 @@ func AesDecrypt(crypted, key []byte) ([]byte, error) { |
|
|
blockMode := cipher.NewCBCDecrypter(block, key[:blockSize]) //初始向量的长度必须等于块block的长度16字节
|
|
|
origData := make([]byte, len(crypted))
|
|
|
blockMode.CryptBlocks(origData, crypted)
|
|
|
origData = PKCS5UnPadding(origData)
|
|
|
origData = PKCS7UnPadding(origData, blockSize)
|
|
|
return origData, nil
|
|
|
} |
...
|
...
|
|