1. 程式人生 > >Java幾種加密

Java幾種加密

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();
        }

    }

}