aes
This commit is contained in:
+13
-13
@@ -57,25 +57,25 @@ key:加密key
|
|||||||
plaintext:加密明文
|
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
|
||||||
@@ -87,12 +87,12 @@ key:解密key
|
|||||||
ciphertext:加密返回的串
|
ciphertext:加密返回的串
|
||||||
plaintext:解密后的字符串
|
plaintext:解密后的字符串
|
||||||
*/
|
*/
|
||||||
func AESCBCDecrypter(key, ciphertext string) (plaintext string,err error) {
|
func AESCBCDecrypter(key, ciphertext string) (plaintext string, err error) {
|
||||||
cipherbyte, _ := hex.DecodeString(ciphertext)
|
cipherbyte, _ := hex.DecodeString(ciphertext)
|
||||||
keybyte := []byte(key)
|
keybyte := []byte(key)
|
||||||
block, err := aes.NewCipher(keybyte)
|
block, err := aes.NewCipher(keybyte)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "",err
|
return "", err
|
||||||
}
|
}
|
||||||
if len(cipherbyte) < aes.BlockSize {
|
if len(cipherbyte) < aes.BlockSize {
|
||||||
return "", errors.New("ciphertext too short")
|
return "", errors.New("ciphertext too short")
|
||||||
|
|||||||
Reference in New Issue
Block a user