自学内容网 自学内容网

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 key
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}

// Create a new GCM (Galois/Counter Mode) cipher mode
gcm, 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 plaintext
ciphertext := gcm.Seal(nonce, nonce, []byte(plaintext), nil)

// Return the hex-encoded ciphertext
return 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 ciphertext
ciphertextBytes, err := hex.DecodeString(ciphertext)
if err != nil {
return "", err
}

// Generate a new AES cipher using the key
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}

// Create a new GCM (Galois/Counter Mode) cipher mode
gcm, 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 ciphertext
nonce, ciphertextBytes := ciphertextBytes[:nonceSize], ciphertextBytes[nonceSize:]

// Decrypt the ciphertext
plaintext, err := gcm.Open(nil, nonce, ciphertextBytes, nil)
if err != nil {
return "", err
}

// Return the plaintext
return 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-256
key := "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 字节,方便去选择对应的算法


原文地址:https://blog.csdn.net/chechenshi/article/details/140612867

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!