Go   发布时间:2022-04-09  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了golang AES大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

加密: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("@H_751_24@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 }

大佬总结

以上是大佬教程为你收集整理的golang AES全部内容,希望文章能够帮你解决golang AES所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:aesgolang