Golang Aes 加密示例
Aes加密的一个示例。供各位参考.
package main import ( "crypto/aes" "crypto/cipher" "fmt" ) func main() { aesEnc := AesEncrypt{} arrEncrypt, err := aesEnc.Encrypt("abcde") if err != nil { fmt.Println(arrEncrypt) return } strMsg, err := aesEnc.Decrypt(arrEncrypt) if err != nil { fmt.Println(arrEncrypt) return } fmt.Println(strMsg) } type AesEncrypt struct { } func (this *AesEncrypt) getKey() []byte { strKey := "1234567890123456" keyLen := len(strKey) if keyLen < 16 { panic("res key 长度不能小于16") } arrKey := []byte(strKey) if keyLen >= 32 { //取前32个字节 return arrKey[:32] } if keyLen >= 24 { //取前24个字节 return arrKey[:24] } //取前16个字节 return arrKey[:16] } //加密字符串 func (this *AesEncrypt) Encrypt(strMesg string) ([]byte, error) { key := this.getKey() var iv = []byte(key)[:aes.BlockSize] encrypted := make([]byte, len(strMesg)) aesBlockEncrypter, err := aes.NewCipher(key) if err != nil { return nil, err } aesEncrypter := cipher.NewCFBEncrypter(aesBlockEncrypter, iv) aesEncrypter.XORKeyStream(encrypted, []byte(strMesg)) return encrypted, nil } //解密字符串 func (this *AesEncrypt) Decrypt(src []byte) (strDesc string, err error) { defer func() { //错误处理 if e := recover(); e != nil { err = e.(error) } }() key := this.getKey() var iv = []byte(key)[:aes.BlockSize] decrypted := make([]byte, len(src)) var aesBlockDecrypter cipher.Block aesBlockDecrypter, err = aes.NewCipher([]byte(key)) if err != nil { return "", err } aesDecrypter := cipher.NewCFBDecrypter(aesBlockDecrypter, iv) aesDecrypter.XORKeyStream(decrypted, src) return string(decrypted), nil }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。