import java
import java
import java
import java
import java
import java
import java
import java
import java
import java
import javax
import sun
import sun
public class RSACoder {
/**
* 得到公鑰
* @param key 密鑰字符串(經過base
* @throws Exception
*/
public static PublicKey getPublicKey(String key) throws Exception {
byte[] keyBytes;
keyBytes = (new BASE
X
KeyFactory keyFactory = KeyFactory
PublicKey publicKey = keyFactory
return publicKey;
}
/**
* 得到私鑰
* @param key 密鑰字符串(經過base
* @throws Exception
*/
public static PrivateKey getPrivateKey(String key) throws Exception {
byte[] keyBytes;
keyBytes = (new BASE
PKCS
KeyFactory keyFactory = KeyFactory
PrivateKey privateKey = keyFactory
return privateKey;
}
/**
* 得到密鑰字符串(經過base
* @return
*/
public static String getKeyString(Key key) throws Exception {
byte[] keyBytes = key
String s = (new BASE
return s;
}
public static void main(String[] args) throws Exception {
KeyPairGenerator keyPairGen = KeyPairGenerator
//密鑰位數
keyPairGen
//密鑰對
KeyPair keyPair = keyPairGen
// 公鑰
PublicKey publicKey = (RSAPublicKey) keyPair
// 私鑰
PrivateKey privateKey = (RSAPrivateKey) keyPair
String publicKeyString = getKeyString(publicKey);
System
String privateKeyString = getKeyString(privateKey);
System
//加解密類
Cipher cipher = Cipher
//明文
byte[] plainText =
//加密
cipher
byte[] enBytes = cipher
//通過密鑰字符串得到密鑰
publicKey = getPublicKey(publicKeyString);
privateKey = getPrivateKey(privateKeyString);
//解密
cipher
byte[]deBytes = cipher
publicKeyString = getKeyString(publicKey);
System
privateKeyString = getKeyString(privateKey);
System
String s = new String(deBytes);
System
}
}
From:http://tw.wingwit.com/Article/program/Java/hx/201311/25516.html