話不多說,直接開擼
public class RSAUtils { private static String PUB_KEY = "xxxxxx"; private static String PRIV_KEY ="xxxxxx"; public static Map<Integer, String> genKeyPair() { Map<Integer, String> keyMap = new HashMap<Integer, String>(); // 用於封裝隨機產生的公鑰與私鑰 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) { return null; } return keyMap; } /** * RSA公鑰加密 * * @param str * 需要加密的字符串 * @param publicKey * 公鑰 * @return 公鑰加密后的內容 */ public static String encrypt(String str) { String outStr = null; try { // base64編碼的公鑰 byte[] decoded = Base64.decodeBase64(PUB_KEY); RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA") .generatePublic(new X509EncodedKeySpec(decoded)); // RSA加密 Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, pubKey); outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8"))); } catch (Exception e) { } return outStr; } /** * RSA私鑰解密 * * @param str * 加密字符串 * @param privateKey * 私鑰 * @return 私鑰解密后的內容 */ public static String decrypt(String str) { String outStr = null; try { // 64位解碼加密后的字符串 byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8")); // base64編碼的私鑰 byte[] decoded = Base64.decodeBase64(PRIV_KEY); 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) { } return outStr; } }
這個類有一個生成公鑰和私鑰的方法,還有一個公鑰加密和私鑰解密的方法.我們將公鑰放在前端用來加密,私鑰放在后端用來解密.
前端需要引入jsencrypt.min.js
下載地址: http://travistidwell.com/jsencrypt/
加密方法:
就可以實現前端加密后端解密了