golang AES
发布时间:2020-12-16 09:31:49 所属栏目:大数据 来源:网络整理
导读:加密:ASE加密后使用base64编码 解密:base64解码后使用ASE解密 ? 1 package main 2 3 import ( 4 " crypto/aes " 5 " crypto/cipher " 6 " crypto/rand " 7 " encoding/base64 " 8 " fmt " 9 " io " 10 ) 11 12 // Encrypt string to base64 crypto using A
加密:ASE加密后使用base64编码 解密:base64解码后使用ASE解密 ? 1 package main 2 3 import ( 4 "crypto/aes" 5 "crypto/cipher" 6 "crypto/rand" 7 "encoding/base64" 8 "fmt" 9 "io" 10 ) 11 12 // Encrypt string to base64 crypto using AES 13 func AESEncrypt(key []byte,text string) (string,bool) { 14 plaintext := []byte(text) 15 16 block,err := aes.NewCipher(key) 17 if err != nil { 18 return "",false 19 } 20 21 ciphertext := make([]byte,aes.BlockSize+len(plaintext)) 22 iv := ciphertext[:aes.BlockSize] 23 if _,err := io.ReadFull(rand.Reader,iv); err != nil { 24 return "",false 25 } 26 27 stream := cipher.NewCFBEncrypter(block,iv) 28 stream.XORKeyStream(ciphertext[aes.BlockSize:],plaintext) 29 30 return base64.URLEncoding.EncodeToString(ciphertext),true 31 } 32 33 // Decrypt from base64 to decrypted string 34 func AESDecrypt(key []byte,cryptoText string) (string,bool) { 35 ciphertext,_ := base64.URLEncoding.DecodeString(cryptoText) 36 37 block,err := aes.NewCipher(key) 38 if err != nil { 39 return "",false 40 } 41 42 if len(ciphertext) < aes.BlockSize { 43 return "",false 44 } 45 iv := ciphertext[:aes.BlockSize] 46 ciphertext = ciphertext[aes.BlockSize:] 47 48 stream := cipher.NewCFBDecrypter(block,iv) 49 50 stream.XORKeyStream(ciphertext,ciphertext) 51 52 return fmt.Sprintf("%s",ciphertext),true 53 } 54 55 func main() { 56 var key = []byte("6aaf508205a7e5cca6b03ee5747a92f3") 57 58 // 每次得到的结果都不同,但是都可以解密 59 msg,ok := AESEncrypt(key,"abcd===a") 60 if !ok { 61 fmt.Println("encrypt is failed.") 62 } 63 fmt.Println("msg=",msg) 64 65 text,ok := AESDecrypt(key,msg) 66 if !ok { 67 fmt.Println("decrypt is failed.") 68 } 69 70 fmt.Println("text=",text) 71 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |