aes
This commit is contained in:
+13
-13
@@ -57,25 +57,25 @@ key:加密key
|
||||
plaintext:加密明文
|
||||
ciphertext:解密返回字节字符串[ 整型以十六进制方式显示]
|
||||
*/
|
||||
func AESCBCEncrypt(key, plaintext string) (ciphertext string,err error) {
|
||||
plainbyte := []byte(plaintext)
|
||||
keybyte := []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)
|
||||
func AESCBCEncrypt(key, plaintext string) (ciphertext string, err error) {
|
||||
|
||||
block, err := aes.NewCipher([]byte(key))
|
||||
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]
|
||||
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
|
||||
return "",err
|
||||
return "", err
|
||||
}
|
||||
|
||||
mode := cipher.NewCBCEncrypter(block, iv)
|
||||
mode.CryptBlocks(cipherbyte[aes.BlockSize:], plainbyte)
|
||||
mode.CryptBlocks(cipherbyte[aes.BlockSize:], plainBytes)
|
||||
|
||||
ciphertext = fmt.Sprintf("%x\n", cipherbyte)
|
||||
return
|
||||
@@ -87,12 +87,12 @@ key:解密key
|
||||
ciphertext:加密返回的串
|
||||
plaintext:解密后的字符串
|
||||
*/
|
||||
func AESCBCDecrypter(key, ciphertext string) (plaintext string,err error) {
|
||||
func AESCBCDecrypter(key, ciphertext string) (plaintext string, err error) {
|
||||
cipherbyte, _ := hex.DecodeString(ciphertext)
|
||||
keybyte := []byte(key)
|
||||
block, err := aes.NewCipher(keybyte)
|
||||
if err != nil {
|
||||
return "",err
|
||||
return "", err
|
||||
}
|
||||
if len(cipherbyte) < aes.BlockSize {
|
||||
return "", errors.New("ciphertext too short")
|
||||
|
||||
Reference in New Issue
Block a user