1. 程式人生 > >對稱加密與非對稱加密理解和非對稱加密的java例子

對稱加密與非對稱加密理解和非對稱加密的java例子

package com.zl.test3;

import java.io.BufferedReader;  
import java.io.BufferedWriter;  
import java.io.ByteArrayOutputStream;
import java.io.FileReader;  
import java.io.FileWriter;  
import java.io.IOException;  
import java.security.InvalidKeyException;  
import java.security.KeyFactory;  
import java.security.KeyPair;  
import java.security.KeyPairGenerator;  
import java.security.NoSuchAlgorithmException;  
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 javax.crypto.BadPaddingException;  
import javax.crypto.Cipher;  
import javax.crypto.IllegalBlockSizeException;  
import javax.crypto.NoSuchPaddingException;  
  
  
public class RSAEncrypt {  
    /** 
     * 位元組資料轉字串專用集合 
     */  
    private static final char[] HEX_CHAR = { '0', '1', '2', '3', '4', '5', '6',  
            '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };  
  
    /** 
     * 隨機生成金鑰對 
     */  
    public static void genKeyPair(String filePath) {  
        // KeyPairGenerator類用於生成公鑰和私鑰對,基於RSA演算法生成物件  
        KeyPairGenerator keyPairGen = null;  
        try {  
            keyPairGen = KeyPairGenerator.getInstance("RSA");  
        } catch (NoSuchAlgorithmException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
        // 初始化金鑰對生成器,金鑰大小為96-1024位  
        keyPairGen.initialize(1024,new SecureRandom());  
        // 生成一個金鑰對,儲存在keyPair中  
        KeyPair keyPair = keyPairGen.generateKeyPair();  
        // 得到私鑰  
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();  
        // 得到公鑰  
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  
        try {  
            // 得到公鑰字串  
            String publicKeyString = Base64.encode(publicKey.getEncoded());  
            // 得到私鑰字串  
            String privateKeyString = Base64.encode(privateKey.getEncoded());  
            // 將金鑰對寫入到檔案  
            FileWriter pubfw = new FileWriter(filePath + "/publicKey.keystore");  
            FileWriter prifw = new FileWriter(filePath + "/privateKey.keystore");  
            BufferedWriter pubbw = new BufferedWriter(pubfw);  
            BufferedWriter pribw = new BufferedWriter(prifw);  
            pubbw.write(publicKeyString);  
            pribw.write(privateKeyString);  
            pubbw.flush();  
            pubbw.close();  
            pubfw.close();  
            pribw.flush();  
            pribw.close();  
            prifw.close();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
  
    /** 
     * 從檔案中輸入流中載入公鑰 
     *  
     * @param in 
     *            公鑰輸入流 
     * @throws Exception 
     *             載入公鑰時產生的異常 
     */  
    public static String loadPublicKeyByFile(String path) throws Exception {  
        try {  
            BufferedReader br = new BufferedReader(new FileReader(path  
                    + "/publicKey.keystore"));  
            String readLine = null;  
            StringBuilder sb = new StringBuilder();  
            while ((readLine = br.readLine()) != null) {  
                sb.append(readLine);  
            }  
            br.close();  
            return sb.toString();  
        } catch (IOException e) {  
            throw new Exception("公鑰資料流讀取錯誤");  
        } catch (NullPointerException e) {  
            throw new Exception("公鑰輸入流為空");  
        }  
    }  
  
    /** 
     * 從字串中載入公鑰 
     *  
     * @param publicKeyStr 
     *            公鑰資料字串 
     * @throws Exception 
     *             載入公鑰時產生的異常 
     */  
    public static RSAPublicKey loadPublicKeyByStr(String publicKeyStr)  
            throws Exception {  
        try {  
            byte[] buffer = Base64.decode(publicKeyStr);  
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");  
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);  
            return (RSAPublicKey) keyFactory.generatePublic(keySpec);  
        } catch (NoSuchAlgorithmException e) {  
            throw new Exception("無此演算法");  
        } catch (InvalidKeySpecException e) {  
            throw new Exception("公鑰非法");  
        } catch (NullPointerException e) {  
            throw new Exception("公鑰資料為空");  
        }  
    }  
  
    /** 
     * 從檔案中載入私鑰 
     *  
     * @param keyFileName 
     *            私鑰檔名 
     * @return 是否成功 
     * @throws Exception 
     */  
    public static String loadPrivateKeyByFile(String path) throws Exception {  
        try {  
            BufferedReader br = new BufferedReader(new FileReader(path  
                    + "/privateKey.keystore"));  
            String readLine = null;  
            StringBuilder sb = new StringBuilder();  
            while ((readLine = br.readLine()) != null) {  
                sb.append(readLine);  
            }  
            br.close();  
            return sb.toString();  
        } catch (IOException e) {  
            throw new Exception("私鑰資料讀取錯誤");  
        } catch (NullPointerException e) {  
            throw new Exception("私鑰輸入流為空");  
        }  
    }  
  
    public static RSAPrivateKey loadPrivateKeyByStr(String privateKeyStr)  
            throws Exception {  
        try {  
            byte[] buffer = Base64.decode(privateKeyStr);  
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);  
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");  
            return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);  
        } catch (NoSuchAlgorithmException e) {  
            throw new Exception("無此演算法");  
        } catch (InvalidKeySpecException e) {  
            throw new Exception("私鑰非法");  
        } catch (NullPointerException e) {  
            throw new Exception("私鑰資料為空");  
        }  
    }  
  
    /** 
     * 公鑰加密過程 
     *  
     * @param publicKey 
     *            公鑰 
     * @param plainTextData 
     *            明文資料 
     * @return 
     * @throws Exception 
     *             加密過程中的異常資訊 
     */  
    public static byte[] encrypt(RSAPublicKey publicKey, byte[] data)  
            throws Exception {  
        if (publicKey == null) {  
            throw new Exception("加密公鑰為空, 請設定");  
        }  
        Cipher cipher = null;  
        try {  
            // 使用預設RSA  
            cipher = Cipher.getInstance("RSA");  
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);  
            int inputLen = data.length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offSet = 0;
            byte[] cache;
            int i = 0;
            // 對資料分段加密
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > 117) {
                    cache = cipher.doFinal(data, offSet, 117);
                } else {
                    cache = cipher.doFinal(data, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * 117;
            }
            byte[] encryptedData = out.toByteArray();
            out.close();
            return encryptedData;
//            byte[] output = cipher.doFinal(data);  
//            return output;  
        } catch (NoSuchAlgorithmException e) {  
            throw new Exception("無此加密演算法");  
        } catch (NoSuchPaddingException e) {  
            e.printStackTrace();  
            return null;  
        } catch (InvalidKeyException e) {  
            throw new Exception("加密公鑰非法,請檢查");  
        } catch (IllegalBlockSizeException e) {  
            throw new Exception("明文長度非法");  
        } catch (BadPaddingException e) {  
            throw new Exception("明文資料已損壞");  
        }  
    }  
  
