通过 go 进行 aes 加密
在 go 中实现 aes 加密通常是通过使用 crypto/aes 包来完成的。aes 是高级加密标准,是一种可靠的对称块加密算法。本文将提供一个实现 aes 加密和解密的 go 代码示例。
package main import ( "crypto/aes" "encoding/base64" "log" ) func main() { origin := []byte("406BF0AD11310101220213481000320000") key := []byte("ER2Fb6ts3ECX") encrypted := AesEncryptECB(origin, key) log.Println("encrypted: ", encrypted) decrypted := AesDecryptECB(encrypted, key) log.Println("decrypted: ", string(decrypted)) } func AesEncryptECB(origData []byte, key []byte) string { cipher, _ := aes.NewCipher(generateKey(key)) length := (len(origData) + aes.BlockSize) / aes.BlockSize plain := make([]byte, length*aes.BlockSize) copy(plain, origData) encrypted := make([]byte, len(plain)) // Block encryption for bs, be := 0, cipher.BlockSize(); bs <= len(origData); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() { cipher.Encrypt(encrypted[bs:be], plain[bs:be]) } return base64.StdEncoding.EncodeToString(encrypted) } func AesDecryptECB(str string, key []byte) (decrypted []byte) { encrypted, _ := base64.StdEncoding.DecodeString(str) cipher, _ := aes.NewCipher(generateKey(key)) decrypted = make([]byte, len(encrypted)) for bs, be := 0, cipher.BlockSize(); bs < len(encrypted); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() { cipher.Decrypt(decrypted[bs:be], encrypted[bs:be]) } trim := 0 if len(decrypted) > 0 { trim = len(decrypted) - int(decrypted[len(decrypted)-1]) } return decrypted[:trim] } func generateKey(key []byte) (genKey []byte) { genKey = make([]byte, 16) copy(genKey, key) for i := 16; i < len(key); { for j := 0; j < 16 && i < len(key); j, i = j+1, i+1 { genKey[j] ^= key[i] } } return genKey }
使用此代码,你可以通过以下步骤加密和解密数据:
注意:
golang框架在微服务架构中的应用
Go语言单向Channel:如何实现只读且写入数据?
Go语言中间件如何优雅地处理多个业务共用同一复杂逻辑?
如何在 Go 代码中获取包含 Java 脚本的绝对路径?
在Go语言开发中处理和解析JSON格式的请求参数,并在Swagger中正确标注,是一个常见的需求。以下是详细的步骤和示例:处理和解析JSON格式的请求参数定义结构体: 首先,需要定义一个结构体来接收JSON数据。这个结构体中的字段需要和JSON数据中的键名一致,并且使用json标签来指定字段名。type User struct { ID int `json:"id"` Name string `json:"name"` Age int `json:"age"` }
Golang框架如何解决安全漏洞问题?