美文网首页
Java加密

Java加密

作者: 逝_思 | 来源:发表于2016-11-01 16:56 被阅读60次

    MD5加密:

    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    
    /**
     * MD5加密,不可逆
     * 
     * @author yyw
     * 
     */
    public class MD5Encrypt {
        /**
         * 对指定的字符串进行md5加密
         * 
         * @param srcString
         *            指定的字符串
         * @return 加密后的字符串
         */
        public static String md5Encrypt(String srcString) {
            try {
                MessageDigest md = MessageDigest.getInstance("md5");
                byte[] result = md.digest(srcString.getBytes());
                StringBuilder sBuilder = new StringBuilder();
                for (byte b : result) {
                    int i = b & 0xff;// 加盐
                    String mString = Integer.toHexString(i);
                    if (mString.length() == 1) {
                        sBuilder.append("0");
                    }
                    sBuilder.append(mString);
                }
                return sBuilder.toString();
            } catch (NoSuchAlgorithmException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return srcString;
        }
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            System.err.println(md5Encrypt("123456"));
    
        }
    
    }
    

    RSA加密:

    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectOutputStream;
    import java.security.InvalidKeyException;
    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.SecureRandom;
    import java.security.interfaces.RSAPrivateKey;
    import java.security.interfaces.RSAPublicKey;
    import java.security.spec.PKCS8EncodedKeySpec;
    import java.security.spec.X509EncodedKeySpec;
    
    import javax.crypto.Cipher;
    import javax.crypto.NoSuchPaddingException;
    
    import sun.misc.BASE64Decoder;
    import sun.misc.BASE64Encoder;
    
    /**
     * 用RSA进行加密解密的工具类
     * 
     * @author yyw
     * 
     */
    public class RSAHepler {
        /**
         * 包含私钥的字符串,可以获取私钥
         */
        private static final String PRIVATE_KEY_STRING = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJ9JhbdNwIWsH8Ms4ENyYis5b9ma931Bv1ejKIAkNcqAbY2w4jwJ0JWW2vTc3B1sr2pC4ABbFKS6ARhNgmrr5gpNYXAxIwL/b/N2im+KpqI5GE5naiItgr049AL1BFIgTdG2b+N8q5TVHXz+bE9hIEzu6Xss2XOQ6uyHb2Gxd6r7AgMBAAECgYA6kouUCwhHXzLSz1asFoyYvmctynlFWv7kV//VlvscursORkP6tdU4nJ9pOSnLvCKI3YyHNPbTV/59FEtny9Tr0F98DTql+J/LbH7Zh8QY/yJTYwmTDYljxYxsVSn0E8jCO5VKs2n2ZwVDubwA32yqu1abkDmZHC8lHu2SKCONUQJBAO4QXsSgLz7RzRkACJL2+9JeRo5eqsm0yvr6hmdvSweQvBYYUpZnDq/Cz20TNruKNG3fxUJbuT/jGys68Mk4mxMCQQCrScFJxFNUdVuNCFCGiRdyeN1U0pc2+KsG9O47hzngawMeIdqX4qA0NV+Nt8gp4KUr93C7LNz1vuY7uTRZdQV5AkA7SyJ/cLIzwEeIGYUJLbDs5YRHQ3bgREJmHm3JZ2PVn4vpKOexBDwZNLk7HpT8QuDqGNjlvTi3m9YRf12nkIy3AkEAnDyAI8sBvy30veVxneV6D54TNIWKDEgxp/zNOFsV/Y9enqN+gb/jJPvyFpAl8ZzIzBu9Jd28BiOEWcGK8HX+8QJBAO0jIFf80YkE8D/kJAUZyv0d6zn0HDx4P+mdmUR+sbf1BYtMKrTGB5O+hN5jrzhvhyb3PES4WxVGSChJDHDpxko=";
        /**
         * 包含公钥的字符串,可以获取公钥
         */
        private static final String PUBLIC_LEY_STRING = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCfSYW3TcCFrB/DLOBDcmIrOW/Zmvd9Qb9XoyiAJDXKgG2NsOI8CdCVltr03NwdbK9qQuAAWxSkugEYTYJq6+YKTWFwMSMC/2/zdopviqaiORhOZ2oiLYK9OPQC9QRSIE3Rtm/jfKuU1R18/mxPYSBM7ul7LNlzkOrsh29hsXeq+wIDAQAB";
    
        /** 加密算法 **/
        private static final String KEY_ALGORITHM = "RSA";
    
        /**
         * 获取公钥
         * 
         * @param key
         *            包含公钥的字符串
         * @return 公钥
         * @throws Exception
         */
        public static RSAPublicKey getPublicKey(String key) throws Exception {
            byte[] keyBytes = (new BASE64Decoder()).decodeBuffer(key);
            X509EncodedKeySpec xKeySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            RSAPublicKey publicKey = (RSAPublicKey) keyFactory
                    .generatePublic(xKeySpec);
            return publicKey;
        }
    
        /**
         * 获取私钥
         * 
         * @param key
         *            包含私钥的字符串
         * @return 私钥
         * @throws Exception
         */
        public static RSAPrivateKey getPrivateKey(String key) throws Exception {
            byte[] keyBytes = (new BASE64Decoder()).decodeBuffer(key);
            PKCS8EncodedKeySpec xKeySpec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            RSAPrivateKey privateKey = (RSAPrivateKey) keyFactory
                    .generatePrivate(xKeySpec);
            return privateKey;
        }
    
        /**
         * 对Key进行编码
         * 
         * @param key
         *            要编码的Key
         * @return 编码后的字符串
         */
        public static String getKeyString(Key key) {
            byte[] encoded = key.getEncoded();
            return (new BASE64Encoder()).encode(encoded);
        }
    
        /**
         * 加密
         * 
         * @param string
         *            明文
         * @return 密文
         */
        public static String encrypt(String string) {
            try {
                // 获取解密加密的工具
                Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
                RSAPublicKey publicKey = getPublicKey(PUBLIC_LEY_STRING);
                // 设置为加密模式,并放入公钥
                cipher.init(Cipher.ENCRYPT_MODE, publicKey);
                // 获取要加密的字节长度
                final int size = string.getBytes().length;
                final byte[] input = string.getBytes();
                // 获得加密块大小,如:加密前数据为128个byte,而key_size=1024 加密块大小为117
                // byte,加密后为128个byte;
                // 因此共有2个加密块,第一个117 byte第二个为11个byte
                
                final int blockSize = 117;
                // 获得加密块加密后块大小(都是128)
                final int resultSize = cipher.getOutputSize(size);
                System.err.println(resultSize);
                // 最后一个加密块的大小
                final int leavedSize = size % blockSize;
                // 加密块的数量
                final int blocksSize = leavedSize == 0 ? size / blockSize : size
                        / blockSize + 1;
                byte[] encrypts = new byte[resultSize * blocksSize];
                for (int i = 0; i < blocksSize; i++) {
                    if (i == blocksSize - 1 && leavedSize > 0) {// 最后一次是不满一个代码块的时候执行
                        cipher.doFinal(input, i * blockSize, leavedSize, encrypts,
                                resultSize * i);
                    } else {
                        cipher.doFinal(input, i * blockSize, blockSize, encrypts,
                                resultSize * i);
                    }
                }
                // 对字节数组进行加密,返回加密后的字节数组
                // encrypts = cipher.doFinal(string.getBytes());
                // 对加密后的字节数组进行64位的编码,生成字符串
                String encrypt = new BASE64Encoder().encode(encrypts);
                System.out.println("加密之后:" + encrypt);
                return encrypt;
            } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
                e.printStackTrace();
            } catch (InvalidKeyException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "";
        }
    
        /**
         * 对文件进行加密
         * 
         * @param file
         *            要加密的文件
         * @param encryptFile
         *            加密后的文件
         * @return
         */
        public static boolean encrypt(File file, File encryptFile) {
            FileInputStream fis = null;
            FileOutputStream fos = null;
            try {
                fis = new FileInputStream(file);
                fos = new FileOutputStream(encryptFile);
                // 获取解密加密的工具
                Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
                RSAPublicKey publicKey = getPublicKey(PUBLIC_LEY_STRING);
                // 设置为加密模式,并放入公钥
                cipher.init(Cipher.ENCRYPT_MODE, publicKey);
                // 获得加密块大小,如:加密前数据为128个byte,而key_size=1024 加密块大小为127
                // byte,加密后为128个byte;
                // 因此共有2个加密块,第一个127 byte第二个为1个byte
                final int blockSize = publicKey.getModulus().bitLength() / 8 - 11;
                System.err.println(blockSize);
                int len = -1;
                byte[] beffer = new byte[blockSize];
                while ((len = fis.read(beffer)) > 0) {
                    byte[] doFinal = cipher.doFinal(beffer, 0, len);
                    fos.write(doFinal);
                }
                // 对字节数组进行加密,返回加密后的字节数组
                // encrypts = cipher.doFinal(string.getBytes());
                // 对加密后的字节数组进行64位的编码,生成字符串
                return true;
            } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
                e.printStackTrace();
            } catch (InvalidKeyException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
            return false;
        }
    
        /**
         * 对文件进行加密
         * 
         * @param file
         *            解密的文件
         * @param encryptFile
         *            加密后的文件
         * @return
         */
        public static boolean dencrypt(File encryptFile, File file) {
            FileInputStream fis = null;
            FileOutputStream fos = null;
            try {
                fis = new FileInputStream(encryptFile);
                fos = new FileOutputStream(file);
                // 获取解密加密的工具
                Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
                RSAPrivateKey privateKey = getPrivateKey(PRIVATE_KEY_STRING);
                // 设置为解密模式,并放入公钥
                cipher.init(Cipher.DECRYPT_MODE, privateKey);
                // 可以解码的最大长度
                final int blockSize = privateKey.getModulus().bitLength() / 8;
                System.err.println(blockSize);
                int len = -1;
                byte[] buffer = new byte[blockSize];
                while ((len = fis.read(buffer)) > 0) {
                    byte[] doFinal = cipher.doFinal(buffer, 0, len);
                    fos.write(doFinal);
                }
                // 对字节数组进行加密,返回加密后的字节数组
                // encrypts = cipher.doFinal(string.getBytes());
                // 对加密后的字节数组进行64位的编码,生成字符串
                return true;
            } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
                e.printStackTrace();
            } catch (InvalidKeyException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
            return false;
        }
    
        /**
         * 解密
         * 
         * @param string
         *            密文
         * @return 明文
         */
        public static String dencrypt(String string) {
            try {
                // 获取解密加密的工具
                Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
                RSAPrivateKey privateKey = getPrivateKey(PRIVATE_KEY_STRING);
                // 设置为解密模式,并放入密钥
                cipher.init(Cipher.DECRYPT_MODE, privateKey);
                // 对字符串进行解码
                byte[] decoders = new BASE64Decoder().decodeBuffer(string);
                // 对字节数组进行解密
                ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
                // 可以解码的最大长度
                final int blockSize = privateKey.getModulus().bitLength() / 8;
                // 需要解码的总长度
                final int size = decoders.length;
                // 最后一次是否有不满一次解码的最大长度
                final int leavedSize = size % blockSize;
                // 需要解码的次数
                final int blocksSize = leavedSize == 0 ? size / blockSize : size
                        / blockSize + 1;
                for (int j = 0; j < blocksSize; j++) {
                    if (j == blocksSize - 1 && leavedSize > 0) {// 最后一次是不满一个代码块的时候执行
                        baos.write(cipher.doFinal(decoders, j * blockSize,
                                leavedSize));
                    } else {
                        baos.write(cipher.doFinal(decoders, j * blockSize,
                                blockSize));
                    }
                }
                String result = baos.toString();
                return result;
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (NoSuchPaddingException e) {
                e.printStackTrace();
            } catch (InvalidKeyException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "";
        }
    
        /**
         * 生成公钥和密钥并保存到文件当中
         * 
         * @param publicKeyFileName
         *            公钥文件名
         * @param privateKeyFileName
         *            密钥文件名
         */
        public static void getKeyPair(String publicKeyFileName,
                String privateKeyFileName) {
            try {
                /** 为RSA算法创建一个KeyPairGenerator对象 */
                KeyPairGenerator keyPairGenerator = KeyPairGenerator
                        .getInstance(KEY_ALGORITHM);
                /** RSA算法要求有一个可信任的随机数源 */
                SecureRandom random = new SecureRandom();
                /** 利用上面的随机数据源初始化这个KeyPairGenerator对象 */
                keyPairGenerator.initialize(1024, random);// 秘钥的位数
                /** 生成密匙对 */
                KeyPair keyPair = keyPairGenerator.generateKeyPair();
                /** 得到私钥 */
                PrivateKey privateKey = keyPair.getPrivate();
                /** 得到公钥 */
                PublicKey publicKey = keyPair.getPublic();
                /** 用对象流将生成的密钥写入文件 */
                ObjectOutputStream oos1 = new ObjectOutputStream(
                        new FileOutputStream(publicKeyFileName));
                ObjectOutputStream oos2 = new ObjectOutputStream(
                        new FileOutputStream(privateKeyFileName));
                oos1.writeObject(publicKey);
                oos2.writeObject(privateKey);
                /** 清空缓存,关闭文件输出流 */
                oos1.close();
                oos2.close();
            } catch (NoSuchAlgorithmException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    
        /**
         * 生成公钥和密钥并打印出来
         */
        public static void getKeyPair() {
            try {
                /** 为RSA算法创建一个KeyPairGenerator对象 */
                KeyPairGenerator keyPairGenerator = KeyPairGenerator
                        .getInstance(KEY_ALGORITHM);
                /** RSA算法要求有一个可信任的随机数源 */
                SecureRandom random = new SecureRandom();
                /** 利用上面的随机数据源初始化这个KeyPairGenerator对象 */
                keyPairGenerator.initialize(1024, random);// 秘钥的位数
                /** 生成密匙对 */
                KeyPair keyPair = keyPairGenerator.generateKeyPair();
                /** 得到私钥 */
                PrivateKey privateKey = keyPair.getPrivate();
                /** 得到公钥 */
                PublicKey publicKey = keyPair.getPublic();
                String publicKeyString = getKeyString(publicKey);
                String privateKeyString = getKeyString(privateKey);
                System.out.println("公钥:" + publicKeyString);
                System.out.println("密钥:" + privateKeyString);
            } catch (NoSuchAlgorithmException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    
        public static void main(String[] args) throws Exception {
            getKeyPair();
            String src = encrypt("今天是周一;");
    //      System.err.println(src);
            String dis = dencrypt(src);
            System.err.println(dis);
    //      File file = new File("D:\\TYSubwayInspcetion.db");
    //      File encryptfile = new File("D:\\encryptfile.db");
    //      File decryptfile = new File("D:\\decryptfile.db");
    //      encrypt(file, encryptfile);
    //      dencrypt(encryptfile, decryptfile);
        
            
        }
    }
    

    CBC加密:

    import java.io.IOException;
    import java.security.InvalidKeyException;
    import java.security.Key;
    
    import javax.crypto.Cipher;
    import javax.crypto.SecretKeyFactory;
    import javax.crypto.spec.DESedeKeySpec;
    import javax.crypto.spec.IvParameterSpec;
    
    import sun.misc.BASE64Decoder;
    import sun.misc.BASE64Encoder;
    
    public class CBCEncrypt {
        private static final byte[] KEY_IV = { 11, 22, 33, 44, 55, 66, 77, 88 };
        private static final String DESEDE = "DESede";
        private static final String DESEDE_CIPHER = "DESede/CBC/PKCS5Padding";
    
        /**
         * 从Base64字符获取对应的Byte[]
         * 
         * @param s
         *            Base64字符串
         * */
        public static byte[] base64Decode(String s) throws IOException {
            if (s == null)
                return null;
            return new BASE64Decoder().decodeBuffer(s);
        }
    
        /**
         * 把指定的字节数据进行编码
         * 
         * @param date
         *            要编码的字节数据
         * */
        public static String base64Encode(byte[] date) throws IOException {
            if (date == null)
                return null;
            return new BASE64Encoder().encode(date);
        }
    
        /**
         * 对指定数据和指定的key进行加密
         * 
         * @param key
         *            加密的秘钥
         * @param data
         *            数据源
         * @return 加密后的数据源
         * @throws Exception
         */
        public static byte[] des3Encrypt(byte[] key, byte[] data) throws Exception {
            DESedeKeySpec keySpec = new DESedeKeySpec(key);
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DESEDE);
            Key desKey = keyFactory.generateSecret(keySpec);
            Cipher cipher = Cipher.getInstance(DESEDE_CIPHER);
            IvParameterSpec ivParameterSpec = new IvParameterSpec(KEY_IV);
            cipher.init(Cipher.ENCRYPT_MODE, desKey, ivParameterSpec);
            return cipher.doFinal(data);
    
        }
    
        /**
         * CBC解密
         * 
         * @param key
         *            密钥
         * @param keyiv
         *            IV
         * @param data
         *            Base64编码的密文
         * @return 明文
         * @throws Exception
         */
        public static byte[] des3Decrypt(byte[] key, byte[] data) throws Exception {
            //生成指定的秘钥
            DESedeKeySpec spec = new DESedeKeySpec(key);
            SecretKeyFactory keyfactory = SecretKeyFactory.getInstance(DESEDE);
            Key deskey = keyfactory.generateSecret(spec);
            //加密解密操作类
            Cipher cipher = Cipher.getInstance(DESEDE_CIPHER);
            //参数规范
            IvParameterSpec ips = new IvParameterSpec(KEY_IV);
            //初始化
            cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
            //解密
            return cipher.doFinal(data);
        }
    
        /**
         * key 秘钥的一部分字符串
         * 
         * @return 秘钥
         * @throws IOException
         */
        public static byte[] getKey(String key) throws IOException {
            int iKeyLength = 24;// key的长度为24
            String cryptionKey = "TongYanMetro" + key;
            if (cryptionKey.length() > iKeyLength) {
                cryptionKey.substring(0, iKeyLength - 1);
            }
            if (cryptionKey.length() < iKeyLength) {
                int iLength = iKeyLength - cryptionKey.length();
                for (int i = 0; i < iLength; i++) {
                    cryptionKey += "0";
                }
            }
            byte[] pt1 = cryptionKey.getBytes("UTF-8");
            return pt1;
        }
    
        public static String encrypt(String key, String dataString)
                throws Exception {
            // 得到3-DES的密钥匙
            byte[] enKey = getKey(key);
            // 要进行3-DES加密的内容在进行/"UTF-16LE/"取字节
            byte[] src2 = dataString.getBytes("utf-8");
            // 进行3-DES加密后的内容的字节
            byte[] encryptedData = des3Encrypt(enKey,src2);
            // 进行3-DES加密后的内容进行BASE64编码
            String base64String = base64Encode(encryptedData);
            return base64String;
    
        }
    
        public static String decrypt(String key, String dataString)
                throws Exception {
            // 得到3-DES的密钥匙
            byte[] enKey = getKey(key);
            // 解码后的数据
            byte[] data = base64Decode(dataString);
            byte[] decryptData = des3Decrypt(enKey,data);
            return new String(decryptData,"UTF-8");
    
        }
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            try {
                String keyString = "zhangshan";
                String encryptString = encrypt(keyString, "点击付款");
                System.err.println(encryptString);
                System.err.println(decrypt(keyString, encryptString));
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
        }
    
    }
    
    

    相关文章

      网友评论

          本文标题:Java加密

          本文链接:https://www.haomeiwen.com/subject/wlbmuttx.html