    /** 
     * 私鑰加密過程 
     *  
     * @param privateKey 
     *            私鑰 
     * @param plainTextData 
     *            明文資料 
     * @return 
     * @throws Exception 
     *             加密過程中的異常資訊 
     */  
    public static byte[] encrypt(RSAPrivateKey privateKey, byte[] plainTextData)  
            throws Exception {  
        if (privateKey == null) {  
            throw new Exception("加密私鑰為空, 請設定");  
        }  
        Cipher cipher = null;  
        try {  
            // 使用預設RSA  
            cipher = Cipher.getInstance("RSA");  
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);  
         // 加密時超過117位元組就報錯。為此採用分段加密的辦法來加密  
            byte[] output = cipher.doFinal(plainTextData);  
            return output;  
        } catch (NoSuchAlgorithmException e) {  
            throw new Exception("無此加密演算法");  
        } catch (NoSuchPaddingException e) {  
            e.printStackTrace();  
            return null;  
        } catch (InvalidKeyException e) {  
            throw new Exception("加密私鑰非法,請檢查");  
        } catch (IllegalBlockSizeException e) {  
            throw new Exception("明文長度非法");  
        } catch (BadPaddingException e) {  
            throw new Exception("明文資料已損壞");  
        }  
    }  
  
    /** 
     * 私鑰解密過程 
     *  
     * @param privateKey 
     *            私鑰 
     * @param cipherData 
     *            密文資料 
     * @return 明文 
     * @throws Exception 
     *             解密過程中的異常資訊 
     */  
    public static byte[] decrypt(RSAPrivateKey privateKey, byte[] encryptedData)  
            throws Exception {  
        if (privateKey == null) {  
            throw new Exception("解密私鑰為空, 請設定");  
        }  
        Cipher cipher = null;  
        try {  
            // 使用預設RSA  
            cipher = Cipher.getInstance("RSA");  
            // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());  
            cipher.init(Cipher.DECRYPT_MODE, privateKey);  
            int inputLen = encryptedData.length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offSet = 0;
            byte[] cache;
            int i = 0;
            // 對資料分段解密
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > 128) {
                    cache = cipher.doFinal(encryptedData, offSet, 128);
                } else {
                    cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * 128;
            }
            byte[] decryptedData = out.toByteArray();
            out.close();
            return decryptedData;
//            byte[] output = cipher.doFinal(encryptedData);  
//            return output;  
        } catch (NoSuchAlgorithmException e) {  
            throw new Exception("無此解密演算法");  
        } catch (NoSuchPaddingException e) {  
            e.printStackTrace();  
            return null;  
        } catch (InvalidKeyException e) {  
            throw new Exception("解密私鑰非法,請檢查");  
        } catch (IllegalBlockSizeException e) {  
            throw new Exception("密文長度非法");  
        } catch (BadPaddingException e) {  
            throw new Exception("密文資料已損壞");  
        }  
    }  
  
    /** 
     * 公鑰解密過程 
     *  
     * @param publicKey 
     *            公鑰 
     * @param cipherData 
     *            密文資料 
     * @return 明文 
     * @throws Exception 
     *             解密過程中的異常資訊 
     */  
    public static byte[] decrypt(RSAPublicKey publicKey, byte[] cipherData)  
            throws Exception {  
        if (publicKey == null) {  
            throw new Exception("解密公鑰為空, 請設定");  
        }  
        Cipher cipher = null;  
        try {  
            // 使用預設RSA  
            cipher = Cipher.getInstance("RSA");  
            // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());  
            cipher.init(Cipher.DECRYPT_MODE, publicKey); 
            byte[] output = cipher.doFinal(cipherData);  
            return output;  
        } catch (NoSuchAlgorithmException e) {  
            throw new Exception("無此解密演算法");  
        } catch (NoSuchPaddingException e) {  
            e.printStackTrace();  
            return null;  
        } catch (InvalidKeyException e) {  
            throw new Exception("解密公鑰非法,請檢查");  
        } catch (IllegalBlockSizeException e) {  
            throw new Exception("密文長度非法");  
        } catch (BadPaddingException e) {  
            throw new Exception("密文資料已損壞");  
        }  
    }  
  
    /** 
     * 位元組資料轉十六進位制字串 
     *  
     * @param data 
     *            輸入資料 
     * @return 十六進位制內容 
     */  
    public static String byteArrayToString(byte[] data) {  
        StringBuilder stringBuilder = new StringBuilder();  
        for (int i = 0; i < data.length; i++) {  
            // 取出位元組的高四位 作為索引得到相應的十六進位制識別符號 注意無符號右移  
            stringBuilder.append(HEX_CHAR[(data[i] & 0xf0) >>> 4]);  
            // 取出位元組的低四位 作為索引得到相應的十六進位制識別符號  
            stringBuilder.append(HEX_CHAR[(data[i] & 0x0f)]);  
            if (i < data.length - 1) {  
                stringBuilder.append(' ');  
            }  
        }  
        return stringBuilder.toString();  
    }  
}  
3.2
package com.zl.test3;
/**
 * 
 * @author zenglong
 *
 * @Description: Base64演算法
 *
 */
