Created
May 20, 2016 09:09
-
-
Save johnsonz/53e533b2fe12bae0d39a82324491f8d6 to your computer and use it in GitHub Desktop.
go 使用AES256 加密、解密
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func AESEncrypt(key, text string) ([]byte, error) { | |
block, err := aes.NewCipher([]byte(key)) | |
if err != nil { | |
return nil, err | |
} | |
b := Base64Encode([]byte(text)) | |
ciphertext := make([]byte, aes.BlockSize+len(b)) | |
iv := ciphertext[:aes.BlockSize] | |
if _, err := io.ReadFull(rand.Reader, iv); err != nil { | |
return nil, err | |
} | |
cfb := cipher.NewCFBEncrypter(block, iv) | |
cfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(b)) | |
return ciphertext, nil | |
} | |
func AESDecrypt(key string, text []byte) ([]byte, error) { | |
block, err := aes.NewCipher([]byte(key)) | |
if err != nil { | |
return nil, err | |
} | |
if len(text) == 0 { | |
return nil, nil | |
} | |
if len(text) < aes.BlockSize { | |
return nil, errors.New("ciphertext too short" + " ,len=" + string(len(text)) + ",blocksize=" + string(aes.BlockSize)) | |
} | |
iv := text[:aes.BlockSize] | |
text = text[aes.BlockSize:] | |
cfb := cipher.NewCFBDecrypter(block, iv) | |
cfb.XORKeyStream(text, text) | |
data, err := Base64Decode(text) | |
if err != nil { | |
return nil, err | |
} | |
return data, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment