PublicKey加密解密入门代码

看到这个问题 http://www.iteye.com/problems/71360,决定试一试加密解密,结果如下:

环境:JDK 1.7.0

import java.io.ByteArrayOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class PublicKeyTest {
    public static void main(String args[]) throws
            NoSuchProviderException, NoSuchAlgorithmException,
            NoSuchPaddingException, InvalidKeyException,
            IllegalBlockSizeException, BadPaddingException,
            IOException {
        final KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        kpg.initialize(1024, new SecureRandom());
        final KeyPair kp = kpg.generateKeyPair();
        final PrivateKey priKey = kp.getPrivate();
        final PublicKey pubKey = kp.getPublic();

        String encrypted = encrypt(pubKey, "公共密匙", "UTF8");
        System.out.println(encrypted);
        String decrypted = decrypt(priKey, encrypted, "UTF8");
        System.out.println(decrypted);
        FileWriter writer = new FileWriter("text.txt");
        writer.write(decrypted);
        writer.flush();
        writer.close();
    }

    private static String encrypt(PublicKey pubKey, String message, String encoding) throws
            NoSuchAlgorithmException, NoSuchPaddingException,
            InvalidKeyException, IllegalBlockSizeException,
            BadPaddingException, IOException {
        // Get a cipher object.
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);

        byte[] bytes = message.getBytes(encoding);

        // encode the message
        final byte[] raw = doSafeFinal(cipher, bytes);

        // converts to base64 for easier display.
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(raw);
    }

    private static String decrypt(PrivateKey priKey, String encrypted, String encoding) throws
            InvalidKeyException, NoSuchAlgorithmException,
            NoSuchPaddingException, IllegalBlockSizeException,
            BadPaddingException, IOException {

        //decode the BASE64 coded message
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] raw = decoder.decodeBuffer(encrypted);

        // Get a cipher object.
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, priKey);

        // decode the message
        final byte[] bytes = doSafeFinal(cipher, raw);

        // converts the decoded message to a String
        return new String(bytes, encoding);
    }

    private static byte[] doSafeFinal(Cipher cipher, byte[] text) throws
            IllegalBlockSizeException, BadPaddingException,
            IOException {

        // avoid overrun the block size of the cipher
        int blockSize = cipher.getBlockSize();
        if (blockSize > 0) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int len;
            for (int offset = 0; offset < text.length; offset += blockSize) {
                if (text.length - offset <= blockSize) {
                    len = text.length - offset;
                } else {
                    len = blockSize;
                }
                out.write(cipher.doFinal(text, offset, len));
            }
            return out.toByteArray();
        } else {
            return cipher.doFinal(text);
        }
    }
}


注意:源文件要求UTF-8格式

参考文献:
1 JDK API 文档
2 JCE offers an API to leverage asymmetric cryptography http://www.techrepublic.com/article/jce-offers-an-api-to-leverage-asymmetric-cryptography/1049434
3 Secret Key Cryptography Tutorial http://www.wikijava.org/wiki/Secret_Key_Cryptography_Tutorial
4 What's wrong with IBM's JCE provider? http://www.ibm.com/developerworks/forums/thread.jspa?messageID=14578218

你可能感兴趣的:(java,Security,public key)