public final class Base64 {  
	  
    static private final int     BASELENGTH           = 128;  
    static private final int     LOOKUPLENGTH         = 64;  
    static private final int     TWENTYFOURBITGROUP   = 24;  
    static private final int     EIGHTBIT             = 8;  
    static private final int     SIXTEENBIT           = 16;  
    static private final int     FOURBYTE             = 4;  
    static private final int     SIGN                 = -128;  
    static private final char    PAD                  = '=';  
    static private final boolean fDebug               = false;  
    static final private byte[]  base64Alphabet       = new byte[BASELENGTH];  
    static final private char[]  lookUpBase64Alphabet = new char[LOOKUPLENGTH];  
  
    static {  
        for (int i = 0; i < BASELENGTH; ++i) {  
            base64Alphabet[i] = -1;  
        }  
        for (int i = 'Z'; i >= 'A'; i--) {  
            base64Alphabet[i] = (byte) (i - 'A');  
        }  
        for (int i = 'z'; i >= 'a'; i--) {  
            base64Alphabet[i] = (byte) (i - 'a' + 26);  
        }  
  
        for (int i = '9'; i >= '0'; i--) {  
            base64Alphabet[i] = (byte) (i - '0' + 52);  
        }  
  
        base64Alphabet['+'] = 62;  
        base64Alphabet['/'] = 63;  
  
        for (int i = 0; i <= 25; i++) {  
            lookUpBase64Alphabet[i] = (char) ('A' + i);  
        }  
  
        for (int i = 26, j = 0; i <= 51; i++, j++) {  
            lookUpBase64Alphabet[i] = (char) ('a' + j);  
        }  
  
        for (int i = 52, j = 0; i <= 61; i++, j++) {  
            lookUpBase64Alphabet[i] = (char) ('0' + j);  
        }  
        lookUpBase64Alphabet[62] = (char) '+';  
        lookUpBase64Alphabet[63] = (char) '/';  
  
    }  
  
