Java RSA非对称加密算法demo工具类
安全性:512位的密钥被视为不安全的;768位的密钥不用担心受到除了国家安全管理(NSA)外的其他事物的危害;1024位的密钥几乎是安全的。
运算速度:慢,RSA的速度比对应同样安全级别的对称密码算法要慢1000倍左右
public class RSAUtil {
public static Map<String,String> map = new HashMap<>();
public static final int KEY_SIZE = 1024;
public static void createKey() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(KEY_SIZE, new SecureRandom());
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
map.put("publicKey", publicKeyString);
map.put("privateKey", privateKeyString);
}
public static String encode(String encodeStr,String publicKey) {
try {
byte[] decode = Base64.decodeBase64(publicKey);
RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decode));
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
String out = Base64.encodeBase64String(cipher.doFinal(encodeStr.getBytes(StandardCharsets.UTF_8)));
return out;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
public static String decode(String decodeStr,String privateKey) {
try{
byte[] bytes = Base64.decodeBase64(decodeStr.getBytes(StandardCharsets.UTF_8));
byte[] decode = Base64.decodeBase64(privateKey);
RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decode));
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE,priKey);
String out = new String(cipher.doFinal(bytes));
return out;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
public static void main(String[] args) throws Exception {
System.out.println("-------------RSA加密 非对称加密算法---开始--------");
RSAUtil.createKey();
String str = "你好,中国!";
String encodeStr = RSAUtil.encode(str,RSAUtil.map.get("publicKey"));
String decodeStr = RSAUtil.decode(encodeStr,RSAUtil.map.get("privateKey"));
System.out.println("待加密明文:"+str);
System.out.println("已加密密文:"+encodeStr);
System.out.println("已解密明文:"+decodeStr);
System.out.println("公钥:"+RSAUtil.map.get("publicKey").length());
System.out.println("秘钥:"+RSAUtil.map.get("privateKey").length());
System.out.println("-------------RSA加密 非对称加密算法---结束--------");
}