aes
This commit is contained in:
+8
-8
@@ -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
|
||||||
|
|||||||
Reference in New Issue
Block a user