JAVA產生RSA非對稱型加密的公開金鑰和私密金鑰(利用JAVA API)

來源:互聯網
上載者:User

標籤:

非對稱型加密非常適合多個用戶端和伺服器之間的秘密通訊,用戶端使用同一個公開金鑰將明文加密,而這個公開金鑰不能逆向的解密,密文發送到伺服器後有伺服器端用私密金鑰解密,這樣就做到了明文的加密傳送。 

非對稱型加密也有它先天的缺點,加密、解密速度慢制約了它的發揮,如果你有大量的文字需要加密傳送,建議你通過非對稱型加密來把對稱型‘密鑰’分發到用戶端,及時更新對稱型‘密鑰’。 

package com.paul.module.common.util;import sun.misc.BASE64Decoder;import sun.misc.BASE64Encoder;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.security.Key;import java.security.KeyPair;import java.security.KeyPairGenerator;import javax.crypto.Cipher;public class RSASecurityUtil2 {    /** 指定密碼編譯演算法為RSA */    private static final String ALGORITHM = "RSA";    /** 密鑰長度,用來初始化 */    private static final int KEYSIZE = 1024;    /** 指定公開金鑰存放檔案 */    private static String PUBLIC_KEY_FILE = "PublicKey";    /** 指定私密金鑰存放檔案 */    private static String PRIVATE_KEY_FILE = "PrivateKey";    /**     * 產生金鑰組     * @throws Exception     */    private static void generateKeyPair() throws Exception {        //        /** RSA演算法要求有一個可信任的隨機數源 *///        SecureRandom secureRandom = new SecureRandom();                /** 為RSA演算法建立一個KeyPairGenerator對象 */        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);                /** 利用上面的隨機資料來源初始化這個KeyPairGenerator對象 *///        keyPairGenerator.initialize(KEYSIZE, secureRandom);        keyPairGenerator.initialize(KEYSIZE);                /** 產生密匙對 */        KeyPair keyPair = keyPairGenerator.generateKeyPair();                /** 得到公開金鑰 */        Key publicKey = keyPair.getPublic();                /** 得到私密金鑰 */        Key privateKey = keyPair.getPrivate();                ObjectOutputStream oos1 = null;        ObjectOutputStream oos2 = null;        try {            /** 用物件流程將產生的密鑰寫入檔案 */            oos1 = new ObjectOutputStream(new FileOutputStream(PUBLIC_KEY_FILE));            oos2 = new ObjectOutputStream(new FileOutputStream(PRIVATE_KEY_FILE));            oos1.writeObject(publicKey);            oos2.writeObject(privateKey);        } catch (Exception e) {            throw e;        }        finally{            /** 清空緩衝,關閉檔案輸出資料流 */            oos1.close();            oos2.close();        }    }    /**     * 加密方法     * @param source 來源資料     * @return     * @throws Exception     */    public static String encrypt(String source) throws Exception {        generateKeyPair();        Key publicKey;        ObjectInputStream ois = null;        try {            /** 將檔案中的公開金鑰對象讀出 */            ois = new ObjectInputStream(new FileInputStream(                    PUBLIC_KEY_FILE));            publicKey = (Key) ois.readObject();        } catch (Exception e) {            throw e;        }        finally{            ois.close();        }                /** 得到Cipher對象來實現對來源資料的RSA加密 */        Cipher cipher = Cipher.getInstance(ALGORITHM);        cipher.init(Cipher.ENCRYPT_MODE, publicKey);        byte[] b = source.getBytes();        /** 執行加密操作 */        byte[] b1 = cipher.doFinal(b);        BASE64Encoder encoder = new BASE64Encoder();        return encoder.encode(b1);    }    /**     * 解密演算法     * @param cryptograph    密文     * @return     * @throws Exception     */    public static String decrypt(String cryptograph) throws Exception {        Key privateKey;        ObjectInputStream ois = null;        try {            /** 將檔案中的私密金鑰對象讀出 */            ois = new ObjectInputStream(new FileInputStream(                    PRIVATE_KEY_FILE));            privateKey = (Key) ois.readObject();        } catch (Exception e) {            throw e;        }        finally{            ois.close();        }                /** 得到Cipher對象對已用公開金鑰加密的資料進行RSA解密 */        Cipher cipher = Cipher.getInstance(ALGORITHM);        cipher.init(Cipher.DECRYPT_MODE, privateKey);        BASE64Decoder decoder = new BASE64Decoder();        byte[] b1 = decoder.decodeBuffer(cryptograph);                /** 執行解密操作 */        byte[] b = cipher.doFinal(b1);        return new String(b);    }    public static void main(String[] args) throws Exception {        String source = "恭喜發財!";// 要加密的字串        System.out.println("準備用公開金鑰加密的字串為:" + source);                String cryptograph = encrypt(source);// 產生的密文        System.out.print("用公開金鑰加密後的結果為:" + cryptograph);        System.out.println();        String target = decrypt(cryptograph);// 解密密文        System.out.println("用私密金鑰解密後的字串為:" + target);        System.out.println();    }}

 

http://blog.sina.com.cn/s/blog_43b03c72010080t2.html
http://topic.csdn.net/t/20040510/14/3049788.html 
http://yuanliyin.iteye.com/blog/853334

JAVA產生RSA非對稱型加密的公開金鑰和私密金鑰(利用JAVA API)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.