rsa工具类:
package com.sh.util; import com.alibaba.druid.util.StringUtils; import org.apache.commons.codec.binary.Base64; import javax.crypto.Cipher; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.security.*; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.HashMap; import java.util.Map; public class RSAUtil { private static Map<Integer, String> keyMap = new HashMap<Integer, String>(); //用于封装随机产生的公钥与私钥 public static void main(String[] args) throws Exception { //生成公钥和私钥 genKeyPair(); //加密字符串 String message = "df723820"; System.out.println("随机生成的公钥为:" + keyMap.get(0)); System.out.println("随机生成的私钥为:" + keyMap.get(1)); String messageEn = encrypt(message,keyMap.get(0)); System.out.println(message + "\t加密后的字符串为:" + messageEn); String messageDe = decrypt(messageEn,keyMap.get(1)); System.out.println("还原后的字符串为:" + messageDe); } /** * 随机生成密钥对 * @throws NoSuchAlgorithmException */ public static void genKeyPair() throws NoSuchAlgorithmException { // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象 KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA"); // 初始化密钥对生成器,密钥大小为96-1024位 keyPairGen.initialize(1024,new SecureRandom()); // 生成一个密钥对,保存在keyPair中 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 keyMap.put(0,publicKeyString); //0表示公钥 keyMap.put(1,privateKeyString); //1表示私钥 } /** * RSA公钥加密 * * @param str * 加密字符串 * @param publicKey * 公钥 * @return 密文 * @throws Exception * 加密过程中的异常信息 */ public static String encrypt( String str, String publicKey ) throws Exception{ //base64编码的公钥 byte[] decoded = Base64.decodeBase64(publicKey); RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded)); //RSA加密 Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, pubKey); String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8"))); return outStr; } /** * RSA私钥解密 * * @param str * 加密字符串 * @param privateKey * 私钥 * @return 铭文 * @throws Exception * 解密过程中的异常信息 */ public static String decrypt(String str, String privateKey) throws Exception{ //64位解码加密后的字符串 byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8")); //base64编码的私钥 byte[] decoded = Base64.decodeBase64(privateKey); RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded)); //RSA解密 Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, priKey); String outStr = new String(cipher.doFinal(inputByte)); return outStr; } public static String rsaDecrypt(String content, String privateKey, String charset) throws Exception { try { PrivateKey priKey = getPrivateKeyFromPKCS8("RSA", new ByteArrayInputStream(privateKey.getBytes())); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(2, priKey); byte[] encryptedData = StringUtils.isEmpty(charset) ? Base64.decodeBase64(content.getBytes()) : Base64.decodeBase64(content.getBytes(charset)); int inputLen = encryptedData.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; int i = 0; int maxDecryptBlock = 128; if (privateKey.length() > 1000) { maxDecryptBlock = 256; } while (inputLen - offSet > 0) { byte[] cache; if (inputLen - offSet > maxDecryptBlock) { cache = cipher.doFinal(encryptedData, offSet, maxDecryptBlock); } else { cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * maxDecryptBlock; } byte[] decryptedData = out.toByteArray(); out.close(); return StringUtils.isEmpty(charset) ? new String(decryptedData) : new String(decryptedData, charset); } catch (Exception e) { throw new Exception("EncodeContent = " + content + ",charset = " + charset, e); } } public static PrivateKey getPrivateKeyFromPKCS8(String algorithm, InputStream ins) throws Exception { if ((ins == null) || (StringUtils.isEmpty(algorithm))) { return null; } KeyFactory keyFactory = KeyFactory.getInstance(algorithm); byte[] encodedKey = StreamUtils.readText(ins).getBytes(); encodedKey = Base64.decodeBase64(encodedKey); PKCS8EncodedKeySpec ps = new PKCS8EncodedKeySpec(encodedKey); return keyFactory.generatePrivate(ps); } }
AES加密工具类L:
package com.sh.util; import org.apache.commons.codec.binary.Base64; import javax.crypto.*; import javax.crypto.spec.SecretKeySpec; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; /*** * AES加密解密算法 * @author Qfh * 地址:http://blog.csdn.net/hbcui1984/article/details/5201247 */ public class AESUtil { public static String AesKey = "duanRon!@"; //秘钥 /** * 加密 * * @param content 需要加密的内容 * @param password 加密密码 * @return */ public static byte[] encrypt(String content, String password) { try { SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// 创建密码器 //这种加密方式不对 // KeyGenerator kgen = KeyGenerator.getInstance("AES"); // kgen.init(128, new SecureRandom(password.getBytes())); // SecretKey secretKey = kgen.generateKey(); // byte[] enCodeFormat = secretKey.getEncoded(); // SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES"); // Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// 创建密码器 byte[] byteContent = content.getBytes("utf-8"); cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化 byte[] result = cipher.doFinal(byteContent); return result; // 加密 } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } return null; } /**解密 * @param content 待解密内容 * @param password 解密密钥 * @return */ public static byte[] decrypt(byte[] content, String password) { try { SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// 创建密码器 cipher.init(Cipher.DECRYPT_MODE, key);// 初始化 int length = content.length; byte[] result = cipher.doFinal(content); return result; // 加密 } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } return null; } public static void main(String[] args) throws Exception { String content = "小明学会了123456,但是他喜欢abcdeef,可是!@######未知"; String password = "duanRon!@"; //加密 System.out.println("加密前:" + content); byte[] encryptResult = encrypt(content, password); System.out.println("密文:" + new String(encryptResult)); //解密 byte[] decryptResult = decrypt(encryptResult,password); System.out.println("解密后:" + new String(decryptResult)); } /** * base64编码字符串 * * @param data * @return */ public static String bytetobase64(byte[] data) { return Base64.encodeBase64String(data); } public static byte[] base64StoByte(String base64Str){ return Base64.decodeBase64(base64Str); } ///附加 /**将二进制转换成16进制 * @param buf // * @return // */ // public static String parseByte2HexStr(byte buf[]) { // StringBuffer sb = new StringBuffer(); // for (int i = 0; i < buf.length; i++) { // String hex = Integer.toHexString(buf[i] & 0xFF); // if (hex.length() == 1) { // hex = '0' + hex; // } // sb.append(hex.toUpperCase()); // } // return sb.toString(); // } // // /**将16进制转换为二进制 // * @param hexStr // * @return // */ // public static byte[] parseHexStr2Byte(String hexStr) { // if (hexStr.length() < 1) // return null; // byte[] result = new byte[hexStr.length()/2]; // for (int i = 0;i< hexStr.length()/2; i++) { // int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16); // int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16); // result[i] = (byte) (high * 16 + low); // } // return result; // } // // /** // * 使用ASE加密后 // * 加密后返回16进制数据 // * @param temp // * @return // */ // public static String encode(String temp){ // byte[] tempByte = ASEUtil.encrypt(temp, ASEUtil.AesKey); //加密 // temp = ASEUtil.parseByte2HexStr(tempByte); //将二进制转换成16进制 // return temp; // } // // /** // * 解密返回UTF-8字符串 // * @param temp // * @return // */ // public static String decode(String temp){ // byte[] tempByte = ASEUtil.parseHexStr2Byte(temp); //将16进制转换为二进制 // tempByte = ASEUtil.decrypt(tempByte, ASEUtil.AesKey); //解密 // try { // temp = new String(tempByte,"UTF-8"); // }catch(UnsupportedEncodingException e) { // e.printStackTrace(); // } // return temp; // } }
测试方法:
package com.sh.util; import com.alibaba.fastjson.JSONObject; import java.net.URLEncoder; public class JiaMiUtil { /** * * @param js * @param i * @return * @throws Exception * * 1.在这个类里面,进行加解密 * 当调用接口时,首先调用本类 进行解密 参数为0 * 在返回值得时候,先加密后解密 * */ public static JSONObject Encode(JSONObject js,int i,String key) throws Exception { if(i==0){//等于0时 拿到数据 // RSA加密后的AES密码 String sign = js.get("sign") != null ? js.get("sign").toString() : ""; //AES加密后的业务数据 String data = js.get("data") != null ? js.get("data").toString() : ""; //解密 AES密码 私钥 String privateKey=""私钥自定义""; //RSA解密 得到加密前的 ASE明文密码 String aesPassword = RSAUtil.decrypt(sign, privateKey); byte[] bytes = AESUtil.base64StoByte(data);//先将 data 进行base64解码 //ASE解密 得到业务数据 System.out.println("jjjjjjjjjjjjjjjjjjjjjjjjjjjjj"); byte[] decrypt = AESUtil.decrypt(bytes, aesPassword); System.out.println(decrypt); byte[] data2 = AESUtil.decrypt(bytes, aesPassword); //得到业务数据 返回实现类 JSONObject js2 = JSONObject.parseObject(new String(data2)); return js2; } else if(i==1){ //返回数据 进行加密 //公钥 String publicKey="公钥 自定义"; //使用AES 对业务数据加密 //一定要注意 这个passeord一定是十六位的 大坑 byte[] data = AESUtil.encrypt(String.valueOf(js), key); //base64转码 String data2 = AESUtil.bytetobase64(data); //使用RSA 对AES密码加密 得到singn //一定要注意 这个passeord一定是十六位的 String sign = RSAUtil.encrypt(key, publicKey); JSONObject jsonObject = new JSONObject(); jsonObject.put("sign",sign); jsonObject.put("data",data2); return jsonObject; } return null; } public static String getSign(JSONObject js) throws Exception { String privateKey="私钥自定义"; //RSA解密 得到加密前的 ASE明文密码 String sign = js.get("sign") != null ? js.get("sign").toString() : ""; String aesPassword = RSAUtil.decrypt(sign, privateKey); return aesPassword; } public static void main(String[] args) throws Exception { JSONObject aa = new JSONObject(); aa.put("idcard","45646"); aa.put("bdczmh","就好好看好看好看"); Object encode = JiaMiUtil.Encode(aa, 1,"U0JJTG758AZhh28z"); System.out.println(encode); JSONObject jsonObject = JSONObject.parseObject(String.valueOf(encode)); Object encode2 = JiaMiUtil.Encode(jsonObject, 0,"U0JJTG758AZhh28z"); System.out.println(encode2); // } }