package cn.com.goldenwater.dcproj.utils; import org.apache.commons.codec.binary.Base64; import org.apache.commons.collections.map.HashedMap; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import javax.crypto.Cipher; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.SecureRandom; 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; /** * Created by 61618 on 2019/4/11. */ public class Encryption { @Autowired private RedisTemplate redisTemplate; public static Map EncryptionPwd(String pwd) throws Exception { Map map = new HashedMap(); Map keyMap = genKeyPair(); String messageEn = encrypt(pwd, keyMap.get(0)); map.put("pubKey", keyMap.get(0)); map.put("priKey", keyMap.get(1)); map.put("pwd", messageEn); return map; } public static Map genKeyPair(){ Map keyMap = new HashMap<>(); try{ // 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表示私钥 }catch (Exception e){ e.printStackTrace(); } return keyMap; } 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; } public static String decrypt(String str, String privateKey){ String outStr = ""; try{ if(str.contains(" ")){ str = str.replaceAll(" ","+"); } // 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); outStr = new String(cipher.doFinal(inputByte)); }catch (Exception e){ e.printStackTrace(); } return outStr; } }