首页 > 代码库 > java util - MD5/AES/RSA快速调用工具

java util - MD5/AES/RSA快速调用工具

测试代码

package cn.java.security;


import java.security.Key;
import java.util.Base64;
import org.junit.Assert;
import cn.java.codec.hex.HexUtil;
import cn.java.security.SecurityUtil.RsaUtil.RsaKeyPair;


public class Test {

    public static void main(String[] args)  throws Exception{
        System.out.println("-----------<<< testDigest >>>------------------");
        testDigest();
        System.out.println();
        
        System.out.println("-----------<<< testAes >>>------------------");
        testAes();
        System.out.println();
        
        System.out.println("-----------<<< testRsa >>>------------------");
        testRsa();
        System.out.println();
    }

    /**
     * 对称加密算法
     * @throws Exception
     */
    public static void testAes() throws Exception {
        String content = "testAes";
        String secretKeyStr = SecurityUtil.AesUtil.generaterKey();
        System.out.println("-----------secretKeyStr------------------");
        System.out.println(secretKeyStr);
        String encryptStr = SecurityUtil.AesUtil.encrypt(content, secretKeyStr);
        String decryptStr = SecurityUtil.AesUtil.decrypt(encryptStr, secretKeyStr);
        System.out.println("-----------encryptStr------------------");
        System.out.println(encryptStr);
        System.out.println("-----------decryptStr------------------");
        System.out.println(decryptStr);
    }
    
    /**
     * 非对称加密算法
     * @throws Exception
     */
    public static void testRsa() throws Exception {

        String content = "testRsa";
        // 生成秘钥对
        RsaKeyPair mRsaKeyPair = SecurityUtil.RsaUtil.generaterKeyPair();
        String privateKeyStr = mRsaKeyPair.getPrivateKey();
        String publicKeyStr = mRsaKeyPair.getPublicKey();
        System.out.println("-----------privateKeyStr------------------");
        System.out.println(privateKeyStr);
        System.out.println("-----------publicKeyStr------------------");
        System.out.println(publicKeyStr);
        
        // test sign
        {
            String signStr = SecurityUtil.RsaUtil.sign(content, privateKeyStr,true);
            boolean isValid = SecurityUtil.RsaUtil.verify(content,signStr, publicKeyStr,true);
            System.out.println("-----------signStr------------------");
            System.out.println(signStr);
            System.out.println("-----------isValid------------------");
            System.out.println(isValid);
        }

        // test codec
        {
            Key privateKey = SecurityUtil.RsaUtil.getPrivateKey(privateKeyStr);
            Key publicKey = SecurityUtil.RsaUtil.getPublicKey(publicKeyStr);

            // 私钥加密、公钥解密
            String encryptStr = SecurityUtil.RsaUtil.encrypt(content, privateKey);
            String decryptStr = SecurityUtil.RsaUtil.decrypt(encryptStr, publicKey);
//            Assert.assertEquals(content, decryptStr);
            System.out.println("-----------encryptStr------------------");
            System.out.println(encryptStr);
            System.out.println("-----------decryptStr------------------");
            System.out.println(decryptStr);

            // 公钥加密、私钥解密
            encryptStr = SecurityUtil.RsaUtil.encrypt(content, privateKey);
            decryptStr = SecurityUtil.RsaUtil.decrypt(encryptStr, publicKey);
            Assert.assertEquals(content, decryptStr);
        }

    }

    /**
     * 签名
     */
    public static void testDigest() throws Exception {
        byte[] bytes = SecurityUtil.MessageDigestUtil.digest("test", true);
        String hexEncode = HexUtil.encode(bytes);
        System.out.println(hexEncode);

        byte[] hexDecode = HexUtil.decode(hexEncode);
        System.out.println(Base64.getEncoder().encodeToString(bytes));
        System.out.println(Base64.getEncoder().encodeToString(hexDecode));
    }

}

数据内容

