在Java中,可以使用java.security包提供的类来实现非对称加密算法。常用的非对称加密算法有RSA算法。
以下是一个简单的示例代码,演示如何使用RSA算法进行非对称加密和解密:
import java.security.KeyPair;import java.security.KeyPairGenerator;import java.security.PrivateKey;import java.security.PublicKey;import java.security.Security;import java.security.spec.PKCS8EncodedKeySpec;import java.security.spec.X509EncodedKeySpec;import javax.crypto.Cipher;public class AsymmetricEncryptionExample { public static void main(String[] args) throws Exception { // 生成RSA密钥对 KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048); KeyPair keyPair = keyPairGenerator.generateKeyPair(); PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); // 加密数据 byte[] data = "Hello, World!".getBytes(); byte[] encryptedData = encrypt(data, publicKey); System.out.println("Encrypted data: " + new String(encryptedData)); // 解密数据 byte[] decryptedData = decrypt(encryptedData, privateKey); System.out.println("Decrypted data: " + new String(decryptedData)); } public static byte[] encrypt(byte[] data, PublicKey publicKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); return cipher.doFinal(data); } public static byte[] decrypt(byte[] data, PrivateKey privateKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, privateKey); return cipher.doFinal(data); }}这段代码首先生成RSA密钥对,然后使用公钥对数据进行加密,再使用私钥对加密后的数据进行解密。最后打印出解密后的数据。
需要注意的是,这里使用的是RSA算法,密钥长度为2048位。在实际应用中,应该根据数据的安全性需求选择合适的密钥长度。


