共計(jì) 1639 個(gè)字符,預(yù)計(jì)需要花費(fèi) 5 分鐘才能閱讀完成。
Java 中可以使用 Java 內(nèi)置的加密庫 javax.crypto 來實(shí)現(xiàn) RSA 算法。
下面是一個(gè)簡(jiǎn)單的 RSA 加密和解密的示例代碼:
import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
public class RSAExample {public static void main(String[] args) throws Exception {String originalText = "Hello, RSA!";
// 生成公私密鑰對(duì)
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
// 使用公鑰加密數(shù)據(jù)
byte[] encryptedBytes = encrypt(originalText, publicKey);
// 使用私鑰解密數(shù)據(jù)
String decryptedText = decrypt(encryptedBytes, privateKey);
System.out.println("Original Text: " + originalText);
System.out.println("Encrypted Text: " + Base64.getEncoder().encodeToString(encryptedBytes));
System.out.println("Decrypted Text: " + decryptedText);
}
public static byte[] encrypt(String text, PublicKey publicKey) throws Exception {Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(text.getBytes());
}
public static String decrypt(byte[] encryptedBytes, PrivateKey privateKey) throws Exception {Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes);
}
}
在這個(gè)示例代碼中,首先生成一個(gè) 2048 位的 RSA 公私鑰對(duì),然后使用公鑰加密原始文本,再使用私鑰解密加密后的數(shù)據(jù)。最后輸出原始文本、加密后的文本和解密后的文本。
需要注意的是,這里使用了 Base64 編碼來將加密后的文本以字符串的形式輸出,方便觀察。在實(shí)際應(yīng)用中,可以根據(jù)需要選擇合適的方式來存儲(chǔ)和傳輸加密后的數(shù)據(jù)。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完