-----------<<< testDigest >>>------------------
098f6bcd4621d373cade4e832627b4f6
CY9rzUYh03PK3k6DJie09g==
CY9rzUYh03PK3k6DJie09g==

-----------<<< testAes >>>------------------
-----------secretKeyStr------------------
BREMlyKxuMP2Qc7wIVa9Hg==
16
16
-----------encryptStr------------------
W+47ylkmqZ3G2Wq95esUEg==
-----------decryptStr------------------
testAes

-----------<<< testRsa >>>------------------
-----------privateKeyStr------------------
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCQsWH5fsMj03Ja2W5pxvCz5JBrOUF43yZCenUuBB9gMcJH9oySOeQVWWiAQJ+sVqI4QqMLrYsZJuNnuHFWr+uIFyXV7doQDFysvPmbMeQ1UPR9Bv+60QC47YRpVzAR3x0bGRbB3cCJ2U+t55xDV0CuljqR7X4CyfVSDvqaRV08uRn+b/vIvC0e623Uidez1IwGbobWYXBL6WRS0ooOm8AcSy84+c+mahuOUQFjJak18fBwJYnPTHWQnpxtnP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BLIpsDow5NwbLymNt2LQeiiRBfw/UoCO478aNXwWmjpoYWCeFCvQRj89IPMSQDAoGBAIYlxX5FcfColAT3Ams4cjXqVMiwH2O+Ka7bkeQMfWuLTpGAcgM/f6vMoQ1NHUgu+M70pyyrV48pBHxIqAP0PYn6piMMfk7S6yORDF9riFh8D30up3O0Bfe8PbTyModCdhaGNWvhSqMs/ijDVclAXWeuKtA6A8GFuWvxgKdONey9
-----------publicKeyStr------------------
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkLFh+X7DI9NyWtluacbws+SQazlBeN8mQnp1LgQfYDHCR/aMkjnkFVlogECfrFaiOEKjC62LGSbjZ7hxVq/riBcl1e3aEAxcrLz5mzHkNVD0fQb/utEAuO2EaVcwEd8dGxkWwd3AidlPreecQ1dArpY6ke1+Asn1Ug76mkVdPLkZ/m/7yLwtHutt1InXs9SMBm6G1mFwS+lkUtKKDpvAHEsvOPnPpmobjlEBYyWpNfHwcCWJz0x1kJ6cbZz2ENNvC2NOTY57seg2NrRKnmr7xbhkOI1xISxKk0C9HU9v2rjN/cBKy5IH8F+jjz4AjPwHFCmjP6Xc22RtSJ9rFYxVJQIDAQAB
-----------signStr------------------
ZZuYMdl58w2TCBaUMfU0p+XUL6Irix9/nD0gPm83P/xqlY18GROztZmat5XLKA5Wu373/2l2WhIKdp7DYoQm0Cnmr/0PDGz9PHw2Hhd9I52OVkcDqSPqgmo0U9uE02Urlt3C2moVS08b3VhLHOOzSq8lcsicqis17p0KY33k2he2XMbHEJEbxRMkPCDubDWqwnS/fKiXbNn3u+jni7zdX/Phaq41V2lMMMjdIP8Pm7OxlxdNP3aoTAu6eHaCvakganQE2cz6Y1HwfgXgA8EzaTCcE+weGBbfy9umcMfK0/Pnsqp+jTiz3c8O0p0C8QwogGwIOLBzbeu4d9svC8JA9Q==
-----------isValid------------------
true
-----------encryptStr------------------
dJGhdeCaK/gw52NkD+z1BPoooKYgHqMWUn+tvyPndrq1f5oqaqc8mn/ZclWCLg/hN4PE9zi7gCD9xgp/KEPWOc6XNzOXA/92LVBERpGGtYLQmZnOS8ZrrD4xxxMmra5qD2j03T9Cu4xrICCVZ/Qcp7l05/tZt6tFXJqSDG5uSN9I/en+Mbza9aGwBiTWm6rpv+E5F3sMVk9XDMMgVTMVu6DeT4jZ7HjQ+GATlYFHReVFWmyTv8ijKdnhgMhVvOrGToRAu/ExbNuF99l6FB5I5ZQQMU0wyQDlpXm4GYoRIMmT5wweWJy2f0yO4BnkTje8oNMz7pXnuhNdEulZ5S86sA==
-----------decryptStr------------------
testRsa

 

