{"original_type": "transaction", // 加密前的对象类型"algorithm": "AEAD_AES_256_GCM", // 加密算法// Base64编码后的密文"ciphertext": "...",// 加密使用的随机串初始化向量)"nonce": "...",// 附加数据包(可能为空)"associated_data": ""}
import java.io.IOException;import java.security.GeneralSecurityException;import java.security.InvalidAlgorithmParameterException;import java.security.InvalidKeyException;import java.security.NoSuchAlgorithmException;import java.util.Base64;import javax.crypto.Cipher;import javax.crypto.NoSuchPaddingException;import javax.crypto.spec.GCMParameterSpec;import javax.crypto.spec.SecretKeySpec;public class AesUtil {static final int KEY_LENGTH_BYTE = 32;static final int TAG_LENGTH_BIT = 128;private final byte[] aesKey;public AesUtil(byte[] key) {if (key.length != KEY_LENGTH_BYTE) {throw new IllegalArgumentException("无效的ApiV3Key,长度必须为32个字节");}this.aesKey = key;}public String decryptToString(byte[] associatedData, byte[] nonce, String ciphertext)throws GeneralSecurityException, IOException {try {Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");SecretKeySpec key = new SecretKeySpec(aesKey, "AES");GCMParameterSpec spec = new GCMParameterSpec(TAG_LENGTH_BIT, nonce);cipher.init(Cipher.DECRYPT_MODE, key, spec);cipher.updateAAD(associatedData);return new String(cipher.doFinal(Base64.getDecoder().decode(ciphertext)), "utf-8");} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {throw new IllegalStateException(e);} catch (InvalidKeyException | InvalidAlgorithmParameterException e) {throw new IllegalArgumentException(e);}}}
from cryptography.hazmat.primitives.ciphers.aead import AESGCMimport base64def decrypt(nonce, ciphertext, associated_data):key = "Your32Apiv3Key"key_bytes = str.encode(key)nonce_bytes = str.encode(nonce)ad_bytes = str.encode(associated_data)data = base64.b64decode(ciphertext)aesgcm = AESGCM(key_bytes)return aesgcm.decrypt(nonce_bytes, data, ad_bytes)
// DecryptGCM decrypts ciphertext using AES-256-GCMfunc DecryptGCM(ciphertext []byte, key []byte, nonce []byte, additionalData []byte) ([]byte, error) {block, err := aes.NewCipher(key)if err != nil {return nil, err}gcm, err := cipher.NewGCM(block)if err != nil {return nil, err}plaintext, err := gcm.Open(nil, nonce, ciphertext, additionalData)if err != nil {return nil, err}return plaintext, nil}
文档反馈