以下是一个简单的
Java RSA 工具类的示例代码:
javaimportjava.security.Key;importjava.security.KeyFactory;importjava.security.KeyPair;importjava.security.KeyPairGenerator;importjava.security.PrivateKey;importjava.security.PublicKey;importjava.security.spec.PKCS8EncodedKeySpec;importjava.security.spec.X509EncodedKeySpec;importjavax.crypto.Cipher;import org.apache.commons.codec.binary.Base64;public classRSAUtils {private static final StringRSA_ALGORITHM = "RSA";public static KeyPair generateKeyPair() throws Exception {KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA_ALGORITHM);keyPairGenerator.initialize(2048);return keyPairGenerator.genKeyPair();}public static String encrypt(String plainText, PublicKey publicKey) throws Exception {Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);cipher.init(Cipher.ENCRYPT_MODE, publicKey);byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());return Base64.encodeBase64String(encryptedBytes);}public static String decrypt(String encryptedText, PrivateKey privateKey) throws Exception {Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);cipher.init(Cipher.DECRYPT_MODE, privateKey);byte[] encryptedBytes = Base64.decodeBase64(encryptedText);byte[] decryptedBytes = cipher.doFinal(encryptedBytes);return new String(decryptedBytes);}public static PublicKey getPublicKey(byte[] publicKeyBytes) throws Exception {X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);return keyFactory.generatePublic(keySpec);}public static PrivateKey getPrivateKey(byte[] privateKeyBytes) throws Exception {PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);return keyFactory.generatePrivate(keySpec);}}
使用示例:
javapublic class Main {public static void main(String[] args) {try {// 生成密钥对KeyPair keyPair =RSAUtils.generateKeyPair();PublicKey publicKey = keyPair.getPublic();PrivateKey privateKey = keyPair.getPrivate();//加密String plainText = "Hello,RSA!";String encryptedText =RSAUtils.encrypt(plainText, publicKey);System.out.println("Encrypted Text: " + encryptedText);//解密String decryptedText =RSAUtils.decrypt(encryptedText, privateKey);System.out.println("Decrypted Text: " + decryptedText);} catch (Exception e) {e.printStackTrace();}}}
请注意,这只是一个简单的示例,用于演示
RSA 加密和
解密过程。在实际应用中,您需要更加严格的错误处理和安全性措施。
版权声明:
本文来源网络,所有图片文章版权属于原作者,如有侵权,联系删除。
本文网址:https://www.mushiming.com/mjsbk/5021.html