import javax.crypto.Cipher; import java.io.InputStream; import java.security.*; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; /** *@Author 黄俊聪 *@Date 2017/12/15 17:29 *@Description 非对称加密解密工具类 */ public class RSAUtil { /** * 私钥字符串 */ private static String PRIVATE_KEY =""; /** * 公钥字符串 */ private static String PUBLIC_KEY ="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCbpmF28RgRDMduGSDhB2CD 0CiOFYytTGxYQuffq5RTgdoxxsE/3dgE+qQaDsTG1yzOwwCq7X3Xye7MZlcL 5SjNiLzh5tSEG7qyAVUfAgit1gYczWM+sTg+G7pnHa/omukvOfEeWceS8P35 Xt3ShqIeKfGxU4UIdiqKonBrQtYT/wIDAQAB"; public static final String KEY_ALGORITHM = "RSA"; /** * 读取密钥字符串 * @throws Exception */ public static void convert() throws Exception { byte[] data = null; try { InputStream is = RSAUtil.class.getResourceAsStream("/enc_pri"); int length = is.available(); data = new byte[length]; is.read(data); } catch (Exception e) { } String dataStr = new String(data); try { PRIVATE_KEY = dataStr; } catch (Exception e) { } if (PRIVATE_KEY == null) { throw new Exception("Fail to retrieve key"); } } /** *@Author 黄俊聪 *@Date 2017/12/15 18:09 *@Description RSA私钥解密 */ public static byte[] decryptByPrivateKey(byte[] data) throws Exception { //从流中读取密钥字符串 convert(); //base64解码 byte[] keyBytes = Base64Util.decode(PRIVATE_KEY); //用PKCS8EncodedKeySpec这种模式解密 PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); //选用RSA非对称算法进行解密 KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); //获取私钥 Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec); //用RSA算法获取Cipher Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); //初始化解密模式 cipher.init(Cipher.DECRYPT_MODE,privateKey); return cipher.doFinal(data); } /** *@Author 黄俊聪 *@Date 2017/12/15 18:18 *@Description RSA公钥加密 */ public static byte[] encryptByPublicKey(byte[] data, String key) throws Exception { //base64解码 byte[] keyBytes = Base64Util.decode(key); //用X509EncodedKeySpec这种模式加密 X509EncodedKeySpec pkcs8KeySpec = new X509EncodedKeySpec(keyBytes); //选用RSA非对称算法进行加密 KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); //获取公钥 Key publicKey = keyFactory.generatePublic(pkcs8KeySpec); //用RSA算法获取Cipher Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); //初始化加密模式 cipher.init(Cipher.ENCRYPT_MODE, publicKey); return cipher.doFinal(data); } public static void main(String[] args) throws Exception { // //根据RSA生成一对key,即公钥和私钥 // KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM); // //设置key的大小,1024K // keyPairGenerator.initialize(1024); // //获取key对的对象 // KeyPair keyPair = keyPairGenerator.generateKeyPair(); // //获取私钥 // PrivateKey privateKey = keyPair.getPrivate(); // //获取公钥 // PublicKey publicKey = keyPair.getPublic(); // System.out.println(Base64Util.encode(publicKey.getEncoded())); // System.out.println(Base64Util.encode(privateKey.getEncoded())); String data = "黄俊聪来了"; byte[] enResult = encryptByPublicKey(data.getBytes("UTF-8"), PUBLIC_KEY); System.out.println(enResult.toString()); byte[] deResult = decryptByPrivateKey(enResult); System.out.println(new String(deResult,"UTF-8")); } //Base64工具类 import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; public class Base64Util { private static final char[] legalChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" .toCharArray(); public static String encode(byte[] data) { byte start = 0; int len = data.length; StringBuffer buf = new StringBuffer(data.length * 3 / 2); int end = len - 3; int i = start; int n = 0; int d; while (i <= end) { d = (data[i] & 255) << 16 | (data[i + 1] & 255) << 8 | data[i + 2] & 255; buf.append(legalChars[d >> 18 & 63]); buf.append(legalChars[d >> 12 & 63]); buf.append(legalChars[d >> 6 & 63]); buf.append(legalChars[d & 63]); i += 3; if (n++ >= 14) { n = 0; buf.append(" "); } } if (i == start + len - 2) { d = (data[i] & 255) << 16 | (data[i + 1] & 255) << 8; buf.append(legalChars[d >> 18 & 63]); buf.append(legalChars[d >> 12 & 63]); buf.append(legalChars[d >> 6 & 63]); buf.append("="); } else if (i == start + len - 1) { d = (data[i] & 255) << 16; buf.append(legalChars[d >> 18 & 63]); buf.append(legalChars[d >> 12 & 63]); buf.append("=="); } return buf.toString(); } private static int decode(char c) { if (c >= 65 && c <= 90) { return c - 65; } else if (c >= 97 && c <= 122) { return c - 97 + 26; } else if (c >= 48 && c <= 57) { return c - 48 + 26 + 26; } else { switch (c) { case '+': return 62; case '/': return 63; case '=': return 0; default: throw new RuntimeException("unexpected code: " + c); } } } public static byte[] decode(String s) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { decode(s, bos); } catch (IOException var5) { throw new RuntimeException(); } byte[] decodedBytes = bos.toByteArray(); try { bos.close(); bos = null; } catch (IOException var4) { System.err.println("Error while decoding BASE64: " + var4.toString()); } return decodedBytes; } private static void decode(String s, OutputStream os) throws IOException { int i = 0; int len = s.length(); while (true) { while (i < len && s.charAt(i) <= 32) { ++i; } if (i == len) { break; } int tri = (decode(s.charAt(i)) << 18) + (decode(s.charAt(i + 1)) << 12) + (decode(s.charAt(i + 2)) << 6) + decode(s.charAt(i + 3)); os.write(tri >> 16 & 255); if (s.charAt(i + 2) == 61) { break; } os.write(tri >> 8 & 255); if (s.charAt(i + 3) == 61) { break; } os.write(tri & 255); i += 4; } } }