    private static boolean isWhiteSpace(char octect) {  
        return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);  
    }  
  
    private static boolean isPad(char octect) {  
        return (octect == PAD);  
    }  
  
    private static boolean isData(char octect) {  
        return (octect < BASELENGTH && base64Alphabet[octect] != -1);  
    }  
  
    /** 
     * Encodes hex octects into Base64 
     * 
     * @param binaryData Array containing binaryData 
     * @return Encoded Base64 array 
     */  
    public static String encode(byte[] binaryData) {  
  
        if (binaryData == null) {  
            return null;  
        }  
  
        int lengthDataBits = binaryData.length * EIGHTBIT;  
        if (lengthDataBits == 0) {  
            return "";  
        }  
  
        int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;  
        int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;  
        int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1 : numberTriplets;  
        char encodedData[] = null;  
  
        encodedData = new char[numberQuartet * 4];  
  
        byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;  
  
        int encodedIndex = 0;  
        int dataIndex = 0;  
        if (fDebug) {  
            System.out.println("number of triplets = " + numberTriplets);  
        }  
  
        for (int i = 0; i < numberTriplets; i++) {  
            b1 = binaryData[dataIndex++];  
            b2 = binaryData[dataIndex++];  
            b3 = binaryData[dataIndex++];  
  
            if (fDebug) {  
                System.out.println("b1= " + b1 + ", b2= " + b2 + ", b3= " + b3);  
            }  
  
            l = (byte) (b2 & 0x0f);  
            k = (byte) (b1 & 0x03);  
  
            byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);  
            byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);  
            byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc);  
  
            if (fDebug) {  
                System.out.println("val2 = " + val2);  
                System.out.println("k4   = " + (k << 4));  
                System.out.println("vak  = " + (val2 | (k << 4)));  
            }  
  
            encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];  
            encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];  
            encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3];  
            encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f];  
        }  
  
        // form integral number of 6-bit groups  
        if (fewerThan24bits == EIGHTBIT) {  
            b1 = binaryData[dataIndex];  
            k = (byte) (b1 & 0x03);  
            if (fDebug) {  
                System.out.println("b1=" + b1);  
                System.out.println("b1<<2 = " + (b1 >> 2));  
            }  
            byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);  
            encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];  
            encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4];  
            encodedData[encodedIndex++] = PAD;  
            encodedData[encodedIndex++] = PAD;  
        } else if (fewerThan24bits == SIXTEENBIT) {  
            b1 = binaryData[dataIndex];  
            b2 = binaryData[dataIndex + 1];  
            l = (byte) (b2 & 0x0f);  
            k = (byte) (b1 & 0x03);  
  
            byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);  
            byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);  
  
            encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];  
            encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];  
            encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2];  
            encodedData[encodedIndex++] = PAD;  
        }  
  
        return new String(encodedData);  
    }  
  
    /** 
     * Decodes Base64 data into octects 
     * 
     * @param encoded string containing Base64 data 
     * @return Array containind decoded data. 
     */  
    public static byte[] decode(String encoded) {  
  
        if (encoded == null) {  
            return null;  
        }  
  
        char[] base64Data = encoded.toCharArray();  
        // remove white spaces  
        int len = removeWhiteSpace(base64Data);  
  
        if (len % FOURBYTE != 0) {  
            return null;//should be divisible by four  
        }  
  
        int numberQuadruple = (len / FOURBYTE);  
  
        if (numberQuadruple == 0) {  
            return new byte[0];  
        }  
  
        byte decodedData[] = null;  
        byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;  
        char d1 = 0, d2 = 0, d3 = 0, d4 = 0;  
  
        int i = 0;  
        int encodedIndex = 0;  
        int dataIndex = 0;  
        decodedData = new byte[(numberQuadruple) * 3];  
  
        for (; i < numberQuadruple - 1; i++) {  
  
            if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))  
                || !isData((d3 = base64Data[dataIndex++]))  
                || !isData((d4 = base64Data[dataIndex++]))) {  
                return null;  
            }//if found "no data" just return null  
  
            b1 = base64Alphabet[d1];  
            b2 = base64Alphabet[d2];  
            b3 = base64Alphabet[d3];  
            b4 = base64Alphabet[d4];  
  
            decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);  
            decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));  
            decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);  
        }  
  
        if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))) {  
            return null;//if found "no data" just return null  
        }  
  
        b1 = base64Alphabet[d1];  
        b2 = base64Alphabet[d2];  
  
        d3 = base64Data[dataIndex++];  
        d4 = base64Data[dataIndex++];  
        if (!isData((d3)) || !isData((d4))) {//Check if they are PAD characters  
            if (isPad(d3) && isPad(d4)) {  
                if ((b2 & 0xf) != 0)//last 4 bits should be zero  
                {  
                    return null;  
                }  
                byte[] tmp = new byte[i * 3 + 1];  
                System.arraycopy(decodedData, 0, tmp, 0, i * 3);  
                tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);  
                return tmp;  
            } else if (!isPad(d3) && isPad(d4)) {  
                b3 = base64Alphabet[d3];  
                if ((b3 & 0x3) != 0)//last 2 bits should be zero  
                {  
                    return null;  
                }  
                byte[] tmp = new byte[i * 3 + 2];  
                System.arraycopy(decodedData, 0, tmp, 0, i * 3);  
                tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);  
                tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));  
                return tmp;  
            } else {  
                return null;  
            }  
        } else { //No PAD e.g 3cQl  
            b3 = base64Alphabet[d3];  
            b4 = base64Alphabet[d4];  
            decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);  
            decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));  
            decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);  
  
        }  
  
        return decodedData;  
    }  
  
    /** 
     * remove WhiteSpace from MIME containing encoded Base64 data. 
     * 
     * @param data  the byte array of base64 data (with WS) 
     * @return      the new length 
     */  
    private static int removeWhiteSpace(char[] data) {  
        if (data == null) {  
            return 0;  
        }  
  
        // count characters that's not whitespace  
        int newSize = 0;  
        int len = data.length;  
        for (int i = 0; i < len; i++) {  
            if (!isWhiteSpace(data[i])) {  
                data[newSize++] = data[i];  
            }  
        }  
        return newSize;  
    }  
}  
package com.zl.test3;

