java中RSA加密解密的使用
作为常用的非对称加密算法,本篇文章大致记录一下,在java代码中如何生成RSA的密钥对以及加密解密的使用。
1、生成密钥对
public class RSAUtils { // 填充方式 public static final String RSA_ALGORITHM_NOPADDING = "RSA"; public static final String RSA_ALGORITHM = "RSA/ECB/PKCS1Padding"; /** * 生成密钥对 * @return */ public static Map<String, String> createKeyPairs() { try { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA_ALGORITHM_NOPADDING); keyPairGenerator.initialize(2048); KeyPair keyPair = keyPairGenerator.generateKeyPair(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); return new HashMap<String, String>(){{ put("publicKey", Base64.encodeBase64String(publicKey.getEncoded())); put("privateKey", Base64.encodeBase64String(privateKey.getEncoded())); }}; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } }
2、加密
/** * 通过公钥对数据进行加密 * @param publicKeyStr * @param data * @return */ public static String encryptRSADefault(String publicKeyStr, String data) { try { KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM_NOPADDING); // 指定算法,返回keyFactory对象 byte[] publicKeyByte = Base64.decodeBase64(publicKeyStr); // 或:Base64.decodeBase64(publicKeyStr.getBytes()) X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKeyByte); // 创建X509编码公钥规范 PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec); // 根据X5090编码密钥规范产生公钥对象 Cipher cipher = Cipher.getInstance(RSA_ALGORITHM_NOPADDING); // 根据算法名称,生成密码对象 cipher.init(Cipher.ENCRYPT_MODE, publicKey); // 使用公钥初始化cipher对象(encrypt加密模式) byte[] encryptByte = cipher.doFinal(data.getBytes()); // 对数据进行加密 return Base64.encodeBase64String(encryptByte); // 将字节数组,经过base64编码后,以US-ASCII编码输出为字符串 } catch (Exception e) { e.printStackTrace(); } return null; }
3、解密
public static String decryptRSADefault(String privateKeyStr, String data) { try { KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM_NOPADDING); byte[] privateKeyByte = Base64.decodeBase64(privateKeyStr); PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKeyByte); // 密钥为pkcs8格式 PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec); // 生成私钥对象 Cipher cipher = Cipher.getInstance(RSA_ALGORITHM_NOPADDING); cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] decryptByte = cipher.doFinal(Base64.decodeBase64(data.getBytes())); return new String(decryptByte, "UTF-8"); } catch (Exception e) { e.printStackTrace(); } return null; }
4、测试
public static void main(String[] args) { Map<String, String> keyPairs = createKeyPairs(); System.out.println("公钥:\n" + keyPairs.get("publicKey")); System.out.println("私钥:\n" + keyPairs.get("privateKey")); if (null != keyPairs) { String encryptMsg = RSAUtils.encryptRSADefault(keyPairs.get("publicKey"), "hello world"); System.out.println("加密后的内容:" + encryptMsg); String decryptMsg = RSAUtils.decryptRSADefault(keyPairs.get("privateKey"), encryptMsg); System.out.println("解密后的内容:" + decryptMsg); }
输出结果: