Java RSA 加解密:前端加密,后端解密 (支持 JDK6)
在Java中,可以使用Java Cryptography Architecture(JCA)和Java Cryptography Extension(JCE)提供的API来实现RSA加解密。
以下是一个简单的示例:
前端加密:
import javax.crypto.Cipher;
import java.security.KeyPairGenerator;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;
public class RASUtils {
private static final String ALGORITHM = "RSA";
private static final int KEY_SIZE = 2048;
public static String encrypt(String message, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedMessage = cipher.doFinal(message.getBytes());
return Base64.getEncoder().encodeToString(encryptedMessage);
}
public static KeyPair generateKeyPair() throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
keyPairGenerator.initialize(KEY_SIZE);
return keyPairGenerator.generateKeyPair();
}
}
后端解密:
import javax.crypto.Cipher;
import java.security.PrivateKey;
import java.util.Base64;
public class RASUtils {
private static final String ALGORITHM = "RSA";
public static String decrypt(String encryptedMessage, PrivateKey privateKey) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedMessage = cipher.doFinal(Base64.getDecoder().decode(encryptedMessage));
return new String(decryptedMessage);
}
}
使用示例:
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
public class Main {
public static void main(String[] args) throws Exception {
// 生成公私钥对
KeyPair keyPair = RASUtils.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
// 前端加密密码
String password = "myPassword";
String encryptedPassword = RASUtils.encrypt(password, publicKey);
// 后端解密密码
String decryptedPassword = RASUtils.decrypt(encryptedPassword, privateKey);
System.out.println("原始密码:" + password);
System.out.println("加密后的密码:" + encryptedPassword);
System.out.println("解密后的密码:" + decryptedPassword);
}
}
**注意:**在使用JDK6时,需要下载并安装Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files,以支持更长的密钥大小。
原文地址: https://www.cveoy.top/t/topic/oe1T 著作权归作者所有。请勿转载和采集!