java各种加密解密

import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.PrivateKey;
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.HashMap;
import java.util.Map;
import java.util.Scanner;

import javax.crypto.*;
import javax.crypto.spec.*;

import Decoder.BASE64Decoder;
import Decoder.BASE64Encoder;

public class Test {
    /**
     * 程序入口
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        int temp = mains();
        while (temp != 0) {
            switch (temp) {
            case 1:
                test1();
                break;
            case 2:
                test2();
                break;
            case 3:
                test3();
                break;
            case 4:
                System.out.println(Test.hexbyteString(md5("duwenleis".getBytes())));
                break;
            case 5:
                verify();
                break;
            }
            System.out.println();
            System.out.println();
            System.out.println();
            temp = mains();
        }
    }
    private static int mains() {
        System.out.println("欢迎进入加解密认证系统");
        System.out.println("请选择:");
        System.out.println("1.对称加密:");
        System.out.println("2.非对称加密之公钥加密私钥解密:");
        System.out.println("3.非对称加密之私钥钥加密公钥解密:");
        System.out.println("4.md5:");
        System.out.println("5.verify:");
        Scanner in = new Scanner(System.in);
        int temp = in.nextInt();
        return temp;
    }

    
    /**
     * verify
     * */
    private static void verify() throws Exception {
        String str = "duwenleis";
        byte[] data = Test.md5(str.getBytes());
        String hexByte = hexbyteString(data);
        boolean flag = Test.approve(str.getBytes(), hexByte);
        System.out.println("运算结果为:" + flag);
    }

    /**
     * verify
     * 
     * @param str
     * @return
     * @throws Exception
     */
    public static boolean approve(byte[] str, String data1) throws Exception {
        MessageDigest md = MessageDigest.getInstance("md5");
        byte[] bt = md.digest(str);
        String data = hexbyteString(bt);
        if (data.equals(data1)) {
            return true;
        }
        return false;
    }

    /**
     * md5
     * 
     * @param str
     * @return
     * @throws Exception
     */
    public static byte[] md5(byte[] str) throws Exception {
        MessageDigest md = MessageDigest.getInstance("md5");
        byte[] data = md.digest(str);
        return data;
    }

    /**
     * 非对称加密 私钥钥加密---公钥解密
     * */
    private static void test3() throws Exception {
        Map<String, Object> map = Test.initKey();
        String publicKey = Test.getPublicKey(map);
        String privateKey = Test.getPrivateKey(map);
        //System.out.println("公钥加密后:" + publicKey + "\n私钥加密后" + privateKey);
        String input = "duwenlei";
        byte[] data = input.getBytes();
        byte[] encData = Test.encryptByPrivateKey(data, privateKey.getBytes());
        byte[] decData = Test.decryptByPublicKey(encData, publicKey.getBytes());
        String output = new String(decData);
        System.out.println("加密前:" + input);
        System.out.println("解密后:" + output);
    }

    /**
     * 非对称加密 公钥加密---私钥解密
     * */
    private static void test2() throws Exception {
        Map<String, Object> map = Test.initKey();
        String publicKey = Test.getPublicKey(map);
        String privateKey = Test.getPrivateKey(map);
        //System.out.println("公钥加密后:" + publicKey + "\n私钥加密后" + privateKey);
        String input = "duwenlei";
        byte[] data = input.getBytes();
        byte[] encData = Test.encryptByPublicKey(data, publicKey.getBytes());
        byte[] decData = Test.decryptByPrivateKey(encData, privateKey.getBytes());
        String output = new String(decData);
        System.out.println("加密前:" + input);
        System.out.println("解密后:" + output);
    }

    /**
     * 对称加密
     * */
    private static void test1() throws Exception {
        String key = "1234567890abcDEF";
        String src = "我的qq是823633682,我的密asdfasdfasdfasdfasdfasdfasdfasdf码是123456@126.com";
        // 加密
        String encStr = Test.Encrypt(src.getBytes(), key.getBytes("ASCII"));
        // 解密
        String decStr = Test.Decrypt(encStr, key.getBytes("ASCII"));
        System.out.println("加密后:" + encStr);
        System.out.println("解密后:" + decStr);
    }

    /**
     * 对称算法加密
     * 
     * @param cSrc
     *            : 要加密的数据
     * @param key
     *            :加密用到的Key , key需要满足16位
     * @return
     * @throws Exception
     */
    public static String symmetricEnc(byte[] src, byte[] key) throws Exception {
        String encStr = Test.Encrypt(src, key);
        return encStr;
    }

    /**
     * 对称算法解密
     * 
     * @param encStr
     *            : 加密后的数据
     * @return
     * @throws Exception
     */
    public static String symmetricDec(String encStr, String Key)
            throws Exception {
        String decStr = Test.Decrypt(encStr, Key.getBytes("ASCII"));
        return decStr;
    }

    /******************************************************* 下面是算法 *************************************************************************/
    
    


