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 字节,方便去选择对应的算法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值