PublicKey加密解密入门代码

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

环境: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 [url]http://www.techrepublic.com/article/jce-offers-an-api-to-leverage-asymmetric-cryptography/1049434[/url]
3 Secret Key Cryptography Tutorial [url]http://www.wikijava.org/wiki/Secret_Key_Cryptography_Tutorial[/url]
4 What's wrong with IBM's JCE provider? [url]http://www.ibm.com/developerworks/forums/thread.jspa?messageID=14578218[/url]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值