func PKCS7Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
//The Repeat() function copies the slice []byte{byte(padding)} padding times, then merges it into a new byte slice and returns it
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
//The reverse operation of padding: remove the padding string
func PKCS7UnPadding(origData []byte) ([]byte, error) {
//Get the data length
length := len(origData)
if length == 0 {
return nil, errors.New("加密字符串错误!")
} else {
//Get the length of the padding string
unpadding := int(origData[length-1])
//Slice off, remove the padding bytes, and return the plaintext
return origData[:(length - unpadding)], nil
}
}
//Implement encryption
func AesEcrypt(origData []byte, key []byte) ([]byte, error) {
//Create an instance of the encryption algorithm
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
//Get the block size
blockSize := block.BlockSize()
//Pad the data so its length meets the requirement
origData = PKCS7Padding(origData, blockSize)
//Use CBC mode from the AES encryption methods
blocMode := cipher.NewCBCEncrypter(block, key[:blockSize])
crypted := make([]byte, len(origData))
//Perform the encryption
blocMode.CryptBlocks(crypted, origData)
return crypted, nil
}
//Implement decryption
func AesDeCrypt(cypted []byte, key []byte) ([]byte, error) {
//Create an instance of the encryption algorithm
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
//Get the block size
blockSize := block.BlockSize()
//Create an instance of the decryption client
blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
origData := make([]byte, len(cypted))
//This function can also be used for decryption
blockMode.CryptBlocks(origData, cypted)
//Remove the padding string
origData, err = PKCS7UnPadding(origData)
if err != nil {
return nil, err
}
return origData, err
}
//Encrypt base64
func EnPwdCode(pwd []byte) (string, error) {
result, err := AesEcrypt(pwd, getKey())
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(result), err
}
//Decrypt
func DePwdCode(pwd string) ([]byte, error) {
//Decrypt the base64 string
pwdByte, err := base64.StdEncoding.DecodeString(pwd)
if err != nil || len(pwdByte) <= 0 {
return nil, err
}
//Perform AES decryption
return AesDeCrypt(pwdByte, getKey())
}
//Encrypt base64
func EnPwdUserCode(pwd []byte) (string, error) {
result, err := AesEcrypt(pwd, getUserKey())
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(result), err
}
//Decrypt
func DePwdUserCode(pwd string) ([]byte, error) {
//Decrypt the base64 string
pwdByte, err := base64.StdEncoding.DecodeString(pwd)
if err != nil || len(pwdByte) <= 0 {
return nil, err
}
//Perform AES decryption
return AesDeCrypt(pwdByte, getUserKey())
}