public class MainTest {  
	  
    public static void main(String[] args) throws Exception {  
        String filepath="F:/javaee/bgyworkspace/Security/doc";  
  
          
          
        System.out.println("--------------公鑰加密私鑰解密過程-------------------");  
//        String plainText="ihep_公鑰加密私鑰解密";  
        String  json="{"
		  		+ "\"bgyprogressuuid\": \"aabc891fc62f41728497da2904294e16\","
		  		+ "\"bgysupplier\": \"供應商名稱3\","
				 + " \"bgyitemname\": \"專案公司名稱3\","
				    + "\"bgyitemcode\": \"0003\","
				    + "\"bgyarea\": \"佛山區域3\","
				    + "\"bgycontractname\": \"合同名稱\","
				    + "\"bgycontractno\": \"合同編號003\","
				    + "\"bgypayamount\": 888.989,"
				    + "\"bgysupplierbank\": \"供應商開戶行:中國銀行\","
				    + "\"bgysupplieraccount\": \"供應商賬號:88888989989\","
				    + "\"bgysupplieraccountname\": \"收方戶名:佛山碧桂園\","
				    + "\"bgypaystatus\": false,"
				    + "\"dr\": 0}"
				    +"{"
			  		+ "\"bgyprogressuuid\": \"aabc891fc62f41728497da2904294e15\","
			  		+ "\"bgysupplier\": \"供應商名稱3\","
					 + " \"bgyitemname\": \"專案公司名稱3\","
					    + "\"bgyitemcode\": \"0003\","
					    + "\"bgyarea\": \"佛山區域3\","
					    + "\"bgycontractname\": \"合同名稱\","
					    + "\"bgycontractno\": \"合同編號003\","
					    + "\"bgypayamount\": 888.989,"
					    + "\"bgysupplierbank\": \"供應商開戶行:中國銀行\","
					    + "\"bgysupplieraccount\": \"供應商賬號:88888989989\","
					    + "\"bgysupplieraccountname\": \"收方戶名:佛山碧桂園\","
					    + "\"bgypaystatus\": false,"
					    + "\"dr\": 0}";
        //公鑰加密過程  
        byte[] cipherData=RSAEncrypt.encrypt(RSAEncrypt.loadPublicKeyByStr(RSAEncrypt.loadPublicKeyByFile(filepath)),json.getBytes());  
        String cipher=Base64.encode(cipherData);  
        //私鑰解密過程  
        byte[] res=RSAEncrypt.decrypt(RSAEncrypt.loadPrivateKeyByStr(RSAEncrypt.loadPrivateKeyByFile(filepath)), Base64.decode(cipher));  
        String restr=new String(res);  
        System.out.println("原文:"+json);  
        System.out.println("加密:"+cipher);  
        System.out.println("解密:"+restr);  
        System.out.println();   
          
    }  
}  
4.原始碼下載地址:其中有3個例項,都是可以執行的,點選開啟連結
http://download.csdn.net/detail/qq_31968809/9777763


