導航:首頁 > 源碼編譯 > rsa演算法java

rsa演算法java

發布時間:2022-01-27 17:48:39

㈠ 求RSA演算法java實現源代碼(帶界面的)

import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.io.*;
import java.math.BigInteger;

/**
* RSA 工具類。提供加密,解密,生成密鑰對等方法。
* 需要到http://www.bouncycastle.org下載bcprov-jdk14-123.jar。
* @author xiaoyusong
* mail: [email protected]
* msn:[email protected]
* @since 2004-5-20
*
*/
public class RSAUtil {

/**
* 生成密鑰對
* @return KeyPair
* @throws EncryptException
*/
public static KeyPair generateKeyPair() throws EncryptException {
try {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA",
new org.bouncycastle.jce.provider.BouncyCastleProvider());
final int KEY_SIZE = 1024;//沒什麼好說的了,這個值關繫到塊加密的大小,可以更改,但是不要太大,否則效率會低
keyPairGen.initialize(KEY_SIZE, new SecureRandom());
KeyPair keyPair = keyPairGen.genKeyPair();
return keyPair;
} catch (Exception e) {
throw new EncryptException(e.getMessage());
}
}
/**
* 生成公鑰
* @param molus
* @param publicExponent
* @return RSAPublicKey
* @throws EncryptException
*/
public static RSAPublicKey generateRSAPublicKey(byte[] molus, byte[] publicExponent) throws EncryptException {
KeyFactory keyFac = null;
try {
keyFac = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
} catch (NoSuchAlgorithmException ex) {
throw new EncryptException(ex.getMessage());
}

RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(molus), new BigInteger(publicExponent));
try {
return (RSAPublicKey) keyFac.generatePublic(pubKeySpec);
} catch (InvalidKeySpecException ex) {
throw new EncryptException(ex.getMessage());
}
}
/**
* 生成私鑰
* @param molus
* @param privateExponent
* @return RSAPrivateKey
* @throws EncryptException
*/
public static RSAPrivateKey generateRSAPrivateKey(byte[] molus, byte[] privateExponent) throws EncryptException {
KeyFactory keyFac = null;
try {
keyFac = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
} catch (NoSuchAlgorithmException ex) {
throw new EncryptException(ex.getMessage());
}

RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(new BigInteger(molus), new BigInteger(privateExponent));
try {
return (RSAPrivateKey) keyFac.generatePrivate(priKeySpec);
} catch (InvalidKeySpecException ex) {
throw new EncryptException(ex.getMessage());
}
}
/**
* 加密
* @param key 加密的密鑰
* @param data 待加密的明文數據
* @return 加密後的數據
* @throws EncryptException
*/
public static byte[] encrypt(Key key, byte[] data) throws EncryptException {
try {
Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
cipher.init(Cipher.ENCRYPT_MODE, key);
int blockSize = cipher.getBlockSize();//獲得加密塊大小,如:加密前數據為128個byte,而key_size=1024 加密塊大小為127 byte,加密後為128個byte;因此共有2個加密塊,第一個127 byte第二個為1個byte
int outputSize = cipher.getOutputSize(data.length);//獲得加密塊加密後塊大小
int leavedSize = data.length % blockSize;
int blocksSize = leavedSize != 0 ? data.length / blockSize + 1 : data.length / blockSize;
byte[] raw = new byte[outputSize * blocksSize];
int i = 0;
while (data.length - i * blockSize > 0) {
if (data.length - i * blockSize > blockSize)
cipher.doFinal(data, i * blockSize, blockSize, raw, i * outputSize);
else
cipher.doFinal(data, i * blockSize, data.length - i * blockSize, raw, i * outputSize);
//這裡面doUpdate方法不可用,查看源代碼後發現每次doUpdate後並沒有什麼實際動作除了把byte[]放到ByteArrayOutputStream中,而最後doFinal的時候才將所有的byte[]進行加密,可是到了此時加密塊大小很可能已經超出了OutputSize所以只好用dofinal方法。

i++;
}
return raw;
} catch (Exception e) {
throw new EncryptException(e.getMessage());
}
}
/**
* 解密
* @param key 解密的密鑰
* @param raw 已經加密的數據
* @return 解密後的明文
* @throws EncryptException
*/
public static byte[] decrypt(Key key, byte[] raw) throws EncryptException {
try {
Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
cipher.init(cipher.DECRYPT_MODE, key);
int blockSize = cipher.getBlockSize();
ByteArrayOutputStream bout = new ByteArrayOutputStream(64);
int j = 0;

while (raw.length - j * blockSize > 0) {
bout.write(cipher.doFinal(raw, j * blockSize, blockSize));
j++;
}
return bout.toByteArray();
} catch (Exception e) {
throw new EncryptException(e.getMessage());
}
}
/**
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
File file = new File("test.html");
FileInputStream in = new FileInputStream(file);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] tmpbuf = new byte[1024];
int count = 0;
while ((count = in.read(tmpbuf)) != -1) {
bout.write(tmpbuf, 0, count);
tmpbuf = new byte[1024];
}
in.close();
byte[] orgData = bout.toByteArray();
KeyPair keyPair = RSAUtil.generateKeyPair();
RSAPublicKey pubKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey priKey = (RSAPrivateKey) keyPair.getPrivate();

byte[] pubModBytes = pubKey.getMolus().toByteArray();
byte[] pubPubExpBytes = pubKey.getPublicExponent().toByteArray();
byte[] priModBytes = priKey.getMolus().toByteArray();
byte[] priPriExpBytes = priKey.getPrivateExponent().toByteArray();
RSAPublicKey recoveryPubKey = RSAUtil.generateRSAPublicKey(pubModBytes,pubPubExpBytes);
RSAPrivateKey recoveryPriKey = RSAUtil.generateRSAPrivateKey(priModBytes,priPriExpBytes);

byte[] raw = RSAUtil.encrypt(priKey, orgData);
file = new File("encrypt_result.dat");
OutputStream out = new FileOutputStream(file);
out.write(raw);
out.close();
byte[] data = RSAUtil.decrypt(recoveryPubKey, raw);
file = new File("decrypt_result.html");
out = new FileOutputStream(file);
out.write(data);
out.flush();
out.close();
}
}

http://book.77169.org/data/web5409/20050328/20050328__3830259.html

這個行吧
http://soft.zdnet.com.cn/software_zone/2007/0925/523319.shtml

再參考這個吧
http://topic.csdn.net/t/20040427/20/3014655.html

㈡ Java中RSA的方式如何實現非對稱加密的示例

代碼如下,需要依賴一個jar包commons-codec-1.9.jar,用於Base64轉換,請自行下載。

importorg.apache.commons.codec.binary.Base64;

importjavax.crypto.BadPaddingException;
importjavax.crypto.Cipher;
importjavax.crypto.IllegalBlockSizeException;
importjava.io.ByteArrayOutputStream;
importjava.io.UnsupportedEncodingException;
importjava.security.*;
importjava.security.interfaces.RSAPrivateKey;
importjava.security.interfaces.RSAPublicKey;
importjava.security.spec.PKCS8EncodedKeySpec;
importjava.security.spec.X509EncodedKeySpec;

publicclassRSAUtils{

//加密方式
="RSA";
//簽名演算法
_ALGORITHM="SHA1WithRSA";
//創建密鑰對初始長度
privatestaticfinalintKEY_SIZE=512;
//字元編碼格式
="UTF-8";
//RSA最大加密明文大小
privatestaticfinalintMAX_ENCRYPT_BLOCK=117;
//RSA最大解密密文大小
privatestaticfinalintMAX_DECRYPT_BLOCK=128;

privateKeyFactorykeyFactory;

publicRSAUtils(){
keyFactory=KeyFactory.getInstance(ALGORITHM);
}

/**
*私鑰加密
*
*@paramcontent待加密字元串
*@paramprivateKey私鑰
*@return加密後字元串(BASE64編碼)
*/
(Stringcontent,StringprivateKey)throwsException{
Stringresult;

try(ByteArrayOutputStreamout=newByteArrayOutputStream()){
byte[]keyBytes=newBase64().decode(privateKey);
=newPKCS8EncodedKeySpec(keyBytes);
PrivateKeypKey=keyFactory.generatePrivate(pkcs8KeySpec);
Ciphercipher=Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE,pKey);

byte[]data=content.getBytes(CHARSET);
write2Stream(cipher,data,out);
byte[]resultBytes=out.toByteArray();

result=Base64.encodeBase64String(resultBytes);
}catch(Exceptione){
thrownewException(e);
}

