RSA非对称加密解密

mac2025-11-18  4

生成公钥私钥对

package com.etone.common.util; import sun.misc.BASE64Encoder; import java.io.FileOutputStream; import java.io.ObjectOutputStream; import java.security.*; /** * Copyright (C), 2011-2018 {company} * FileName: com.huateng.util.KeyPairGenUtil.java * Author: xxx * Email: xxx * Date: 2018/6/6 14:01 * Description: * History: * <Author> <Time> <version> <desc> * {xxx} 14:01 1.0 Create */ public class KeyPairGenUtil { /** 指定加密算法为RSA */ private static final String ALGORITHM = "RSA"; /** 密钥长度,用来初始化 */ private static final int KEYSIZE = 2048; /** 指定公钥存放文件 */ private static String PUBLIC_KEY_FILE = "merkey.public"; /** 指定私钥存放文件 */ private static String PRIVATE_KEY_FILE = "merkey.private"; public static void main(String[] args) throws Exception { // 生成公私钥文件 generateKeyPair(); // 生成公私钥字符串 genKeyPair(); } /** * 生成密钥对 * @throws Exception */ public static void generateKeyPair() throws Exception { // /** RSA算法要求有一个可信任的随机数源 */ // SecureRandom secureRandom = new SecureRandom(); /** 为RSA算法创建一个KeyPairGenerator对象 */ KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM); /** 利用上面的随机数据源初始化这个KeyPairGenerator对象 */ // keyPairGenerator.initialize(KEYSIZE, secureRandom); keyPairGenerator.initialize(KEYSIZE); /** 生成密匙对 */ KeyPair keyPair = keyPairGenerator.generateKeyPair(); /** 得到公钥 */ Key publicKey = keyPair.getPublic(); /** 得到私钥 */ Key privateKey = keyPair.getPrivate(); ObjectOutputStream oos1 = null; ObjectOutputStream oos2 = null; try { /** 用对象流将生成的密钥写入文件 */ oos1 = new ObjectOutputStream(new FileOutputStream(PUBLIC_KEY_FILE)); oos2 = new ObjectOutputStream(new FileOutputStream(PRIVATE_KEY_FILE)); oos1.writeObject(publicKey); oos2.writeObject(privateKey); } catch (Exception e) { throw e; } finally { /** 清空缓存,关闭文件输出流 */ if(oos1 != null){ oos1.close(); } if(oos2 != null){ oos2.close(); } } } public static void genKeyPair() throws NoSuchAlgorithmException { /** RSA算法要求有一个可信任的随机数源 */ SecureRandom secureRandom = new SecureRandom(); /** 为RSA算法创建一个KeyPairGenerator对象 */ KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM); /** 利用上面的随机数据源初始化这个KeyPairGenerator对象 */ keyPairGenerator.initialize(KEYSIZE, secureRandom); //keyPairGenerator.initialize(KEYSIZE); /** 生成密匙对 */ KeyPair keyPair = keyPairGenerator.generateKeyPair(); /** 得到公钥 */ Key publicKey = keyPair.getPublic(); /** 得到私钥 */ Key privateKey = keyPair.getPrivate(); byte[] publicKeyBytes = publicKey.getEncoded(); byte[] privateKeyBytes = privateKey.getEncoded(); String publicKeyBase64 = new BASE64Encoder().encode(publicKeyBytes); String privateKeyBase64 = new BASE64Encoder().encode(privateKeyBytes); System.out.println("publicKeyBase64.length():" + publicKeyBase64.length()); System.out.println("publicKeyBase64:" + publicKeyBase64); System.out.println("privateKeyBase64.length():" + privateKeyBase64.length()); System.out.println("privateKeyBase64:" + privateKeyBase64); } }

加密解密

package com.etone.common.util; import javax.crypto.Cipher; import java.security.KeyFactory; import java.security.PrivateKey; import java.security.PublicKey; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.Base64; public class RSAUtil { //非对称密钥算法 private static final String KEY_ALGORITHM = "RSA"; //字符编码 private static final String CHARSET = "UTF-8"; /** * 私钥加密 * * @param data 待加密数据 * @param privateKey 私钥字节数组 * @return byte[] 加密数据 */ public static byte[] encryptByPrivateKey(byte[] data, byte[] privateKey) throws Exception { //实例化密钥工厂 KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); //生成私钥 PrivateKey key = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privateKey)); //数据加密 Cipher cipher = Cipher.getInstance(KEY_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, key); return cipher.doFinal(data); } /** * 私钥加密 * * @param data 待加密数据 * @param privateKey Base64编码的私钥 * @return String Base64编码的加密数据 */ public static String encryptByPrivateKey(String data, String privateKey) throws Exception { byte[] key = Base64.getDecoder().decode(privateKey); return Base64.getEncoder().encodeToString(encryptByPrivateKey(data.getBytes(CHARSET), key)); } /** * 公钥解密 * * @param data 待解密数据 * @param publicKey 公钥字节数组 * @return byte[] 解密数据 */ public static byte[] decryptByPublicKey(byte[] data, byte[] publicKey) throws Exception { //实例化密钥工厂 KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); //产生公钥 PublicKey key = keyFactory.generatePublic(new X509EncodedKeySpec(publicKey)); //数据解密 Cipher cipher = Cipher.getInstance(KEY_ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, key); return cipher.doFinal(data); } /** * 公钥解密 * * @param data Base64编码的待解密数据 * @param publicKey Base64编码的公钥 * @return String 解密数据 */ public static String decryptByPublicKey(String data, String publicKey) throws Exception { byte[] key = Base64.getDecoder().decode(publicKey); return new String(decryptByPublicKey(Base64.getDecoder().decode(data), key), CHARSET); } public static void main(String[] args) throws Exception { String publicKey="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCVgd/h3JK4XgLmFMVRy64actnmaAgZBRZkz/brILRLuWlnBNxYWeZpUgT6ZTSHu2Krl4nPaYrFkBqrI9vGtXkFkclU" + "6C0rrZ8/hCGgdfwt+vkRt+W1Tp7uKmtV9RGSWGaDpynb6mCSgvGbjsFrqTKaV4yy" + "LZVluiaVv1+FumDpMQIDAQAB"; String privateKey="MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJWB3+HckrheAuYU" + "xVHLrhpy2eZoCBkFFmTP9usgtEu5aWcE3FhZ5mlSBPplNIe7YquXic9pisWQGqsj" + "28a1eQWRyVToLSutnz+EIaB1/C36+RG35bVOnu4qa1X1EZJYZoOnKdvqYJKC8ZuO" + "wWupMppXjLItlWW6JpW/X4W6YOkxAgMBAAECgYAbiO3YxSzoc7gI8+5bYC3ShTCI" + "dMR5ByzWqE6Lg1xxTdaRuJ10UCpVX1u3WghQrzw+6gvhfUinliCzQElr0WRWUDDa" + "KkPXdrAJlIKwfO3Jq6CVeeZReRWTANSi532ViW0OoEh0XKJn+9VciEsWDX9OFFCi" + "O/xfdcn6JnapUiiHoQJBAMUKN4wPab8VMjQzvwz3czjnl7ct2KocLKhCXEo//wlZ" + "1+GvNKQvK3p/nvT0DmiNaBJ0R5i8CzC10ejxw6p/4v0CQQDCPojTkZFZvkOummu0" + "efaqmuQ11Nj2/nLP7BEfVXo3tNHV31fMxdtMisB1KPuBmk25I6VRpOSQynuheOs7" + "1BdFAkEAvAd/8nxS4TIM8pve2TTaE5eNxBRQCiVQyFBrWb+wVPATfx5/EZ6h0wgu" + "XHr5tPQcOGAWYr4vv5ACfFUZ736S0QJBAI5n6Eorq4M+0UH95j6PN/8FxY+Nt28F" + "RskWycrOEOcsQrZoomb3G3q3MrfyTslKhfbYokgD+qoIOLE+BD99k30CQECKGSjm" + "k3vj6b0hXPWPAr2t3kc/1WsSbUfVxJywbqGo9G07eQ+k+8P+CxHNk2COUmvmhj3P" + "uZhSfazUVFEdC4w="; String data="123456"; String prData=encryptByPrivateKey(data,privateKey); System.out.println("密文:"+prData); String puData=decryptByPublicKey(prData,publicKey); System.out.println("明文:"+puData); } }

实例

pn =RSAUtil.decryptByPublicKey(pn,hkPublicKey); ytBn =RSAUtil.decryptByPublicKey(ytBn,hkPublicKey); accessid =RSAUtil.decryptByPublicKey(accessid,hkPublicKey); paymentKey =RSAUtil.decryptByPublicKey(paymentKey,hkPublicKey); agentNo =RSAUtil.decryptByPublicKey(agentNo,hkPublicKey);

 

 

最新回复(0)