相關推薦

對稱加密對稱加密理解對稱加密java例子

package com.zl.test3; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.FileReader;

深入理解阻塞同步IO阻塞異步IO

sam log while循環 不清楚 重要 http 文章 最終 簡單 這兩篇文章分析了Linux下的5種IO模型 http://blog.csdn.net/historyasamirror/article/details/5778378 http://blog.csd

splitre.split/捕獲分組捕獲分組/startswithendswithfnmatch/finditer 筆記

split()對字串進行劃分: >>> a = 'a b c d' >>> a.split(' ') ['a', 'b', 'c', 'd']   複雜一些可以使用re.split() >>> import re >

@ResponseBodyPrintWriter(response.getWriter)理解用法區分

理解:很多情況我們需要在controller接收請求然後返回一些message。 在springmvc中當返回值是String時,如果不加@ResponseBody的話,返回的字串就會找這個String對應的頁面,如果找不到會報404錯誤。 如果加上@Res

幾個例子理解對稱加密對稱加密、公鑰私鑰、簽名驗籤、數字證書、HTTPS加密方式

# 原創,轉載請留言聯絡 為什麼會出現這麼多加密啊,公鑰私鑰啊,簽名啊這些東西呢?說到底還是保證雙方通訊的安全性與完整性。例如小明發一封表白郵件給小紅,他總不希望給別人看見吧。而各種各樣的技術就是為了保障通訊的安全。(本文務必從上到下看) 1.對稱加密與非對稱加密 對稱加密: 對稱加密是