returnresult;
}

/**
*公鑰解密
*
*@paramcontent已加密字元串(BASE64加密)
*@parampublicKey公鑰
*@return
*/
(Stringcontent,StringpublicKey)throwsException{
Stringresult="";

try(ByteArrayOutputStreamout=newByteArrayOutputStream()){
byte[]keyBytes=newBase64().decode(publicKey);
X509EncodedKeySpecx509KeySpec=newX509EncodedKeySpec(keyBytes);
PublicKeypKey=keyFactory.generatePublic(x509KeySpec);
Ciphercipher=Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE,pKey);

byte[]data=Base64.decodeBase64(content);
write2Stream(cipher,data,out);
byte[]resultBytes=out.toByteArray();

result=newString(resultBytes);
}catch(Exceptione){
thrownewException(e);
}

returnresult;
}

/**
*公鑰加密
*
*@paramcontent待加密字元串
*@parampublicKey公鑰
*@return加密後字元串(BASE64編碼)
*/
(Stringcontent,StringpublicKey)throwsException{
Stringresult="";

try(ByteArrayOutputStreamout=newByteArrayOutputStream()){
byte[]keyBytes=newBase64().decode(publicKey);
X509EncodedKeySpecx509KeySpec=newX509EncodedKeySpec(keyBytes);
PublicKeypKey=keyFactory.generatePublic(x509KeySpec);
Ciphercipher=Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE,pKey);

byte[]data=content.getBytes(CHARSET);
write2Stream(cipher,
data,out);
byte[]resultBytes=out.toByteArray();
result=Base64.encodeBase64String(resultBytes);
}catch(Exceptione){
thrownewException(e);
}

