//引入文件
10多年的嵊州網(wǎng)站建設經驗,針對設計、前端、開發(fā)、售后、文案、推廣等六對一服務,響應快,48小時及時工作處理。全網(wǎng)整合營銷推廣的優(yōu)勢是能夠根據(jù)用戶設備顯示端的尺寸不同,自動調整嵊州建站的顯示方式,使網(wǎng)站能夠適用不同顯示終端,在瀏覽器中調整網(wǎng)站的寬度,無論在任何一種瀏覽器上瀏覽網(wǎng)站,都能展現(xiàn)優(yōu)雅布局與設計,從而大程度地提升瀏覽體驗。創(chuàng)新互聯(lián)公司從事“嵊州網(wǎng)站設計”,“嵊州網(wǎng)站推廣”以來,每個客戶項目都認真落實執(zhí)行。
import java.security.*;
import javax.crypto.*;
/**
* RSACryptography
* RSACryptography use the privated key to encrypt the plain text and decrypt
* the cipher text with the public key
*/
public class RSACryptography {
Cipher cipher;
/**
構造函數(shù),就是你每次new這個對象RSACryptography 時候就會執(zhí)行里面的方法
返回一個Cipher對象(其實他就是用來加密解密的)
*/
public RSACryptography() {
try {
cipher = Cipher.getInstance("RSA");//返回一個cipher對象,該類
//應該是單例的
} catch (NoSuchAlgorithmException e) {//拋出異常,沒什么說的
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
}
}
/**
好了,重點來了,你需要加密解密的就調用這個方法encrypt_decrypt(),傳入一個byte[]的類型值byteInput,,就是你要加密的東西,在傳入一個key,這個key 就像鑰匙一樣,你根據(jù)這個key進行加密,也可以根據(jù)這個key進行解密的,boolean 類型的 crypto,如果true就是加密,false就是解密
*/
public byte[] encrypt_decrypt(byte[] byteInput, Key key, boolean crypto) {
try {
if(crypto){
cipher.init(Cipher.ENCRYPT_MODE,key);//加密前初始化
}else{
cipher.init(Cipher.DECRYPT_MODE,key);//解密前初始化
}
byte[] cipherByte = cipher.doFinal(byteInput);//進行加密或解密
return cipherByte;//返回你的加密或者解密值類型為byte[]
} catch (InvalidKeyException e) {//拋出異常
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
}
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 工具類。提供加密,解密,生成密鑰對等方法。
* 需要到下載bcprov-jdk14-123.jar。
* @author xiaoyusong
* mail: xiaoyusong@etang.com
* msn:xiao_yu_song@hotmail.com
* @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 modulus
* @param publicExponent
* @return RSAPublicKey
* @throws EncryptException
*/
public static RSAPublicKey generateRSAPublicKey(byte[] modulus, 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(modulus), new BigInteger(publicExponent));
try {
return (RSAPublicKey) keyFac.generatePublic(pubKeySpec);
} catch (InvalidKeySpecException ex) {
throw new EncryptException(ex.getMessage());
}
}
/**
* 生成私鑰
* @param modulus
* @param privateExponent
* @return RSAPrivateKey
* @throws EncryptException
*/
public static RSAPrivateKey generateRSAPrivateKey(byte[] modulus, 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(modulus), new BigInteger(privateExponent));
try {
return (RSAPrivateKey) keyFac.generatePrivate(priKeySpec);
} catch (InvalidKeySpecException ex) {
throw new EncryptException(ex.getMessage());
}
}
/**
* 加密
* @param key 加密的密鑰
* @param data 待加密的明文數(shù)據(jù)
* @return 加密后的數(shù)據(jù)
* @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();//獲得加密塊大小,如:加密前數(shù)據(jù)為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方法不可用,查看源代碼后發(fā)現(xiàn)每次doUpdate后并沒有什么實際動作除了把byte[]放到ByteArrayOutputStream中,而最后doFinal的時候才將所有的byte[]進行加密,可是到了此時加密塊大小很可能已經超出了OutputSize所以只好用dofinal方法。
i++;
}
return raw;
} catch (Exception e) {
throw new EncryptException(e.getMessage());
}
}
/**
* 解密
* @param key 解密的密鑰
* @param raw 已經加密的數(shù)據(jù)
* @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.getModulus().toByteArray();
byte[] pubPubExpBytes = pubKey.getPublicExponent().toByteArray();
byte[] priModBytes = priKey.getModulus().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();
}
}
這個行吧
再參考這個吧
RSA算法非常簡單,概述如下:
找兩素數(shù)p和q
取n=p*q
取t=(p-1)*(q-1)
取任何一個數(shù)e,要求滿足et并且e與t互素(就是最大公因數(shù)為1)
取d*e%t==1
這樣最終得到三個數(shù): n d e
設消息為數(shù)M (M n)
設c=(M**d)%n就得到了加密后的消息c
設m=(c**e)%n則 m == M,從而完成對c的解密。
注:**表示次方,上面兩式中的d和e可以互換。
在對稱加密中:
n d兩個數(shù)構成公鑰,可以告訴別人;
n e兩個數(shù)構成私鑰,e自己保留,不讓任何人知道。
給別人發(fā)送的信息使用e加密,只要別人能用d解開就證明信息是由你發(fā)送的,構成了簽名機制。
別人給你發(fā)送信息時使用d加密,這樣只有擁有e的你能夠對其解密。
rsa的安全性在于對于一個大數(shù)n,沒有有效的方法能夠將其分解
從而在已知n d的情況下無法獲得e;同樣在已知n e的情況下無法
求得d。
二實踐
接下來我們來一個實踐,看看實際的操作:
找兩個素數(shù):
p=47
q=59
這樣
n=p*q=2773
t=(p-1)*(q-1)=2668
取e=63,滿足et并且e和t互素
用perl簡單窮舉可以獲得滿主 e*d%t ==1的數(shù)d:
C:\Tempperl -e "foreach $i (1..9999){ print($i),last if $i*63%2668==1 }"
847
即d=847
最終我們獲得關鍵的
n=2773
d=847
e=63
取消息M=244我們看看
加密:
c=M**d%n = 244**847%2773
用perl的大數(shù)計算來算一下:
C:\Tempperl -Mbigint -e "print 244**847%2773"
465
即用d對M加密后獲得加密信息c=465
解密:
我們可以用e來對加密后的c進行解密,還原M:
m=c**e%n=465**63%2773 :
C:\Tempperl -Mbigint -e "print 465**63%2773"
244
即用e對c解密后獲得m=244 , 該值和原始信息M相等。
三字符串加密
把上面的過程集成一下我們就能實現(xiàn)一個對字符串加密解密的示例了。
每次取字符串中的一個字符的ascii值作為M進行計算,其輸出為加密后16進制
的數(shù)的字符串形式,按3字節(jié)表示,如01F
代碼如下:
#!/usr/bin/perl -w
#RSA 計算過程學習程序編寫的測試程序
#watercloud 2003-8-12
#
use strict;
use Math::BigInt;
my %RSA_CORE = (n=2773,e=63,d=847); #p=47,q=59
my $N=new Math::BigInt($RSA_CORE{n});
my $E=new Math::BigInt($RSA_CORE{e});
my $D=new Math::BigInt($RSA_COREsqu6kqw);
print "N=$N D=$D E=$E\n";
sub RSA_ENCRYPT
{
my $r_mess = shift @_;
my ($c,$i,$M,$C,$cmess);
for($i=0;$i length($$r_mess);$i++)
{
$c=ord(substr($$r_mess,$i,1));
$M=Math::BigInt-new($c);
$C=$M-copy(); $C-bmodpow($D,$N);
$c=sprintf "%03X",$C;
$cmess.=$c;
}
return \$cmess;
}
sub RSA_DECRYPT
{
my $r_mess = shift @_;
my ($c,$i,$M,$C,$dmess);
for($i=0;$i length($$r_mess);$i+=3)
{
$c=substr($$r_mess,$i,3);
$c=hex($c);
$M=Math::BigInt-new($c);
$C=$M-copy(); $C-bmodpow($E,$N);
$c=chr($C);
$dmess.=$c;
}
return \$dmess;
}
my $mess="RSA 娃哈哈哈~~~";
$mess=$ARGV[0] if @ARGV = 1;
print "原始串:",$mess,"\n";
my $r_cmess = RSA_ENCRYPT(\$mess);
print "加密串:",$$r_cmess,"\n";
my $r_dmess = RSA_DECRYPT($r_cmess);
print "解密串:",$$r_dmess,"\n";
#EOF
測試一下:
C:\Tempperl rsa-test.pl
N=2773 D=847 E=63
原始串:RSA 娃哈哈哈~~~
加密串:5CB6CD6BC58A7709470AA74A0AA74A0AA74A6C70A46C70A46C70A4
解密串:RSA 娃哈哈哈~~~
C:\Tempperl rsa-test.pl 安全焦點(xfocus)
N=2773 D=847 E=63
原始串:安全焦點(xfocus)
加密串:3393EC12F0A466E0AA9510D025D7BA0712DC3379F47D51C325D67B
解密串:安全焦點(xfocus)
四提高
前面已經提到,rsa的安全來源于n足夠大,我們測試中使用的n是非常小的,根本不能保障安全性,
我們可以通過RSAKit、RSATool之類的工具獲得足夠大的N 及D E。
通過工具,我們獲得1024位的N及D E來測試一下:
n=0x328C74784DF31119C526D18098EBEBB943B0032B599CEE13CC2BCE7B5FCD15F90B66EC3A85F5005D
BDCDED9BDFCB3C4C265AF164AD55884D8278F791C7A6BFDAD55EDBC4F017F9CCF1538D4C2013433B383B
47D80EC74B51276CA05B5D6346B9EE5AD2D7BE7ABFB36E37108DD60438941D2ED173CCA50E114705D7E2
BC511951
d=0x10001
e=0xE760A3804ACDE1E8E3D7DC0197F9CEF6282EF552E8CEBBB7434B01CB19A9D87A3106DD28C523C2995
4C5D86B36E943080E4919CA8CE08718C3B0930867A98F635EB9EA9200B25906D91B80A47B77324E66AFF2
C4D70D8B1C69C50A9D8B4B7A3C9EE05FFF3A16AFC023731D80634763DA1DCABE9861A4789BD782A592D2B
1965
設原始信息
M=0x11111111111122222222222233333333333
完成這么大數(shù)字的計算依賴于大數(shù)運算庫,用perl來運算非常簡單:
A) 用d對M進行加密如下:
c=M**d%n :
C:\Tempperl -Mbigint -e " $x=Math::BigInt-bmodpow(0x11111111111122222222222233
333333333, 0x10001, 0x328C74784DF31119C526D18098EBEBB943B0032B599CEE13CC2BCE7B5F
CD15F90B66EC3A85F5005DBDCDED9BDFCB3C4C265AF164AD55884D8278F791C7A6BFDAD55EDBC4F0
17F9CCF1538D4C2013433B383B47D80EC74B51276CA05B5D6346B9EE5AD2D7BE7ABFB36E37108DD6
0438941D2ED173CCA50E114705D7E2BC511951);print $x-as_hex"
0x17b287be418c69ecd7c39227ab681ac422fcc84bb35d8a632543b304de288a8d4434b73d2576bd
45692b007f3a2f7c5f5aa1d99ef3866af26a8e876712ed1d4cc4b293e26bc0a1dc67e247715caa6b
3028f9461a3b1533ec0cb476441465f10d8ad47452a12db0601c5e8beda686dd96d2acd59ea89b91
f1834580c3f6d90898
即用d對M加密后信息為:
c=0x17b287be418c69ecd7c39227ab681ac422fcc84bb35d8a632543b304de288a8d4434b73d2576bd
45692b007f3a2f7c5f5aa1d99ef3866af26a8e876712ed1d4cc4b293e26bc0a1dc67e247715caa6b
3028f9461a3b1533ec0cb476441465f10d8ad47452a12db0601c5e8beda686dd96d2acd59ea89b91
f1834580c3f6d90898
B) 用e對c進行解密如下:
m=c**e%n :
C:\Tempperl -Mbigint -e " $x=Math::BigInt-bmodpow(0x17b287be418c69ecd7c39227ab
681ac422fcc84bb35d8a632543b304de288a8d4434b73d2576bd45692b007f3a2f7c5f5aa1d99ef3
866af26a8e876712ed1d4cc4b293e26bc0a1dc67e247715caa6b3028f9461a3b1533ec0cb4764414
65f10d8ad47452a12db0601c5e8beda686dd96d2acd59ea89b91f1834580c3f6d90898, 0xE760A
3804ACDE1E8E3D7DC0197F9CEF6282EF552E8CEBBB7434B01CB19A9D87A3106DD28C523C29954C5D
86B36E943080E4919CA8CE08718C3B0930867A98F635EB9EA9200B25906D91B80A47B77324E66AFF
2C4D70D8B1C69C50A9D8B4B7A3C9EE05FFF3A16AFC023731D80634763DA1DCABE9861A4789BD782A
592D2B1965, 0x328C74784DF31119C526D18098EBEBB943B0032B599CEE13CC2BCE7B5FCD15F90
B66EC3A85F5005DBDCDED9BDFCB3C4C265AF164AD55884D8278F791C7A6BFDAD55EDBC4F017F9CCF
1538D4C2013433B383B47D80EC74B51276CA05B5D6346B9EE5AD2D7BE7ABFB36E37108DD60438941
D2ED173CCA50E114705D7E2BC511951);print $x-as_hex"
0x11111111111122222222222233333333333
(我的P4 1.6G的機器上計算了約5秒鐘)
得到用e解密后的m=0x11111111111122222222222233333333333 == M
C) RSA通常的實現(xiàn)
RSA簡潔幽雅,但計算速度比較慢,通常加密中并不是直接使用RSA 來對所有的信息進行加密,
最常見的情況是隨機產生一個對稱加密的密鑰,然后使用對稱加密算法對信息加密,之后用
RSA對剛才的加密密鑰進行加密。
最后需要說明的是,當前小于1024位的N已經被證明是不安全的
自己使用中不要使用小于1024位的RSA,最好使用2048位的。
----------------------------------------------------------
一個簡單的RSA算法實現(xiàn)JAVA源代碼:
filename:RSA.java
/*
* Created on Mar 3, 2005
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
import java.math.BigInteger;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.BufferedReader;
import java.util.StringTokenizer;
/**
* @author Steve
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class RSA {
/**
* BigInteger.ZERO
*/
private static final BigInteger ZERO = BigInteger.ZERO;
/**
* BigInteger.ONE
*/
private static final BigInteger ONE = BigInteger.ONE;
/**
* Pseudo BigInteger.TWO
*/
private static final BigInteger TWO = new BigInteger("2");
private BigInteger myKey;
private BigInteger myMod;
private int blockSize;
public RSA (BigInteger key, BigInteger n, int b) {
myKey = key;
myMod = n;
blockSize = b;
}
public void encodeFile (String filename) {
byte[] bytes = new byte[blockSize / 8 + 1];
byte[] temp;
int tempLen;
InputStream is = null;
FileWriter writer = null;
try {
is = new FileInputStream(filename);
writer = new FileWriter(filename + ".enc");
}
catch (FileNotFoundException e1){
System.out.println("File not found: " + filename);
}
catch (IOException e1){
System.out.println("File not found: " + filename + ".enc");
}
/**
* Write encoded message to 'filename'.enc
*/
try {
while ((tempLen = is.read(bytes, 1, blockSize / 8)) 0) {
for (int i = tempLen + 1; i bytes.length; ++i) {
bytes[i] = 0;
}
writer.write(encodeDecode(new BigInteger(bytes)) + " ");
}
}
catch (IOException e1) {
System.out.println("error writing to file");
}
/**
* Close input stream and file writer
*/
try {
is.close();
writer.close();
}
catch (IOException e1) {
System.out.println("Error closing file.");
}
}
public void decodeFile (String filename) {
FileReader reader = null;
OutputStream os = null;
try {
reader = new FileReader(filename);
os = new FileOutputStream(filename.replaceAll(".enc", ".dec"));
}
catch (FileNotFoundException e1) {
if (reader == null)
System.out.println("File not found: " + filename);
else
System.out.println("File not found: " + filename.replaceAll(".enc", "dec"));
}
BufferedReader br = new BufferedReader(reader);
int offset;
byte[] temp, toFile;
StringTokenizer st = null;
try {
while (br.ready()) {
st = new StringTokenizer(br.readLine());
while (st.hasMoreTokens()){
toFile = encodeDecode(new BigInteger(st.nextToken())).toByteArray();
System.out.println(toFile.length + " x " + (blockSize / 8));
if (toFile[0] == 0 toFile.length != (blockSize / 8)) {
temp = new byte[blockSize / 8];
offset = temp.length - toFile.length;
for (int i = toFile.length - 1; (i = 0) ((i + offset) = 0); --i) {
temp[i + offset] = toFile[i];
}
toFile = temp;
}
/*if (toFile.length != ((blockSize / 8) + 1)){
temp = new byte[(blockSize / 8) + 1];
System.out.println(toFile.length + " x " + temp.length);
for (int i = 1; i temp.length; i++) {
temp[i] = toFile[i - 1];
}
toFile = temp;
}
else
System.out.println(toFile.length + " " + ((blockSize / 8) + 1));*/
os.write(toFile);
}
}
}
catch (IOException e1) {
System.out.println("Something went wrong");
}
/**
* close data streams
*/
try {
os.close();
reader.close();
}
catch (IOException e1) {
System.out.println("Error closing file.");
}
}
/**
* Performs ttbase/tt^supttpow/tt/sup within the modular
* domain of ttmod/tt.
*
* @param base the base to be raised
* @param pow the power to which the base will be raisded
* @param mod the modular domain over which to perform this operation
* @return ttbase/tt^supttpow/tt/sup within the modular
* domain of ttmod/tt.
*/
public BigInteger encodeDecode(BigInteger base) {
BigInteger a = ONE;
BigInteger s = base;
BigInteger n = myKey;
while (!n.equals(ZERO)) {
if(!n.mod(TWO).equals(ZERO))
a = a.multiply(s).mod(myMod);
s = s.pow(2).mod(myMod);
n = n.divide(TWO);
}
return a;
}
}
在這里提供兩個版本的RSA算法JAVA實現(xiàn)的代碼下載:
1. 來自于 的RSA算法實現(xiàn)源代碼包:
2. 來自于 的實現(xiàn):
- 源代碼包
- 編譯好的jar包
另外關于RSA算法的php實現(xiàn)請參見文章:
php下的RSA算法實現(xiàn)
關于使用VB實現(xiàn)RSA算法的源代碼下載(此程序采用了psc1算法來實現(xiàn)快速的RSA加密):
RSA加密的JavaScript實現(xiàn):
參考下面代碼:
try?{
KeyPairGenerator?keyPairGen?=?KeyPairGenerator.getInstance("RSA",
new?org.bouncycastle.jce.provider.BouncyCastleProvider());
final?int?KEY_SIZE?=?128;//?沒什么好說的了,這個值關系到塊加密的大小,可以更改,但是不要太大,否則效率會低
keyPairGen.initialize(KEY_SIZE,?new?SecureRandom());
KeyPair?keyPair?=?keyPairGen.generateKeyPair();
return?keyPair;
}?catch?(Exception?e)?{
throw?new?Exception(e.getMessage());
}
樓主看看下面的代碼是不是你所需要的,這是我原來用的時候收集的
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 工具類。提供加密,解密,生成密鑰對等方法。
* 需要到下載bcprov-jdk14-123.jar。
* RSA加密原理概述
* RSA的安全性依賴于大數(shù)的分解,公鑰和私鑰都是兩個大素數(shù)(大于100的十進制位)的函數(shù)。
* 據(jù)猜測,從一個密鑰和密文推斷出明文的難度等同于分解兩個大素數(shù)的積
* ===================================================================
* (該算法的安全性未得到理論的證明)
* ===================================================================
* 密鑰的產生:
* 1.選擇兩個大素數(shù) 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(二進制表示) 分成等長的數(shù)據(jù)塊 m1,m2,...,mi 塊長 s(盡可能大) ,其中 2^sn
* 2:對應的密文是: ci = mi^e(mod n)
* 3:解密時作如下計算: mi = ci^d(mod n)
* ===================================================================
* RSA速度
* 由于進行的都是大數(shù)計算,使得RSA最快的情況也比DES慢上100倍,無論是軟件還是硬件實現(xiàn)。
* 速度一直是RSA的缺陷。一般來說只用于少量數(shù)據(jù)加密。
* 文件名:RSAUtil.javabr
* @author 趙峰br
* 版本:1.0.1br
* 描述:本算法摘自網(wǎng)絡,是對RSA算法的實現(xiàn)br
* 創(chuàng)建時間:2009-7-10 下午09:58:16br
* 文件描述:首先生成兩個大素數(shù),然后根據(jù)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 modulus
* @param publicExponent
* @return RSAPublicKey
* @throws Exception
*/
private RSAPublicKey generateRSAPublicKey(byte[] modulus, 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(modulus), new BigInteger(publicExponent));
try {
return (RSAPublicKey) keyFac.generatePublic(pubKeySpec);
} catch (InvalidKeySpecException ex) {
throw new Exception(ex.getMessage());
}
}
/**
* 生成私鑰
* @param modulus
* @param privateExponent
* @return RSAPrivateKey
* @throws Exception
*/
private RSAPrivateKey generateRSAPrivateKey(byte[] modulus, 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(modulus), new BigInteger(privateExponent));
try {
return (RSAPrivateKey) keyFac.generatePrivate(priKeySpec);
} catch (InvalidKeySpecException ex) {
throw new Exception(ex.getMessage());
}
}
/**
* 加密
* @param key 加密的密鑰
* @param data 待加密的明文數(shù)據(jù)
* @return 加密后的數(shù)據(jù)
* @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);
// 獲得加密塊大小,如:加密前數(shù)據(jù)為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方法不可用,查看源代碼后發(fā)現(xiàn)每次doUpdate后并沒有什么實際動作除了把byte[]放到ByteArrayOutputStream中
// 而最后doFinal的時候才將所有的byte[]進行加密,可是到了此時加密塊大小很可能已經超出了OutputSize所以只好用dofinal方法。
i++;
}
return raw;
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
/**
* 解密
* @param key 解密的密鑰
* @param raw 已經加密的數(shù)據(jù)
* @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();
//獲取公鑰系數(shù)(字節(jié)數(shù)組形式)
byte[] pubModBytes = pubKey.getModulus().toByteArray();
//返回公鑰公用指數(shù)(字節(jié)數(shù)組形式)
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();
// 返回私鑰系數(shù)(字節(jié)數(shù)組形式)
byte[] priModBytes = priKey.getModulus().toByteArray();
// 返回私鑰專用指數(shù)(字節(jié)數(shù)組形式)
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()))));
}
}
代碼如下,需要依賴一個jar包commons-codec-1.9.jar,用于Base64轉換,請自行下載。
import?org.apache.commons.codec.binary.Base64;
import?javax.crypto.BadPaddingException;
import?javax.crypto.Cipher;
import?javax.crypto.IllegalBlockSizeException;
import?java.io.ByteArrayOutputStream;
import?java.io.UnsupportedEncodingException;
import?java.security.*;
import?java.security.interfaces.RSAPrivateKey;
import?java.security.interfaces.RSAPublicKey;
import?java.security.spec.PKCS8EncodedKeySpec;
import?java.security.spec.X509EncodedKeySpec;
public?class?RSAUtils?{
//?加密方式
public?static?final?String?ALGORITHM?=?"RSA";
//?簽名算法
private?static?final?String?SIGNATURE_ALGORITHM?=?"SHA1WithRSA";
//?創(chuàng)建密鑰對初始長度
private?static?final?int?KEY_SIZE?=?512;
//?字符編碼格式
private?static?final?String?CHARSET?=?"UTF-8";
//?RSA最大加密明文大小
private?static?final?int?MAX_ENCRYPT_BLOCK?=?117;
//?RSA最大解密密文大小
private?static?final?int?MAX_DECRYPT_BLOCK?=?128;
private?KeyFactory?keyFactory;
public?RSAUtils()?throws?NoSuchAlgorithmException?{
keyFactory?=?KeyFactory.getInstance(ALGORITHM);
}
/**
*?私鑰加密
*
*?@param?content????待加密字符串
*?@param?privateKey?私鑰
*?@return?加密后字符串(BASE64編碼)
*/
public?String?encryptByPrivateKey(String?content,?String?privateKey)?throws?Exception?{
String?result;
try?(ByteArrayOutputStream?out?=?new?ByteArrayOutputStream())?{
byte[]?keyBytes?=?new?Base64().decode(privateKey);
PKCS8EncodedKeySpec?pkcs8KeySpec?=?new?PKCS8EncodedKeySpec(keyBytes);
PrivateKey?pKey?=?keyFactory.generatePrivate(pkcs8KeySpec);
Cipher?cipher?=?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?(Exception?e)?{
throw?new?Exception(e);
}
return?result;
}
/**
*?公鑰解密
*
*?@param?content???已加密字符串(BASE64加密)
*?@param?publicKey?公鑰
*?@return
*/
public?String?decryptByPublicKey(String?content,?String?publicKey)?throws?Exception?{
String?result?=?"";
try?(ByteArrayOutputStream?out?=?new?ByteArrayOutputStream())?{
byte[]?keyBytes?=?new?Base64().decode(publicKey);
X509EncodedKeySpec?x509KeySpec?=?new?X509EncodedKeySpec(keyBytes);
PublicKey?pKey?=?keyFactory.generatePublic(x509KeySpec);
Cipher?cipher?=?Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE,?pKey);
byte[]?data?=?Base64.decodeBase64(content);
write2Stream(cipher,?data,?out);
byte[]?resultBytes?=?out.toByteArray();
result?=?new?String(resultBytes);
}?catch?(Exception?e)?{
throw?new?Exception(e);
}
return?result;
}
/**
*?公鑰加密
*
*?@param?content???待加密字符串
*?@param?publicKey?公鑰
*?@return?加密后字符串(BASE64編碼)
*/
public?String?encryptByPublicKey(String?content,?String?publicKey)?throws?Exception?{
String?result?=?"";
try?(ByteArrayOutputStream?out?=?new?ByteArrayOutputStream())?{
byte[]?keyBytes?=?new?Base64().decode(publicKey);
X509EncodedKeySpec?x509KeySpec?=?new?X509EncodedKeySpec(keyBytes);
PublicKey?pKey?=?keyFactory.generatePublic(x509KeySpec);
Cipher?cipher?=?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?(Exception?e)?{
throw?new?Exception(e);
}
return?result;
}
/**
*?私鑰解密
*
*?@param?content????已加密字符串
*?@param?privateKey?私鑰
*?@return?解密后字符串
*/
public?String?decryptByPrivateKey(String?content,?String?privateKey)?throws?Exception?{
String?result?=?"";
try?(ByteArrayOutputStream?out?=?new?ByteArrayOutputStream())?{
byte[]?keyBytes?=?new?Base64().decode(privateKey);
PKCS8EncodedKeySpec?pkcs8KeySpec?=?new?PKCS8EncodedKeySpec(keyBytes);
PrivateKey?pKey?=?keyFactory.generatePrivate(pkcs8KeySpec);
Cipher?cipher?=?Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE,?pKey);
byte[]?data?=?Base64.decodeBase64(content);
write2Stream(cipher,?data,?out);
byte[]?resultBytes?=?out.toByteArray();
result?=?new?String(resultBytes);
}?catch?(Exception?e)?{
throw?new?Exception(e);
}
return?result;
}
private?static?void?write2Stream(Cipher?cipher,?byte[]?data,?ByteArrayOutputStream?out)?throws
BadPaddingException,?IllegalBlockSizeException?{
int?dataLen?=?data.length;
int?offSet?=?0;
byte[]?cache;
int?i?=?0;
//?對數(shù)據(jù)分段解密
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;
}
}
/**
*?用私鑰對信息生成數(shù)字簽名
*
*?@param?data???????已加密數(shù)據(jù)
*?@param?privateKey?私鑰(BASE64編碼)
*?@return?sign
*/
public?String?sign(String?data,?String?privateKey)?throws?Exception?{
String?result?=?"";
try?{
byte[]?keyBytes?=?new?Base64().decode(privateKey);
PKCS8EncodedKeySpec?pkcs8KeySpec?=?new?PKCS8EncodedKeySpec(keyBytes);
PrivateKey?privateK?=?keyFactory.generatePrivate(pkcs8KeySpec);
Signature?signature?=?Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initSign(privateK);
signature.update(parse2HexStr(data).getBytes(CHARSET));
result?=?new?Base64().encodeToString(signature.sign());
}?catch?(Exception?e)?{
throw?new?Exception(e);
}
return?result;
}
/**
*?校驗數(shù)字簽名
*
*?@param?data??????已加密數(shù)據(jù)
*?@param?publicKey?公鑰(BASE64編碼)
*?@param?sign??????數(shù)字簽名
*?@return
*?@throws?Exception
*/
public?boolean?verify(String?data,?String?publicKey,?String?sign)?throws?Exception?{
boolean?result;
try?{
byte[]?keyBytes?=?new?Base64().decode(publicKey);
X509EncodedKeySpec?keySpec?=?new?X509EncodedKeySpec(keyBytes);
PublicKey?publicK?=?keyFactory.generatePublic(keySpec);
Signature?signature?=?Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initVerify(publicK);
signature.update(parse2HexStr(data).getBytes(CHARSET));
result?=?signature.verify(new?Base64().decode(sign));
}?catch?(Exception?e)?{
throw?new?Exception(e);
}
return?result;
}
/**
*?將二進制轉換成16進制
*
*?@param?data
*?@return
*/
public?static?String?parse2HexStr(String?data)?throws?Exception?{
String?result?=?"";
try?{
byte[]?buf?=?data.getBytes(CHARSET);
StringBuffer?sb?=?new?StringBuffer();
for?(int?i?=?0;?i??buf.length;?i++)?{
String?hex?=?Integer.toHexString(buf[i]??0xFF);
if?(hex.length()?==?1)?{
hex?=?'0'?+?hex;
}
sb.append(hex.toUpperCase());
}
result?=?sb.toString();
}?catch?(UnsupportedEncodingException?e)?{
throw?new?Exception(e);
}
return?result;
}
/**
*?生成公鑰與私鑰
*/
public?static?void?createKey()?throws?Exception?{
try?{
KeyPairGenerator?keyPairGenerator?=?KeyPairGenerator.getInstance(ALGORITHM);
keyPairGenerator.initialize(KEY_SIZE);
KeyPair?keyPair?=?keyPairGenerator.generateKeyPair();
RSAPublicKey?rsaPublicKey?=?(RSAPublicKey)?keyPair.getPublic();
RSAPrivateKey?rsaPrivateKey?=?(RSAPrivateKey)?keyPair.getPrivate();
String?publicKey?=?Base64.encodeBase64String(rsaPublicKey.getEncoded());
String?privateKey?=?Base64.encodeBase64String(rsaPrivateKey.getEncoded());
System.out.println("publicKey="?+?publicKey?+?"\nprivateKey="?+?privateKey);
}?catch?(NoSuchAlgorithmException?e)?{
throw?new?Exception(e);
}
}
public?static?void?main(String[]?args)?throws?Exception?{
String?PRIVATE_KEY?=?"MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAKeYGXH6Vz+m+KuL11RDRaNdHB4YQeZgqpJGPRSwBelgvEoHu2/fNs1bmgfJhI8lhr/o/Hy8EFB/I/DDyLcCcU4bCLtxpki8edC+KJR2WvyYfnVmWEe/3q2jSVKRf81868q9Cd3MMfrQPMsY4x0TQ0GtOf/nMSMbAltV2W8J86IfAgMBAAECgYEApYu4lr2SMW3ddJZNvQ42W4g9nfyYG9igpJx8+VJmhIDpfLbmjzsOBwvUupx0NHH9CNQ7k3qxItJzzf+W5C+lesEOAqdO5nahRZsL8BIDoxTEn2j+1GXkzQw3vqPY50xqRnZsoP5TyNNsOM7KYaOoz4VFMdVIFwoT3OKM5z7mxgECQQD51r17WZDSa/kucaH7gCOePxJPS6Ust0eVd5tBOMpFzD/VtziogSIWyhGKkLH0SyTJEe91CCpdpxufLSZgIiN5AkEAq7ojtvU4twak1N1/1qX+t8f5wD8i/8GU702PeCwkGI5ymrARq+W2yCuvU1bouXBhjKHV4KhafKYixdHUMg00VwJAYVUjpLaUESY3gbyLWqvlNHVl8LaLtwwAO17JgXNaei7Ef8JNtHf6i95VTyJn8cCEqEDwhSuVNb8wp6azWKh0IQJBAJHrcT2d0bt0IcvfCynRk0eG3WnGPG8mhu9w8GAk4ecb47YdtmZio5YjyK8AQnCQVdOyEJL9eyY/5XxCeBSvs7ECQQCKQ2f5HLDkkHvc6rlaHCJmqNRCS+CxhoaiaSPYLAac7WXmb614ACLECc86C/nkefTq0SNpUDVbGxVpJi9/FOUf";
String?PUBLIC_KEY?=?"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnmBlx+lc/pviri9dUQ0WjXRweGEHmYKqSRj0UsAXpYLxKB7tv3zbNW5oHyYSPJYa/6Px8vBBQfyPww8i3AnFOGwi7caZIvHnQviiUdlr8mH51ZlhHv96to0lSkX/NfOvKvQndzDH60DzLGOMdE0NBrTn/5zEjGwJbVdlvCfOiHwIDAQAB";
RSAUtils?rsaUtil?=?new?RSAUtils();
String?encryptByPublicKey?=?rsaUtil.encryptByPublicKey("你好!",?PUBLIC_KEY);
System.out.println(encryptByPublicKey);
String?decryptByPrivateKey?=?rsaUtil.decryptByPrivateKey(encryptByPublicKey,?PRIVATE_KEY);
System.out.println(decryptByPrivateKey);
String?encryptByPrivateKey?=?rsaUtil.encryptByPrivateKey("你好!",?PRIVATE_KEY);
System.out.println(encryptByPrivateKey);
String?decryptByPublicKey?=?rsaUtil.decryptByPublicKey(encryptByPrivateKey,?PUBLIC_KEY);
System.out.println(decryptByPublicKey);
String?sign?=?rsaUtil.sign("1234",?PRIVATE_KEY);
System.out.println("sign:"?+?sign);
System.out.println(rsaUtil.verify("1234",?PUBLIC_KEY,?sign));
}
}