在 Java 中實(shí)現(xiàn)非對(duì)稱加密解密通常使用公鑰和私鑰進(jìn)行加密和解密操作。下面是一個(gè)簡單的示例:
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048);
KeyPair keyPair = keyGen.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] input = "Hello World".getBytes();
byte[] encryptedBytes = cipher.doFinal(input);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
String decrypted = new String(decryptedBytes);
System.out.println("Decrypted message: " + decrypted);
需要注意的是,非對(duì)稱加密解密過程中需要使用相應(yīng)的公鑰和私鑰進(jìn)行操作,并且保證公鑰加密的數(shù)據(jù)只能由私鑰解密,私鑰加密的數(shù)據(jù)只能由公鑰解密。