對 【對稱加密對稱加密以及CA】的理解(二)

非對稱加密更加安全但是費時費力,對稱加密雖然省時,快速但是不安全,於是就可以將它倆結合起來使用。 結合思路是這樣的:檔案傳輸用對稱加密,對稱加密的加密和解密用的都是同一個金鑰,用非對稱加密的公鑰對此對稱加密的金鑰進行加密,然後傳送出去,接收方用非對稱加密的私鑰對剛才用公鑰加密過的對稱加密的金鑰進

對 【對稱加密對稱加密以及CA】的理解(一)

最近申請了阿里雲的伺服器,進入了一個新的領域,當然一開始也是懵逼狀態,處於雲裡霧裡,決定將自己學習的計算機網路的相關知識複習一下。 對稱加密:即通訊雙方在對傳輸的檔案進行加密和解密時候,所用的是同一個金鑰。 優點:速度快,對稱性加密通常在訊息傳送方需要加密大量資料時使用,演算法公開、計算量小

Http協議請求, Post請求Get請求的區別,Base64URL編碼,md5,sha-1加密,對稱對稱加密,支付寶微信第三方支付

Http協議與請求 Post請求 Post請求與Get請求的區別 Get請求的引數是直接放在url後面的,而Post請求是放在請求體中的 Get請求引數的長度會根據瀏覽器的不同實現有一定限制,而Post請求引數長度沒有限制

對稱加密對稱加密理解

對稱加密的缺點: 1、金鑰數太多,每兩個人之間就要有一個金鑰,n個人就要有n*(n-1)個金鑰 2、金鑰洩露 3、無法驗證接受者和傳送者身份 總結: 公鑰加密,私鑰解密 反過來是私鑰數字簽名,證明發送者是傳送者本人

安全科普:理解SSL(https)中的對稱加密對稱加密

轉:http://www.freebuf.com/articles/system/37624.html 今天剛好為站點的後臺弄了下https,就來分享我瞭解的吧。 密碼學最早可以追溯到古希臘羅馬時代,那時的加密方法很簡單:替換字母。 早期的密碼學: 古希臘人用一種叫  的工具加密。更快的工具是 —:只

