Java 加密解密工具類

RSA非對稱加密
package com.chitic.supplywater.common.service; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.security.Key; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Signature; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.Arrays; import javax.crypto.Cipher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; @SuppressWarnings("restriction") public class RSACoder { private static final Logger logger = LoggerFactory.getLogger(RSACoder.class); /** * 加密方式 */
    public static final String KEY_ALGORITHM = "RSA"; /** * 簽名方式 */
    public static final String KEY_SIGN = "SHA1withRSA"; /** * RSA最大加密明文大小 */
    public static final int MAX_ENCRYPT_BLOCK = 117; /** * RSA最大解密密文大小 */
    public static final int MAX_DECRYPT_BLOCK = 128; /** * RSA最大解密密文大小 */
    public static final int MAX_DECRYPT_BLOCK_256 = 256; /* * static { KeyPairGenerator keyPairGen = null; try { keyPairGen = * KeyPairGenerator.getInstance(KEY_ALGORITHM); } catch * (NoSuchAlgorithmException e) { logger.error("建立密鑰失敗", e); } * keyPairGen.initialize(1024); * * KeyPair keyPair = keyPairGen.generateKeyPair(); // 公鑰 RSAPublicKey * publicKey = (RSAPublicKey) keyPair.getPublic(); PUBLIC_KEY = * encryptBASE64(publicKey.getEncoded()); // 私鑰 RSAPrivateKey privateKey = * (RSAPrivateKey) keyPair.getPrivate(); PRIVATE_KEY = * encryptBASE64(privateKey.getEncoded()); } */

    public static void main(String[] args) { KeyPairGenerator keyPairGen = null; try { keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM); } catch (NoSuchAlgorithmException e) { } keyPairGen.initialize(1024); KeyPair keyPair = keyPairGen.generateKeyPair(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); System.out.println(RSACoder.encryptBASE64(publicKey.getEncoded())); System.out.println("-----------------------------"); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); System.out.println(RSACoder.encryptBASE64(privateKey.getEncoded())); String pubKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCPEaBoSSdHgK32dsM4H407pOmqSliYz6qh1m5i2ZHY1rF+0ze2VAXf4d+XU4kk2L5L1itHIdxMzMoxHI+F4ZGaeETQLluDJlRpcJL+ZTjEAI6CBNtmGFCTd1QB3AHco1txch04PzMpcjLIa6WzHrI65/bF0kCmo2mQNHLQ+W5hvwIDAQAB"; String priKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAI8RoGhJJ0eArfZ2wzgfjTuk6apKWJjPqqHWbmLZkdjWsX7TN7ZUBd/h35dTiSTYvkvWK0ch3EzMyjEcj4XhkZp4RNAuW4MmVGlwkv5lOMQAjoIE22YYUJN3VAHcAdyjW3FyHTg/MylyMshrpbMesjrn9sXSQKajaZA0ctD5bmG/AgMBAAECgYBuKgR6SNoWFN/fiFOKQ8Fcy/+hQN43zLB3LcaSFzZW4fqKzdl4a/qaCjNBMvHHjZ36h0+L1mbsPET0zCk3zhluzSb+PqmpRfhX8jjEwAd3BB4qHVv2qg5BhDj7JpS7/+iKDztmeHLIAmWNCoI3/fyymuTVPcol46qoCeIjtJ26AQJBAOQQojEPWsTTA+G8E6Qya2B2btm9RkYYgtRwO4ZW/ZYhfYdJdVwYSO4fyALhYfbSBI6lqcL/tp/24n1hqNq3MvcCQQCgl8tsnkIc1IWlez6N/XaZKyh08teNXVfOlduaQQRIng/hYlelc9VeqzEwrzNym0x4CpMy+FsVYg+pDgDh1U15AkASVtwUAd4UsbtALbWOoJdN3HgxfizmehYbKyM+PESMDAliFaAgVbuXmmqlAKa2CFFhfyTVj2aKGnpABthjLhQlAkAMiAvNrAPIsCTFpvpYpiCtDxsXFSQQ2enSKwt52/zzlbHzinMAbCuIOZ+bBvDizo+HBnw6C/s/jele7cLP3I8xAkBFzb9eBxIFzmi7a1+shTXCoSfpsND4fvYbQrHpwzZ4+uLEderoao8JjetHIE4IhXagbfwXKRif27uq/mkEoeGO"; try { String jiami = RSACoder.encryptByPublicKey(pubKey, URLEncoder.encode("{\"sDate\":\"20160101\",\"eDate\":\"20181201\"}", "UTF-8")); // String params = RSACoder.encryptByPublicKey(pubKey,URLEncoder.encode("{\"contractNo\":\"4號\"}", "UTF-8")); // String params = RSACoder.encryptByPublicKey(pubKey,URLEncoder.encode("{\"projName\":\"新密\"}", "UTF-8"));
            System.out.println("加密後的密文:" + jiami); String jiemi = URLDecoder.decode(RSACoder.decryptByPrivateKey(priKey, jiami), "utf-8"); System.out.println("解密加密後的密文:" + jiemi); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block
 e.printStackTrace(); } } /** * 公鑰加密 * * @param pubKey * @param data * @return
     */
    public static String encryptByPublicKey(String pubKey, String data) { try { return encryptBASE64(encryptByPublicKey(pubKey, data.getBytes("utf-8"))); } catch (UnsupportedEncodingException e) { throw new RuntimeException("加密失敗", e); } } /** * 公鑰加密 * * @param pubKey * @param data * @return
     */
    public static byte[] encryptByPublicKey(String pubKey, byte[] data) { try { byte[] keyBytes = decryptBASE64(pubKey); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key key = keyFactory.generatePublic(x509KeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, key); int inputLen = data.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // 對數據分段加密
            while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK); } else { cache = cipher.doFinal(data, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_ENCRYPT_BLOCK; } return out.toByteArray(); } catch (Exception e) { throw new RuntimeException("加密失敗", e); } } /** * 私鑰解密 * * @param pubKey * @param data * @return
     */
    public static String decryptByPrivateKey(String priKey, String data) { try { return new String(decryptByPrivateKey(priKey, decryptBASE64(data)), "utf-8"); } catch (IOException e) { throw new RuntimeException("解密失敗", e); } } /** * 私鑰解密 * * @param prikey * @param data * @return
     */
    public static byte[] decryptByPrivateKey(String priKey, byte[] data) { try { byte[] keyBytes = decryptBASE64(priKey); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key key = keyFactory.generatePrivate(pkcs8KeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, key); int inputLen = data.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // 對數據分段解密
            while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_DECRYPT_BLOCK) { cache = cipher.doFinal(data, offSet, MAX_DECRYPT_BLOCK); } else { cache = cipher.doFinal(data, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_DECRYPT_BLOCK; } cache = out.toByteArray(); out.close(); return cache; } catch (Exception e) { throw new RuntimeException("解密失敗", e); } } /** * 使用私鑰加密數據 用一個已打包成的私鑰加密數據,即數字簽名 * * @param priKey 獲取到的的私鑰(我方的) * @param source 要簽名的數據,通常應是數字摘要 * @return 簽名 byte[] */
    public static String sign(String priKey, byte[] source) { try { byte[] keyBytes = decryptBASE64(priKey); PKCS8EncodedKeySpec priSpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory mykeyFactory = KeyFactory.getInstance(KEY_ALGORITHM); PrivateKey key = mykeyFactory.generatePrivate(priSpec); Signature sig = Signature.getInstance(KEY_SIGN); sig.initSign(key); sig.update(source); return encryptBASE64(sig.sign()); } catch (Exception e) { throw new RuntimeException("加簽失敗", e); } } /** * 驗證數字簽名 * * @param pubKey 獲取到的公鑰(我方的) * @param source 原文的數字摘要 * @param sign 簽名(對原文的數字摘要的簽名) * @return 是否證明 boolean */
    public static boolean verify(String pubKey, byte[] source, String sign) { try { byte[] keyBytes = decryptBASE64(pubKey); KeyFactory mykeyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Signature sig = Signature.getInstance(KEY_SIGN); X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(keyBytes); PublicKey key = mykeyFactory.generatePublic(pubSpec); sig.initVerify(key); sig.update(source); return sig.verify(decryptBASE64(sign)); } catch (Exception e) { logger.error("驗籤失敗", e); return false; } } /** * 私鑰加密 * * @param priKey * @param data * @return
     */
    public static String encryptByPrivateKey(String priKey, String data) { try { return encryptBASE64(encryptByPrivateKey(priKey, data.getBytes("utf-8"))); } catch (UnsupportedEncodingException e) { throw new RuntimeException("加密失敗", e); } } /** * 私鑰加密 * * @param priKey * @param data * @return
     */
    public static byte[] encryptByPrivateKey(String priKey, byte[] data) { try { byte[] bytes = decryptBASE64(priKey); // 取得私鑰
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes); KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM); Key key = factory.generatePrivate(keySpec); // 對數據加密
            Cipher cipher = Cipher.getInstance(factory.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, key); int inputLen = data.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // 對數據分段加密
            while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK); } else { cache = cipher.doFinal(data, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_ENCRYPT_BLOCK; } cache = out.toByteArray(); out.close(); return cache; } catch (Exception e) { throw new RuntimeException("加密失敗", e); } } /** * 公鑰解密 * * @param pubKey * @param data * @return
     */
    public static String decryptByPublicKey(String pubKey, String data) { try { return new String(decryptByPublicKey(pubKey, decryptBASE64(data)), "utf-8"); } catch (IOException e) { throw new RuntimeException("解密失敗", e); } } /** * 公鑰解密 * * @param pubKey * @param data * @return
     */
    public static byte[] decryptByPublicKey(String pubKey, byte[] data) { try { // 對公鑰解密
            byte[] bytes = decryptBASE64(pubKey); // 取得公鑰
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes); KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM); Key key = factory.generatePublic(keySpec); // 對數據解密
            Cipher cipher = Cipher.getInstance(factory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, key); int inputLen = data.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // 對數據分段解密
            while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_DECRYPT_BLOCK) { cache = cipher.doFinal(data, offSet, MAX_DECRYPT_BLOCK); } else { cache = cipher.doFinal(data, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_DECRYPT_BLOCK; } cache = out.toByteArray(); out.close(); return cache; } catch (Exception e) { throw new RuntimeException("解密失敗", e); } } public static byte[] decryptBASE64(String key) throws IOException { return new BASE64Decoder().decodeBuffer(key); } public static String encryptBASE64(byte[] bytes) { return new BASE64Encoder().encodeBuffer(bytes); } public static String encryptBASE64(InputStream in) throws IOException { StringBuilder builder = new StringBuilder(); BASE64Encoder encoder = new BASE64Encoder(); byte[] byteBuf = new byte[6 * 760]; int length; while ((length = in.read(byteBuf)) != -1) { if (length != byteBuf.length) { byte[] copy = Arrays.copyOf(byteBuf, length); builder.append(encoder.encode(copy)); } else { builder.append(encoder.encode(byteBuf)); } } return builder.toString(); } public static String encryptBASE64(InputStream in, String prefix) throws IOException { StringBuilder builder = new StringBuilder(prefix); BASE64Encoder encoder = new BASE64Encoder(); byte[] byteBuf = new byte[6 * 760]; int length; while ((length = in.read(byteBuf)) != -1) { if (length != byteBuf.length) { byte[] copy = Arrays.copyOf(byteBuf, length); builder.append(encoder.encode(copy)); } else { builder.append(encoder.encode(byteBuf)); } } return builder.toString(); } }

 

前臺加密java

首先引入:jsencrypt.min.js 連接:https://pan.baidu.com/s/1vd4AK9iHUHwmOtbdUP2l6Q 密碼:hkvr
 js代碼: var password = $("#password").val(); var encrypt = new JSEncrypt(); encrypt.setPublicKey(publicKey); pwd = encrypt.encrypt(password); pwd 即爲加密後的密碼。
相關文章
相關標籤/搜索