工具类

package cn.java.security;

import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
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.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class SecurityUtil {

    /**
     * 消息摘要
     * @author zhouzhian
     *
     */
    public static class MessageDigestUtil {

        public static byte[] digest(String content, boolean isMd5) throws Exception {
            MessageDigest messageDigest = null;
            String algorithm = isMd5 ? "MD5" : "SHA";
            messageDigest = MessageDigest.getInstance(algorithm);
            return messageDigest.digest(content.getBytes());
        }

        public static byte[] digest1(String content, boolean isMd5) throws Exception {
            MessageDigest messageDigest = null;
            String algorithm = isMd5 ? "MD5" : "SHA";
            messageDigest = MessageDigest.getInstance(algorithm);
            messageDigest.update(content.getBytes());
            return messageDigest.digest();
        }
    }

    /**
     * 对称加密算法
     * @author zhouzhian
     *
     */
    public static class AesUtil {
        private static final String ALGORITHM = "AES";
        private static final String DEFAULT_CHARSET = "UTF-8";

        /**
         * 生成秘钥
         * @return
         * @throws NoSuchAlgorithmException
         */
        public static String generaterKey() throws NoSuchAlgorithmException {  
            KeyGenerator keygen = KeyGenerator.getInstance(ALGORITHM);
            keygen.init(128, new SecureRandom()); // 16 字节 == 128 bit
            //            keygen.init(128, new SecureRandom(seedStr.getBytes())); // 随机因子一样,生成出来的秘钥会一样
            SecretKey secretKey = keygen.generateKey();
            return Base64.getEncoder().encodeToString(secretKey.getEncoded());
        }

        /**
         */
        public static SecretKeySpec getSecretKeySpec(String secretKeyStr){
            byte[] secretKey = Base64.getDecoder().decode(secretKeyStr);
            System.out.println(secretKey.length);
            return new SecretKeySpec(secretKey, ALGORITHM);
        }

        /**
         * 加密
         */
        public static String encrypt(String content,String secretKey) throws Exception{
            Key key = getSecretKeySpec(secretKey);
            Cipher cipher = Cipher.getInstance(ALGORITHM);// 创建密码器  
            cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
            byte[] result = cipher.doFinal(content.getBytes(DEFAULT_CHARSET));
            return Base64.getEncoder().encodeToString(result);
        }

        /**
         * 解密
         */
        public static String decrypt(String content, String secretKey) throws Exception{  
            Key key = getSecretKeySpec(secretKey);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] result = cipher.doFinal(Base64.getDecoder().decode(content));  
            return new String(result);
        }  
    }

    /**
     * 非对称加密算法
     * @author zhouzhian
     *
     */
    public static class RsaUtil {

        public static class RsaKeyPair {
            private String publicKey ="";
            private String privateKey ="";

            public RsaKeyPair(String publicKey, String privateKey) {
                super();
                this.publicKey = publicKey;
                this.privateKey = privateKey;
            }

            public String getPublicKey() {
                return publicKey;
            }
            public String getPrivateKey() {
                return privateKey;
            }
        }

        private static final String ALGORITHM = "RSA";
        private static final String ALGORITHMS_SHA1WithRSA = "SHA1WithRSA";
        private static final String ALGORITHMS_SHA256WithRSA = "SHA256WithRSA";
        private static final String DEFAULT_CHARSET = "UTF-8";
        private static String getAlgorithms(boolean isRsa2) {
            return isRsa2 ? ALGORITHMS_SHA256WithRSA : ALGORITHMS_SHA1WithRSA;
        }

        /**
         * 生成秘钥对
         * @return
         * @throws NoSuchAlgorithmException
         */
        public static RsaKeyPair generaterKeyPair() throws NoSuchAlgorithmException{  
            KeyPairGenerator keygen = KeyPairGenerator.getInstance(ALGORITHM);  
            SecureRandom random = new SecureRandom();  
            //            SecureRandom random = new SecureRandom(seedStr.getBytes()); // 随机因子一样,生成出来的秘钥会一样
            // 512位已被破解,用1024位,最好用2048位 
            keygen.initialize(2048, random);
            // 生成密钥对  
            KeyPair keyPair = keygen.generateKeyPair();  
            RSAPrivateKey privateKey = (RSAPrivateKey)keyPair.getPrivate();  
            RSAPublicKey publicKey = (RSAPublicKey)keyPair.getPublic();   
            String privateKeyStr = Base64.getEncoder().encodeToString(privateKey.getEncoded());
            String publicKeyStr = Base64.getEncoder().encodeToString(publicKey.getEncoded());  
            return new RsaKeyPair(publicKeyStr,privateKeyStr);
        }

        /**
         * 获取公钥
         * @param publicKey
         * @return
         * @throws Exception
         */
        public static RSAPublicKey getPublicKey(String publicKey) throws Exception{  
            byte[] keyBytes = Base64.getDecoder().decode(publicKey);  
            X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);  
            KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);  
            return (RSAPublicKey) keyFactory.generatePublic(spec);  
        }

        /**
         * 获取私钥
         * @param privateKey
         * @return
         * @throws NoSuchAlgorithmException 
         * @throws InvalidKeySpecException 
         * @throws Exception
         */
        public static RSAPrivateKey getPrivateKey(String privateKey) throws Exception{  
            byte[] keyBytes = Base64.getDecoder().decode(privateKey);  
            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);  
            KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);  
            return (RSAPrivateKey) keyFactory.generatePrivate(spec);  
        }

        /**
         * 要私钥签名
         * @throws InvalidKeySpecException 
         * @throws Exception 
         */
        public static String sign(String content, String privateKey, boolean isRsa2) throws Exception {
            PrivateKey priKey = getPrivateKey(privateKey);
            java.security.Signature signature = java.security.Signature.getInstance(getAlgorithms(isRsa2));
            signature.initSign(priKey);
            signature.update(content.getBytes(DEFAULT_CHARSET));
            byte[] signed = signature.sign();
            return Base64.getEncoder().encodeToString(signed);
        }

        /**
         * 要公钥签名
         */
        public static boolean verify(String content,String sign,String publicKey,boolean isRsa2) throws Exception {
            PublicKey pubKey = getPublicKey(publicKey);
            java.security.Signature signature = java.security.Signature.getInstance(getAlgorithms(isRsa2));
            signature.initVerify(pubKey);
            signature.update(content.getBytes(DEFAULT_CHARSET));
            return signature.verify(Base64.getDecoder().decode(sign));
        }

        /**
         * 加密
         * @param input
         * @param pubOrPrikey
         * @return
         */
        public static String encrypt(String content, Key pubOrPrikey) throws Exception{
            Cipher cipher = null;
            cipher = Cipher.getInstance(ALGORITHM); 
            cipher.init(Cipher.ENCRYPT_MODE, pubOrPrikey);
            byte[] result = cipher.doFinal(content.getBytes(DEFAULT_CHARSET));
            return Base64.getEncoder().encodeToString(result);
        }

        /**
         * 解密
         * @param input
         * @param pubOrPrikey
         * @return
         */
        public static String decrypt(String content, Key pubOrPrikey) throws Exception {
            Cipher cipher = null;
            cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, pubOrPrikey);  
            byte[] result = cipher.doFinal(Base64.getDecoder().decode(content));
            return new String(result);
        }
    }

}

 

java util - MD5/AES/RSA快速调用工具