returnresult;
}

/**
*私鑰解密
*
*@paramcontent已加密字元串
*@paramprivateKey私鑰
*@return解密後字元串
*/
(Stringcontent,StringprivateKey)throwsException{
Stringresult="";

try(ByteArrayOutputStreamout=newByteArrayOutputStream()){
byte[]keyBytes=newBase64().decode(privateKey);
=newPKCS8EncodedKeySpec(keyBytes);
PrivateKeypKey=keyFactory.generatePrivate(pkcs8KeySpec);
Ciphercipher=Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE,pKey);

byte[]data=Base64.decodeBase64(content);
write2Stream(cipher,data,out);
byte[]resultBytes=out.toByteArray();
result=newString(resultBytes);
}catch(Exceptione){
thrownewException(e);
}

returnresult;
}

privatestaticvoidwrite2Stream(Ciphercipher,byte[]data,ByteArrayOutputStreamout)throws
BadPaddingException,IllegalBlockSizeException{
intdataLen=data.length;
intoffSet=0;
byte[]cache;
inti=0;
//對數據分段解密
while(dataLen-offSet>0){
if(dataLen-offSet>MAX_DECRYPT_BLOCK){
cache=cipher.doFinal(data,offSet,MAX_DECRYPT_BLOCK);
}else{
cache=cipher.doFinal(data,offSet,dataLen-offSet);
}
out.write(cache,0,cache.length);
i++;
offSet=i*MAX_DECRYPT_BLOCK;
}
}

/**
*用私鑰對信息生成數字簽名
*
*@paramdata已加密數據
*@paramprivateKey私鑰(BASE64編碼)
*@returnsign
*/
publicStringsign(Stringdata,StringprivateKey)throwsException{
Stringresult="";
try{
byte[]keyBytes=newBase64().decode(privateKey);
=newPKCS8EncodedKeySpec(keyBytes);
PrivateKeyprivateK=keyFactory.generatePrivate(pkcs8KeySpec);
Signaturesignature=Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initSign(privateK);
signature.update(parse2HexStr(data).getBytes(CHARSET));

result=newBase64().encodeToString(signature.sign());
}catch(Exceptione){
thrownewException(e);
}
returnresult;
}

