配合 AES 加解密如何使用
时间: 2023-07-20 15:22:34 浏览: 39
使用 ECDH 算法生成的共享密钥可以被用于对称加密算法,如 AES 加密算法。以下是使用 ECDH 生成的共享密钥对数据进行 AES 加解密的代码示例:
```
import javax.crypto.*;
import javax.crypto.spec.*;
public class AESUtil {
public static byte[] encrypt(byte[] plainText, byte[] key) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
return cipher.doFinal(plainText);
}
public static byte[] decrypt(byte[] cipherText, byte[] key) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
return cipher.doFinal(cipherText);
}
}
public class ECDHWithAES {
public static void main(String[] args) throws Exception {
// 生成公私钥对
KeyPair keyPairA = ECDHUtil.generateKeyPair();
KeyPair keyPairB = ECDHUtil.generateKeyPair();
PublicKey publicKeyA = keyPairA.getPublic();
PrivateKey privateKeyA = keyPairA.getPrivate();
PublicKey publicKeyB = keyPairB.getPublic();
PrivateKey privateKeyB = keyPairB.getPrivate();
// A 计算共享密钥
byte[] sharedSecretA = ECDHUtil.generateSharedSecret(privateKeyA, publicKeyB);
// B 计算共享密钥
byte[] sharedSecretB = ECDHUtil.generateSharedSecret(privateKeyB, publicKeyA);
// 对称加密
byte[] plainText = "Hello, world!".getBytes();
byte[] cipherTextA = AESUtil.encrypt(plainText, sharedSecretA);
byte[] cipherTextB = AESUtil.encrypt(plainText, sharedSecretB);
byte[] decryptedTextA = AESUtil.decrypt(cipherTextB, sharedSecretA);
byte[] decryptedTextB = AESUtil.decrypt(cipherTextA, sharedSecretB);
System.out.println(new String(decryptedTextA)); // 输出 "Hello, world!"
System.out.println(new String(decryptedTextB)); // 输出 "Hello, world!"
}
}
```
在这个示例中,首先生成了两对公私钥对,分别属于 A 和 B 两个实体。A 和 B 分别计算出共享密钥 `sharedSecretA` 和 `sharedSecretB`,然后使用这两个密钥对数据进行加解密。每个实体都可以使用自己的私钥和对方的公钥计算出共享密钥,并且这两个共享密钥是相同的,因此数据可以在 A 和 B 之间安全地传输。在这个示例中,使用了 Java 内置的 AES 加密算法,密钥长度为 128 位。