feat: 增加商户消息加密密钥管理
This commit is contained in:
@@ -6,10 +6,56 @@
|
||||
package encrypt
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"github.com/forgoer/openssl"
|
||||
"io"
|
||||
)
|
||||
|
||||
const AESGCMKeySize = 32
|
||||
|
||||
// AESGCMEncrypt encrypts plaintext with AES-256-GCM and a fresh random nonce.
|
||||
func AESGCMEncrypt(plaintext, key, additionalData []byte) (ciphertext, nonce []byte, err error) {
|
||||
if len(key) != AESGCMKeySize {
|
||||
return nil, nil, fmt.Errorf("AES-256-GCM key must be %d bytes", AESGCMKeySize)
|
||||
}
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
nonce = make([]byte, gcm.NonceSize())
|
||||
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return gcm.Seal(nil, nonce, plaintext, additionalData), nonce, nil
|
||||
}
|
||||
|
||||
// AESGCMDecrypt authenticates and decrypts ciphertext encrypted by AESGCMEncrypt.
|
||||
func AESGCMDecrypt(ciphertext, nonce, key, additionalData []byte) ([]byte, error) {
|
||||
if len(key) != AESGCMKeySize {
|
||||
return nil, fmt.Errorf("AES-256-GCM key must be %d bytes", AESGCMKeySize)
|
||||
}
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(nonce) != gcm.NonceSize() {
|
||||
return nil, fmt.Errorf("AES-GCM nonce must be %d bytes", gcm.NonceSize())
|
||||
}
|
||||
return gcm.Open(nil, nonce, ciphertext, additionalData)
|
||||
}
|
||||
|
||||
// AesECBEncrypt 加密
|
||||
func AesECBEncrypt(src, key []byte) (dst []byte, err error) {
|
||||
return openssl.AesECBEncrypt(src, key, openssl.PKCS7_PADDING)
|
||||
|
||||
Reference in New Issue
Block a user