/**
*校驗數字簽名
*
*@paramdata已加密數據
*@parampublicKey公鑰(BASE64編碼)
*@paramsign數字簽名
*@return
*@throwsException
*/
publicbooleanverify(Stringdata,StringpublicKey,Stringsign)throwsException{
booleanresult;

try{
byte[]keyBytes=newBase64().decode(publicKey);
X509EncodedKeySpeckeySpec=newX509EncodedKeySpec(keyBytes);
PublicKeypublicK=keyFactory.generatePublic(keySpec);
Signaturesignature=Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initVerify(publicK);
signature.update(parse2HexStr(data).getBytes(CHARSET));
result=signature.verify(newBase64().decode(sign));
}catch(Exceptione){
thrownewException(e);
}
returnresult;
}

/**
*將二進制轉換成16進制
*
*@paramdata
*@return
*/
(Stringdata)throwsException{
Stringresult="";
try{
byte[]buf=data.getBytes(CHARSET);

StringBuffersb=newStringBuffer();
for(inti=0;i<buf.length;i++){
Stringhex=Integer.toHexString(buf[i]&0xFF);
if(hex.length()==1){
hex='0'+hex;
}
sb.append(hex.toUpperCase());
}
result=sb.toString();
}catch(UnsupportedEncodingExceptione){
thrownewException(e);
}
returnresult;
}

/**
*生成公鑰與私鑰
*/
publicstaticvoidcreateKey()throwsException{
try{
=KeyPairGenerator.getInstance(ALGORITHM);
keyPairGenerator.initialize(KEY_SIZE);
KeyPairkeyPair=keyPairGenerator.generateKeyPair();
RSAPublicKeyrsaPublicKey=(RSAPublicKey)keyPair.getPublic();
RSAPrivateKeyrsaPrivateKey=(RSAPrivateKey)keyPair.getPrivate();

StringpublicKey=Base64.encodeBase64String(rsaPublicKey.getEncoded());
StringprivateKey=Base64.encodeBase64String(rsaPrivateKey.getEncoded());

System.out.println("publicKey="+publicKey+" privateKey="+privateKey);
}catch(NoSuchAlgorithmExceptione){
thrownewException(e);
}
}

publicstaticvoidmain(String[]args)throwsException{

StringPRIVATE_KEY="+m+/fNs1bmgfJhI8lhr/o/Hy8EFB/I/DDyLcCcU4bCLtxpki8edC+KJR2WvyYfnVmWEe//++W5C+lesEOAqdO5nahRZsL8BIDoxTEn2j+DSa///1qX+t8f5wD8i/8GU702PeCwkGI5ymrARq+/+/nkefTq0SNpUDVbGxVpJi9/FOUf";
StringPUBLIC_KEY="+lc///NfOvKvQndzDH60DzLGOMdE0NBrTn/5zEjGwJbVdlvCfOiHwIDAQAB";

RSAUtilsrsaUtil=newRSAUtils();
StringencryptByPublicKey=rsaUtil.encryptByPublicKey("你好!",PUBLIC_KEY);
System.out.println(encryptByPublicKey);
StringdecryptByPrivateKey=rsaUtil.decryptByPrivateKey(encryptByPublicKey,PRIVATE_KEY);
System.out.println(decryptByPrivateKey);
StringencryptByPrivateKey=rsaUtil.encryptByPrivateKey("你好!",PRIVATE_KEY);
System.out.println(encryptByPrivateKey);
StringdecryptByPublicKey=rsaUtil.decryptByPublicKey(encryptByPrivateKey,PUBLIC_KEY);
System.out.println(decryptByPublicKey);
Stringsign=rsaUtil.sign("1234",PRIVATE_KEY);
System.out.println("sign:"+sign);
System.out.println(rsaUtil.verify("1234",PUBLIC_KEY,sign));
}
}

㈢ java加密問題,RSA演算法

無法找到文件異常。樓主確定路徑正確。後綴名正確

FileInputStream f=new FileInputStream("Skey_RSA_pub.dat");

樓主你的文件放在什麼位置

㈣ 求救求救。。。剛學習JAVA,有沒有JAVA的RSA完整演算法急。。。

