欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 创投人物 > Golang AES 对称加密

Golang AES 对称加密

2024/10/24 21:37:11 来源:https://blog.csdn.net/chechenshi/article/details/140612867  浏览:    关键词:Golang AES 对称加密

背景

需要加密手机号、身份证号和银行卡

代码

AES 加解密函数

// Encrypt encrypts plaintext using the given key with AES.
func EncryptWithKey(plaintext string, key []byte) (string, error) {// Generate a new AES cipher using the keyblock, err := aes.NewCipher(key)if err != nil {return "", err}// Create a new GCM (Galois/Counter Mode) cipher modegcm, err := cipher.NewGCM(block)if err != nil {return "", err}// Create a nonce. Nonce size must be equal to gcm.NonceSize()nonce := make([]byte, gcm.NonceSize())if _, err = io.ReadFull(rand.Reader, nonce); err != nil {return "", err}// Encrypt the plaintextciphertext := gcm.Seal(nonce, nonce, []byte(plaintext), nil)// Return the hex-encoded ciphertextreturn hex.EncodeToString(ciphertext), nil
}// Decrypt decrypts ciphertext using the given key with AES.
func DecryptWithKey(ciphertext string, key []byte) (string, error) {// Decode the hex-encoded ciphertextciphertextBytes, err := hex.DecodeString(ciphertext)if err != nil {return "", err}// Generate a new AES cipher using the keyblock, err := aes.NewCipher(key)if err != nil {return "", err}// Create a new GCM (Galois/Counter Mode) cipher modegcm, err := cipher.NewGCM(block)if err != nil {return "", err}// The nonce size must be equal to gcm.NonceSize()nonceSize := gcm.NonceSize()if len(ciphertextBytes) < nonceSize {return "", fmt.Errorf("ciphertext too short")}// Split the nonce and the ciphertextnonce, ciphertextBytes := ciphertextBytes[:nonceSize], ciphertextBytes[nonceSize:]// Decrypt the ciphertextplaintext, err := gcm.Open(nil, nonce, ciphertextBytes, nil)if err != nil {return "", err}// Return the plaintextreturn string(plaintext), nil
}

测试代码

func TestAES (t *testing.T) {data := "18645672588"// Key must be either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256key := "FieldEncrypt_123"encrytedData, err := EncryptWithKey(data, []byte(key))if err != nil { fmt.Errorf(err.Error()) }fmt.Println("encrytedData", string(encrytedData))decrytedData, err := DecryptWithKey(encrytedData, []byte(key))if err != nil {fmt.Errorf(err.Error())}fmt.Println("decrytedData", string(decrytedData))
}

注意:key 必须是 16, 24, or 32 字节,方便去选择对应的算法

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com