zoukankan      html  css  js  c++  java
  • 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();
        }
    }

    前台加密

    首先引入: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 即为加密后的密码。
  • 相关阅读:
    一步一步学习开发BPM工作流系统(三)开发WinForm的应用平台1
    支持多数据库本地和远程调用的数据访问层架构
    HF Web表单开发技术文档
    CDZSC_2015寒假新人(2) 数学 C
    CDZSC_2015寒假新人(2)——数学 A
    ZSC 1306: 沼跃鱼早已看穿了一切 题解
    解决”java.lang.UnsatisfiedLinkError: Native Library .dll already loaded in another classloader”的问题
    有目标就要坚持
    (转)新兴XML处理方法VTDXML介绍
    (转)Java远程通讯可选技术及原理
  • 原文地址:https://www.cnblogs.com/gaomanito/p/8882927.html
Copyright © 2011-2022 走看看