例如:import java.awt.*;
即把java包中awt組件包中所有的類添加進來了,類似的,你要指定某個類就要指定到他的具體位置,可以在類所在的文件包上用「*」,後者吧「*」換成制定的類名;
不知道回答的是否你想要的,希望會對你有幫助!努力加油!

㈤ 求JAVA編寫的RSA加密演算法

代碼如下:main方法用於測試的,不是演算法本身。

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;

import javax.crypto.Cipher;

public class RSACrypto
{
private final static String RSA = "RSA";
public static PublicKey uk;
public static PrivateKey rk;

public static void generateKey() throws Exception
{
KeyPairGenerator gen = KeyPairGenerator.getInstance(RSA);
gen.initialize(512, new SecureRandom());
KeyPair keyPair = gen.generateKeyPair();
uk = keyPair.getPublic();
rk = keyPair.getPrivate();
}

private static byte[] encrypt(String text, PublicKey pubRSA) throws Exception
{
Cipher cipher = Cipher.getInstance(RSA);
cipher.init(Cipher.ENCRYPT_MODE, pubRSA);
return cipher.doFinal(text.getBytes());
}

public final static String encrypt(String text)
{
try {
return byte2hex(encrypt(text, uk));
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}

public final static String decrypt(String data)
{
try{
return new String(decrypt(hex2byte(data.getBytes())));
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}

private static byte[] decrypt(byte[] src) throws Exception
{
Cipher cipher = Cipher.getInstance(RSA);
cipher.init(Cipher.DECRYPT_MODE, rk);
return cipher.doFinal(src);
}

public static String byte2hex(byte[] b)
{
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n ++)
{
stmp = Integer.toHexString(b[n] & 0xFF);
if (stmp.length() == 1)
hs += ("0" + stmp);
else
hs += stmp;
}
return hs.toUpperCase();
}

public static byte[] hex2byte(byte[] b)
{
if ((b.length % 2) != 0)
throw new IllegalArgumentException("長度不是偶數");

byte[] b2 = new byte[b.length / 2];

for (int n = 0; n < b.length; n += 2)
{
String item = new String(b, n, 2);
b2[n/2] = (byte)Integer.parseInt(item, 16);
}
return b2;
}

//just for test
public static void main(String args[])
{
try
{
RSACrypto.generateKey();
String cipherText = RSACrypto.encrypt("asdfghjh");
System.out.println(cipherText);
String plainText = RSACrypto.decrypt(cipherText);
System.out.println(plainText);
}
catch(Exception e)
{
e.printStackTrace();
}
}

}

㈥ java RSA演算法實現256位密鑰怎麼做

【下載實例】本文介紹RSA2加密與解密,RSA2是RSA的加強版本,在密鑰長度上採用2048, RSA2比RSA更安全,更可靠, 本人的另一篇文章RSA已經發表,有想了解的可以點開下面的RSA文章

㈦ 如何用java實現128位密鑰的RSA演算法

final int KEY_SIZE = 128;// 沒什麼好說的了,這個值關繫到塊加密的大小,可以更改,但是不要太大,否則效率會低

㈧ RSA PKCS#1在java中怎麼實現

樓主看看下面的代碼是不是你所需要的,這是我原來用的時候收集的
import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.io.*;
import java.math.BigInteger;

/**
* RSA 工具類。提供加密,解密,生成密鑰對等方法。
* 需要到http://www.bouncycastle.org下載bcprov-jdk14-123.jar。
* RSA加密原理概述
* RSA的安全性依賴於大數的分解,公鑰和私鑰都是兩個大素數(大於100的十進制位)的函數。
* 據猜測,從一個密鑰和密文推斷出明文的難度等同於分解兩個大素數的積
* ===================================================================
* (該演算法的安全性未得到理論的證明)
* ===================================================================
* 密鑰的產生:
* 1.選擇兩個大素數 p,q ,計算 n=p*q;
* 2.隨機選擇加密密鑰 e ,要求 e 和 (p-1)*(q-1)互質
* 3.利用 Euclid 演算法計算解密密鑰 d , 使其滿足 e*d = 1(mod(p-1)*(q-1)) (其中 n,d 也要互質)
* 4:至此得出公鑰為 (n,e) 私鑰為 (n,d)
* ===================================================================
* 加解密方法:
* 1.首先將要加密的信息 m(二進製表示) 分成等長的數據塊 m1,m2,...,mi 塊長 s(盡可能大) ,其中 2^s<n
* 2:對應的密文是: ci = mi^e(mod n)
* 3:解密時作如下計算: mi = ci^d(mod n)
* ===================================================================
* RSA速度
* 由於進行的都是大數計算,使得RSA最快的情況也比DES慢上100倍,無論是軟體還是硬體實現。
* 速度一直是RSA的缺陷。一般來說只用於少量數據加密。
* 文件名:RSAUtil.java<br>
* @author 趙峰<br>
* 版本:1.0.1<br>
* 描述:本演算法摘自網路,是對RSA演算法的實現<br>
* 創建時間:2009-7-10 下午09:58:16<br>
* 文件描述:首先生成兩個大素數,然後根據Euclid演算法生成解密密鑰<br>
*/
public class RSAUtil {

//密鑰對
private KeyPair keyPair = null;

/**
* 初始化密鑰對
*/
public RSAUtil(){
try {
this.keyPair = this.generateKeyPair();
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 生成密鑰對
* @return KeyPair
* @throws Exception
*/
private KeyPair generateKeyPair() throws Exception {
try {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA",new org.bouncycastle.jce.provider.BouncyCastleProvider());
//這個值關繫到塊加密的大小,可以更改,但是不要太大,否則效率會低
final int KEY_SIZE = 1024;
keyPairGen.initialize(KEY_SIZE, new SecureRandom());
KeyPair keyPair = keyPairGen.genKeyPair();
return keyPair;
} catch (Exception e) {
throw new Exception(e.getMessage());
}

}

/**
* 生成公鑰
* @param molus
* @param publicExponent
* @return RSAPublicKey
* @throws Exception
*/
private RSAPublicKey generateRSAPublicKey(byte[] molus, byte[] publicExponent) throws Exception {

KeyFactory keyFac = null;
try {
keyFac = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
} catch (NoSuchAlgorithmException ex) {
throw new Exception(ex.getMessage());
}
RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(molus), new BigInteger(publicExponent));
try {
return (RSAPublicKey) keyFac.generatePublic(pubKeySpec);
} catch (InvalidKeySpecException ex) {
throw new Exception(ex.getMessage());
}

}

/**
* 生成私鑰
* @param molus
* @param privateExponent
* @return RSAPrivateKey
* @throws Exception
*/
private RSAPrivateKey generateRSAPrivateKey(byte[] molus, byte[] privateExponent) throws Exception {
KeyFactory keyFac = null;
try {
keyFac = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
} catch (NoSuchAlgorithmException ex) {
throw new Exception(ex.getMessage());
}
RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(new BigInteger(molus), new BigInteger(privateExponent));
try {
return (RSAPrivateKey) keyFac.generatePrivate(priKeySpec);
} catch (InvalidKeySpecException ex) {
throw new Exception(ex.getMessage());
}
}

/**
* 加密
* @param key 加密的密鑰
* @param data 待加密的明文數據
* @return 加密後的數據
* @throws Exception
*/
public byte[] encrypt(Key key, byte[] data) throws Exception {
try {
Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
cipher.init(Cipher.ENCRYPT_MODE, key);
// 獲得加密塊大小,如:加密前數據為128個byte,而key_size=1024 加密塊大小為127 byte,加密後為128個byte;
// 因此共有2個加密塊,第一個127 byte第二個為1個byte
int blockSize = cipher.getBlockSize();
// System.out.println("blockSize:"+blockSize);
int outputSize = cipher.getOutputSize(data.length);// 獲得加密塊加密後塊大小
// System.out.println("加密塊大小:"+outputSize);
int leavedSize = data.length % blockSize;
// System.out.println("leavedSize:"+leavedSize);
int blocksSize = leavedSize != 0 ? data.length / blockSize + 1 : data.length / blockSize;
byte[] raw = new byte[outputSize * blocksSize];
int i = 0;
while (data.length - i * blockSize > 0) {
if (data.length - i * blockSize > blockSize)
cipher.doFinal(data, i * blockSize, blockSize, raw, i * outputSize);
else
cipher.doFinal(data, i * blockSize, data.length - i * blockSize, raw, i * outputSize);
// 這裡面doUpdate方法不可用,查看源代碼後發現每次doUpdate後並沒有什麼實際動作除了把byte[]放到ByteArrayOutputStream中
// 而最後doFinal的時候才將所有的byte[]進行加密,可是到了此時加密塊大小很可能已經超出了OutputSize所以只好用dofinal方法。
i++;
}
return raw;
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}

/**
* 解密
* @param key 解密的密鑰
* @param raw 已經加密的數據
* @return 解密後的明文
* @throws Exception
*/
@SuppressWarnings("static-access")
public byte[] decrypt(Key key, byte[] raw) throws Exception {
try {
Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
cipher.init(cipher.DECRYPT_MODE, key);
int blockSize = cipher.getBlockSize();
ByteArrayOutputStream bout = new ByteArrayOutputStream(64);
int j = 0;
while (raw.length - j * blockSize > 0) {
bout.write(cipher.doFinal(raw, j * blockSize, blockSize));
j++;
}
return bout.toByteArray();
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}

/**
* 返回公鑰
* @return
* @throws Exception
*/
public RSAPublicKey getRSAPublicKey() throws Exception{
//獲取公鑰
RSAPublicKey pubKey = (RSAPublicKey) keyPair.getPublic();
//獲取公鑰系數(位元組數組形式)
byte[] pubModBytes = pubKey.getMolus().toByteArray();
//返回公鑰公用指數(位元組數組形式)
byte[] pubPubExpBytes = pubKey.getPublicExponent().toByteArray();
//生成公鑰
RSAPublicKey recoveryPubKey = this.generateRSAPublicKey(pubModBytes,pubPubExpBytes);
return recoveryPubKey;
}

/**
* 獲取私鑰
* @return
* @throws Exception
*/
public RSAPrivateKey getRSAPrivateKey() throws Exception{
// 獲取私鑰
RSAPrivateKey priKey = (RSAPrivateKey) keyPair.getPrivate();
// 返回私鑰系數(位元組數組形式)
byte[] priModBytes = priKey.getMolus().toByteArray();
// 返回私鑰專用指數(位元組數組形式)
byte[] priPriExpBytes = priKey.getPrivateExponent().toByteArray();
// 生成私鑰
RSAPrivateKey recoveryPriKey = this.generateRSAPrivateKey(priModBytes,priPriExpBytes);
return recoveryPriKey;
}

/**
* 測試
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
RSAUtil rsa = new RSAUtil();
String str = "天龍八部、神鵰俠侶、射鵰英雄傳白馬嘯西風";
RSAPublicKey pubKey = rsa.getRSAPublicKey();
RSAPrivateKey priKey = rsa.getRSAPrivateKey();
// System.out.println("加密後==" + new String(rsa.encrypt(pubKey,str.getBytes())));
String mw = new String(rsa.encrypt(pubKey, str.getBytes()));
System.out.println("加密後:"+mw);
// System.out.println("解密後:");
System.out.println("解密後==" + new String(rsa.decrypt(priKey,rsa.encrypt(pubKey,str.getBytes()))));
}
}

閱讀全文

與rsa演算法java相關的資料

熱點內容
android圖片變灰 瀏覽:268
linuxvi下一個 瀏覽:975
安卓手機的應用鎖怎麼解 瀏覽:735
linux增加路徑 瀏覽:849
sql身份證號最後四位加密 瀏覽:533
xp系統表格加密 瀏覽:856
光遇安卓軍大衣什麼時候上線 瀏覽:840
android應用商店圖標 瀏覽:341
java計算圓的面積 瀏覽:643
應用編譯優化recovery 瀏覽:577
域控命令n 瀏覽:258
php導出文件 瀏覽:15
谷歌地圖網頁版無法連接伺服器地址 瀏覽:298
菜鳥工具在線編譯python 瀏覽:858
柵格化命令有何作用 瀏覽:825
為什麼壓縮文件不能解壓 瀏覽:311
足球app哪個軟體好 瀏覽:96
產品經理逼瘋程序員的一天 瀏覽:17
修改svn伺服器ip地址 瀏覽:584
下列關於編譯說法正確的是 瀏覽:246