【IoT】加密安全:對稱加密演算法 RSA 1024 公鑰、祕鑰、明文密文長度

RSA 1024 是指公鑰及私鑰分別是 1024bit,也就是 1024/8 = 128Bytes。 RSA 演算法金鑰長度的選擇是安全性和程式效能平衡的結果,金鑰長度越長,安全性越好,加密解密所需時間越長。 1、非對稱加密演算法中 1024bit 金鑰的強度相當於對稱加

對稱加密對稱加密

通過 lan pan 消息加密 ack 屬於 加密算法 效率 構建 1.對稱加密 對稱加密(也叫私鑰加密)指加密和解密使用相同密鑰的加密算法。有時又叫傳統密碼算法,就是加密密鑰能夠從解密密鑰中推算出來,同時解密密鑰也可以從加密密鑰中推算出來。而在大多數的對稱算法中,加密密

如何使用gpg工具實現公鑰加密對稱加密對稱加密)?

gpg工具 對稱加密 公鑰加密 非對稱加密 使用gpg實現公鑰加密【對稱加密】1、 對稱加密file文件gpg -c filels file.gpg------------------------對稱加密過程------------------------輸入口令,兩次,例如centos再查看

Java加密解密筆記(三) 對稱加密

arr 內容 phy 資料 密碼 load esp uid user 非對稱的特點是加密和解密時使用的是不同的鑰匙。密鑰分為公鑰和私鑰,用公鑰加密的數據只能用私鑰進行解密,反之亦然。 另外,密鑰還可以用於數字簽名。數字簽名跟上文說的消息摘要是一個道理,通過一定方法對數據內容

對稱加密對稱加密

.com 對稱加密 alt str mage nbsp com strong bubuko 對稱加密和非對稱加密

第10章 網路安全(1)_對稱加密對稱加密

1 網路安全概述 1.1 計算機網路面臨的安全威協 (1)截獲:攻擊者從網路上竊聽他人的通訊內容,通常把這類攻擊稱為“截獲”。在被動攻擊中,攻擊者只是觀察和分析某一個協議資料單元(PDU)而不干擾資訊流。 (2)篡改:攻擊者篡改網路上傳遞的報文。這裡包括徹底中斷傳遞的報文,甚至把完

對稱加密GPG/PGP

最近瀏覽部落格的時候,經常會看到博主展示出自己的公鑰,於是對 GPG/PGP 產生興趣。下面簡單記錄相關文章的連結,方便以後瞭解。 簡介: 1991年,程式設計師Phil Zimmermann為了避開政府的監視,開發了加密軟體PGP。因為這個軟體非常好用,迅速流傳開來成為許多程式設計師的必備工具。但是,它

最全加密演算法之對稱加密對稱加密

常見加密演算法 : DES(Data Encryption Standard):資料加密標準,速度較快,適用於加密大量資料的場合;  3DES(Triple DES):是基於DES,對一塊資料用三個不同的金鑰進行三次加密,強度更高; RC2和 RC4:用變長金鑰對大量資

golang[34]-區塊鏈-對稱加密對稱加密

對稱加密 對稱金鑰加密(英語:Symmetric-key algorithm)又稱為對稱加密、私鑰加密、共享金鑰加密,是密碼學中的一類加密演算法。這類演算法在加密和解密時使用相同的金鑰,或是使用兩個可以簡單地相互推算的金鑰。事實上,這組金鑰成為在兩個或多個成員間的共同祕密,以便維持專屬的通訊聯絡。與公開

對稱加密對稱加密、數字簽名、數字證書的區別

之前在面試的時候被問到了HTTPS,SSL這樣的知識點,也沒答上來,這裡也簡單整理一下。 首先還是來解釋一下基礎的東東: 對稱加密: 加密和解密都是用同一個金鑰 非對稱加密: 加密用公開的金鑰,解密用私鑰 (私鑰只有自己知道