    /**************************************************************base64 加解密模板方法****************************************************************************/    
    /**
     * BASE64解密
     * 
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] decryptBASE64(byte[] key) throws Exception {
        return (new BASE64Decoder()).decodeBuffer(new String(key));
    }

    /**
     * BASE64加密
     * 
     * @param key
     * @return
     * @throws Exception
     */
    public static String encryptBASE64(byte[] key) throws Exception {
        return (new BASE64Encoder()).encodeBuffer(key);
    }

    
    /**************************************************************公钥解密,私钥解密模板方法****************************************************************************/    
    /**
     * 解密<br>
     * 用私钥解密
     * 
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPrivateKey(byte[] data, byte[] key)
            throws Exception {
        // 对密钥解密
        byte[] keyBytes = decryptBASE64(key);

        // 取得私钥
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);

        // 对数据解密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privateKey);

        return cipher.doFinal(data);
    }

    /**
     * 解密<br>
     * 用公钥解密
     * 
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPublicKey(byte[] data, byte[] key)
            throws Exception {
        // 对密钥解密
        byte[] keyBytes = decryptBASE64(key);

        // 取得公钥
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicKey = keyFactory.generatePublic(x509KeySpec);

        // 对数据解密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, publicKey);

        return cipher.doFinal(data);
    }

    /**************************************************************公钥加密,私钥加密模板方法****************************************************************************/
    /**
     * 加密<br>
     * 用公钥加密
     * 
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPublicKey(byte[] data, byte[] key)
            throws Exception {
        // 对公钥解密
        byte[] keyBytes = decryptBASE64(key);

        // 取得公钥
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicKey = keyFactory.generatePublic(x509KeySpec);

        // 对数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);

        return cipher.doFinal(data);
    }

    /**
     * 加密<br>
     * 用私钥加密
     * 
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPrivateKey(byte[] data, byte[] key)
            throws Exception {
        // 对密钥解密
        byte[] keyBytes = decryptBASE64(key);

        // 取得私钥
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);

        // 对数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        return cipher.doFinal(data);
    }

    /****************************************对称加解密模板方法*********************************************************/
    public static String Decrypt(String sSrc, byte[] sKey) throws Exception {
        try {
            // 判断Key是否正确
            if (sKey == null) {
                System.out.print("Key为空null");
                return null;
            }
            SecretKeySpec skeySpec = new SecretKeySpec(sKey, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] encrypted1 = hex2byte(sSrc.toString());
            try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original);
                return originalString;
            } catch (Exception e) {
                System.out.println(e.toString());
                return null;
            }
        } catch (Exception ex) {
            System.out.println(ex.toString());
            return null;
        }
    }

    // 判断Key是否正确
    public static String Encrypt(byte[] sSrc, byte[] sKey) throws Exception {
        if(sKey == null){
            System.out.println("Key不能为空!");
            return null;
        }
        SecretKeySpec skeySpec = new SecretKeySpec(sKey, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(sSrc);
        return byte2hex(encrypted).toLowerCase();
    }

    /*************************************二进制转16进制*****************************************/
    public static byte[] hex2byte(String strhex) {
        if (strhex == null) {
            return null;
        }
        int l = strhex.length();
        if (l % 2 == 1) {
            return null;
        }
        byte[] b = new byte[l / 2];
        for (int i = 0; i != l / 2; i++) {
            b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2),
                    16);
        }
        return b;
    }

    public static String byte2hex(byte[] b) {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1) {
                hs = hs + "0" + stmp;
            } else {
                hs = hs + stmp ;
            }
        }
        return hs.toUpperCase();
    }

    /**
     * 二进制转16进制
     * @param b
     * @return
     */
    public static String hexbyteString(byte[] b) {
        String result = "";
        for (int i = 0; i < b.length; i++) {
            String temp = Integer.toHexString(b[i] & 0xFF);
            if (temp.length() == 1) {
                temp = "0" + temp;
            }
            result += "0x" + temp + ", ";
        }
        return result;
    }
/*****************************************************************非对称加密一些初始化工作***************************************************************************************/    
    // 公钥的key
    private static final String PUBLIC_KEY = "RSAPublicKey";
    // 私钥的Key
    private static final String PRIVATE_KEY = "RSAPrivateKey";
    // 算法 AES
    private static final String KEY_ALGORITHM = "RSA";

    /**
     * 初始化密钥
     * 
     * @return
     * @throws Exception
     */
    public static Map<String, Object> initKey() throws Exception {
        KeyPairGenerator keyPairGen = KeyPairGenerator
                .getInstance(KEY_ALGORITHM);
        keyPairGen.initialize(1024);

        KeyPair keyPair = keyPairGen.generateKeyPair();

        // 公钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

        // 私钥
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

        Map<String, Object> keyMap = new HashMap<String, Object>(2);

        keyMap.put(PUBLIC_KEY, publicKey);
        keyMap.put(PRIVATE_KEY, privateKey);
        return keyMap;
    }

    public static String sign(byte[] data, byte[] privateKey) throws Exception {
        // 解密由base64编码的私钥
        byte[] keyBytes = decryptBASE64(privateKey);

        // 构造PKCS8EncodedKeySpec对象
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);

        // KEY_ALGORITHM 指定的加密算法
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

        // 取私钥匙对象
        PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);

        // 用私钥对信息生成数字签名
        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initSign(priKey);
        signature.update(data);

        return encryptBASE64(signature.sign());
    }

    /**
     * 取得私钥
     * 
     * @param keyMap
     * @return
     * @throws Exception
     */
    public static String getPrivateKey(Map<String, Object> keyMap)
            throws Exception {
        Key key = (Key) keyMap.get(PRIVATE_KEY);

        return encryptBASE64(key.getEncoded());
    }

    /**
     * 取得公钥
     * 
     * @param keyMap
     * @return
     * @throws Exception
     */
    public static String getPublicKey(Map<String, Object> keyMap)
            throws Exception {
        Key key = (Key) keyMap.get(PUBLIC_KEY);

        return encryptBASE64(key.getEncoded());
    }    
}

 

posted @ 2015-03-06 11:18  哎呦喂,我的小祖宗╰つ  阅读(160)  评论(0编辑  收藏  举报