This commit is contained in:
Yun
2024-10-27 22:12:08 +08:00
parent 9b3b9ae574
commit 8bcdc16955
+8 -8
View File
@@ -58,24 +58,24 @@ plaintext:加密明文
ciphertext:解密返回字节字符串[ 整型以十六进制方式显示] ciphertext:解密返回字节字符串[ 整型以十六进制方式显示]
*/ */
func AESCBCEncrypt(key, plaintext string) (ciphertext string, err error) { func AESCBCEncrypt(key, plaintext string) (ciphertext string, err error) {
plainbyte := []byte(plaintext)
keybyte := []byte(key) block, err := aes.NewCipher([]byte(key))
if len(plainbyte)%aes.BlockSize != 0 {
return "",errors.New ("plaintext is not a multiple of the block size")
}
block, err := aes.NewCipher(keybyte)
if err != nil { if err != nil {
return "", err return "", err
} }
cipherbyte := make([]byte, aes.BlockSize+len(plainbyte)) padding := aes.BlockSize - (len(plaintext) % aes.BlockSize)
padtest := bytes.Repeat([]byte{byte(padding)}, padding)
plainBytes := append([]byte(plaintext), padtest...)
cipherbyte := make([]byte, aes.BlockSize+len(plainBytes))
iv := cipherbyte[:aes.BlockSize] iv := cipherbyte[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil { if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return "", err return "", err
} }
mode := cipher.NewCBCEncrypter(block, iv) mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(cipherbyte[aes.BlockSize:], plainbyte) mode.CryptBlocks(cipherbyte[aes.BlockSize:], plainBytes)
ciphertext = fmt.Sprintf("%x\n", cipherbyte) ciphertext = fmt.Sprintf("%x\n", cipherbyte)
return return