導航:首頁 > 文檔加密 > javarsa加密工具

javarsa加密工具

發布時間:2022-08-24 05:42:12

java RSA 加密解密中 密鑰保存並讀取,數據加密解密並保存讀取 問題

幫你完善了下代碼。

importjava.io.File;
importjava.io.FileOutputStream;
importjava.io.FileReader;
importjava.io.OutputStream;
importjava.io.PrintWriter;
importjava.io.Reader;
importjava.util.Map;

publicclassTest{
staticStringpublicKey;
staticStringprivateKey;

publicTest()throwsException{
//TODOAuto-generatedconstructorstub
Map<String,Object>keyMap=RSAUtils.genKeyPair();
publicKey=RSAUtils.getPublicKey(keyMap);
privateKey=RSAUtils.getPrivateKey(keyMap);

//保存密鑰,名字分別為publicKey。txt和privateKey。txt;
PrintWriterpw1=newPrintWriter(newFileOutputStream(
"D:/publicKey.txt"));
PrintWriterpw2=newPrintWriter(newFileOutputStream(
"D:/privateKey.txt"));
pw1.print(publicKey);
pw2.print(privateKey);
pw1.close();
pw2.close();

//從保存的目錄讀取剛才的保存的公鑰,
Stringpubkey=readFile("D:/publicKey.txt");//讀取的公鑰內容;
Stringdata=readFile("D:/1.txt");//需要公鑰加密的文件的內容(如D:/1.txt)
byte[]encByPubKeyData=RSAUtils.encryptByPublicKey(data.getBytes(),
pubkey);
//將加密數據base64後寫入文件
writeFile("D:/Encfile.txt",Base64Utils.encode(encByPubKeyData).getBytes("UTF-8"));
//加密後的文件保存在

Stringprikey=readFile("D:/privateKey.txt");//從保存的目錄讀取剛才的保存的私鑰,
StringEncdata=readFile("D:/Encfile.txt");//剛才加密的文件的內容;
byte[]encData=Base64Utils.decode(Encdata);
byte[]decByPriKeyData=RSAUtils.decryptByPrivateKey(encData,prikey);
//解密後後的文件保存在D:/Decfile.txt
writeFile("D:/Decfile.txt",decByPriKeyData);
}

privatestaticStringreadFile(StringfilePath)throwsException{
FileinFile=newFile(filePath);
longfileLen=inFile.length();
Readerreader=newFileReader(inFile);

char[]content=newchar[(int)fileLen];
reader.read(content);
System.out.println("讀取到的內容為:"+newString(content));
returnnewString(content);
}

privatestaticvoidwriteFile(StringfilePath,byte[]content)
throwsException{
System.out.println("待寫入文件的內容為:"+newString(content));
FileoutFile=newFile(filePath);
OutputStreamout=newFileOutputStream(outFile);
out.write(content);
if(out!=null)out.close();
}

publicstaticvoidmain(String[]args)throwsException{
//TODOAuto-generatedmethodstub

newTest();
}

}

測試結果:

讀取到的內容為:++lXfZxzNpeA+rHaxmeQ2qI+5ES9AF7G6KIwjzakKsA08Ly+1y3dp0BnoyHF7/Pj3AS28fDmE5piea7w36vp4E3Ts+F9vwIDAQAB
讀取到的內容為:鍩縣ahaha

Ⅱ 怎樣用Java實現RSA加密

提供加密,解密,生成密鑰對等方法。�梢願�模��遣灰��螅�裨蛐�駛岬� 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 */ public static 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 */ public static 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 static 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); int blockSize = cipher.getBlockSize();//獲得加密塊大小� i++; } return raw; } catch (Exception e) { throw new Exception(e.getMessage()); } } /** * 解密 * @param key 解密的密鑰 * @param raw 已經加密的數據 * @return 解密後的明文 * @throws Exception */ public static 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()); } } /** * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { File file = new File("c:/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 = RSA.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 = RSA.generateRSAPublicKey(pubModBytes,pubPubExpBytes); RSAPrivateKey recoveryPriKey = RSA.generateRSAPrivateKey(priModBytes,priPriExpBytes); byte[] raw = RSA.encrypt(priKey, orgData); file = new File("c:/encrypt_result.dat"); OutputStream out = new FileOutputStream(file); out.write(raw); out.close(); byte[] data = RSA.decrypt(recoveryPubKey, raw); file = new File("c:/decrypt_result.html"); out = new FileOutputStream(file); out.write(data); out.flush(); out.close(); } } (責任編輯:雲子)

Ⅲ 高分求java的RSA 和IDEA 加密解密演算法

RSA演算法非常簡單,概述如下:
找兩素數p和q
取n=p*q
取t=(p-1)*(q-1)
取任何一個數e,要求滿足e<t並且e與t互素(就是最大公因數為1)
取d*e%t==1

這樣最終得到三個數: n d e

設消息為數M (M <n)
設c=(M**d)%n就得到了加密後的消息c
設m=(c**e)%n則 m == M,從而完成對c的解密。
註:**表示次方,上面兩式中的d和e可以互換。

在對稱加密中:
n d兩個數構成公鑰,可以告訴別人;
n e兩個數構成私鑰,e自己保留,不讓任何人知道。
給別人發送的信息使用e加密,只要別人能用d解開就證明信息是由你發送的,構成了簽名機制。
別人給你發送信息時使用d加密,這樣只有擁有e的你能夠對其解密。

rsa的安全性在於對於一個大數n,沒有有效的方法能夠將其分解
從而在已知n d的情況下無法獲得e;同樣在已知n e的情況下無法
求得d。

<二>實踐

接下來我們來一個實踐,看看實際的操作:
找兩個素數:
p=47
q=59
這樣
n=p*q=2773
t=(p-1)*(q-1)=2668
取e=63,滿足e<t並且e和t互素
用perl簡單窮舉可以獲得滿主 e*d%t ==1的數d:
C:\Temp>perl -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的大數計算來算一下:
C:\Temp>perl -Mbigint -e "print 244**847%2773"
465
即用d對M加密後獲得加密信息c=465

解密:

我們可以用e來對加密後的c進行解密,還原M:
m=c**e%n=465**63%2773 :
C:\Temp>perl -Mbigint -e "print 465**63%2773"
244
即用e對c解密後獲得m=244 , 該值和原始信息M相等。

<三>字元串加密

把上面的過程集成一下我們就能實現一個對字元串加密解密的示例了。
每次取字元串中的一個字元的ascii值作為M進行計算,其輸出為加密後16進制
的數的字元串形式,按3位元組表示,如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_CORE{d});

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->(); $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->(); $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:\Temp>perl rsa-test.pl
N=2773 D=847 E=63
原始串:RSA 娃哈哈哈~~~
加密串:
解密串:RSA 娃哈哈哈~~~

C:\Temp>perl rsa-test.pl 安全焦點(xfocus)
N=2773 D=847 E=63
原始串:安全焦點(xfocus)
加密串:
解密串:安全焦點(xfocus)

<四>提高

前面已經提到,rsa的安全來源於n足夠大,我們測試中使用的n是非常小的,根本不能保障安全性,
我們可以通過RSAKit、RSATool之類的工具獲得足夠大的N 及D E。
通過工具,我們獲得1024位的N及D E來測試一下:

n=EC3A85F5005D
4C2013433B383B
A50E114705D7E2
BC511951

d=0x10001

e=DD28C523C2995
47B77324E66AFF2
789BD782A592D2B
1965

設原始信息
M=

完成這么大數字的計算依賴於大數運算庫,用perl來運算非常簡單:

A) 用d對M進行加密如下:
c=M**d%n :
C:\Temp>perl -Mbigint -e " $x=Math::BigInt->bmodpow(0x11111111111122222222222233
333333333, 0x10001,
D55EDBC4F0
6E37108DD6
);print $x->as_hex"
b73d2576bd
47715caa6b
d59ea89b91
f1834580c3f6d90898

即用d對M加密後信息為:
c=b73d2576bd
47715caa6b
d59ea89b91
f1834580c3f6d90898

B) 用e對c進行解密如下:

m=c**e%n :
C:\Temp>perl -Mbigint -e " $x=Math::BigInt->bmodpow(0x17b287be418c69ecd7c39227ab
5aa1d99ef3
0cb4764414
, 0xE760A
3C29954C5D
7324E66AFF
2789BD782A
592D2B1965, CD15F90
4F017F9CCF
DD60438941
);print $x->as_hex"

(我的P4 1.6G的機器上計算了約5秒鍾)

得到用e解密後的m= == M

C) RSA通常的實現
RSA簡潔幽雅,但計算速度比較慢,通常加密中並不是直接使用RSA 來對所有的信息進行加密,
最常見的情況是隨機產生一個對稱加密的密鑰,然後使用對稱加密演算法對信息加密,之後用
RSA對剛才的加密密鑰進行加密。

最後需要說明的是,當前小於1024位的N已經被證明是不安全的
自己使用中不要使用小於1024位的RSA,最好使用2048位的。

----------------------------------------------------------

一個簡單的RSA演算法實現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 <tt>base</tt>^<sup><tt>pow</tt></sup> within the molar
* domain of <tt>mod</tt>.
*
* @param base the base to be raised
* @param pow the power to which the base will be raisded
* @param mod the molar domain over which to perform this operation
* @return <tt>base</tt>^<sup><tt>pow</tt></sup> within the molar
* domain of <tt>mod</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實現的代碼下載:

1. 來自於 http://www.javafr.com/code.aspx?ID=27020 的RSA演算法實現源代碼包:
http://zeal.newmenbase.net/attachment/JavaFR_RSA_Source.rar

2. 來自於 http://www.ferrara.linux.it/Members/lucabariani/RSA/implementazioneRsa/ 的實現:
http://zeal.newmenbase.net/attachment/sorgentiJava.tar.gz - 源代碼包
http://zeal.newmenbase.net/attachment/algoritmoRSA.jar - 編譯好的jar包

另外關於RSA演算法的php實現請參見文章:
php下的RSA演算法實現

關於使用VB實現RSA演算法的源代碼下載(此程序採用了psc1演算法來實現快速的RSA加密):
http://zeal.newmenbase.net/attachment/vb_PSC1_RSA.rar

RSA加密的JavaScript實現: http://www.ohdave.com/rsa/

Ⅳ java rsa加密,高並發如何解決

把你的加密的過程做成同步的,就不會存在這個問題了

Ⅳ 基於java的rsa對文件加密。java寫的後台

一定要把邏輯寫進jsp嗎?如果是,可以把你的java類import進jsp,然後直接在jsp的<%%>里new一個調用就行。比如<%MyClass myClass = new MyClass(); String encData = myClass.rsaEncrypt(myData);%>

Ⅵ Java程序設計一文件用RSA演算法進行加密和解密,請高人幫忙

計一文件用RSA演算法進行加密和解
z這個任務書沒有嗎

Ⅶ 求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實現對文件加密解密

這個我不清楚。

對文件加密,我使用的是超級加密3000.

超級加密3000採用國際上成熟的加密演算法和安全快速的加密方法,可以有效保障數據安全!

具體操作方法:

1下載安裝超級加密3000。

2 然後在需要加密的文件上單擊滑鼠右鍵選擇加密。

3 在彈出的文件加密窗口中設置文件加密密碼就OK了。

超級加密3000的下載地址你可以在網路上搜索超級加密3000,第一個就是。

Ⅸ JAVA裡面RSA加密演算法的使用

RSA的Java實現不能一次加密很大的字元,自己處理了一下,見下面的代碼。Base64編碼類用的是一個Public domain Base64 for java http://iharder.sourceforge.net/current/java/base64/其他的保存公鑰到文件等簡單的實現,就不詳細說了,看代碼吧。==============================================import java.security.*;import java.security.spec.PKCS8EncodedKeySpec;import java.security.spec.X509EncodedKeySpec;import java.util.HashMap;import java.util.Map;import javax.crypto.*;import java.io.*;public class Encryptor {private static final String KEY_FILENAME = "c:\\mykey.dat";private static final String OTHERS_KEY_FILENAME = "c:\\Otherskey.dat";// private static final int KEY_SIZE = 1024;// private static final int BLOCK_SIZE = 117;// private static final int OUTPUT_BLOCK_SIZE = 128;private static final int KEY_SIZE = 2048; //RSA key 是多少位的private static final int BLOCK_SIZE = 245; //一次RSA加密操作所允許的最大長度//這個值與 KEY_SIZE 已經padding方法有關。因為 1024的key的輸出是128,2048key輸出是256位元組//可能11個位元組用於保存padding信息了,所以最多可用的就只有245位元組了。private static final int OUTPUT_BLOCK_SIZE = 256;private SecureRandom secrand;private Cipher rsaCipher;private KeyPair keys;private Map<String, Key> allUserKeys;public Encryptor() throws Exception {try {allUserKeys = new HashMap<String, Key>();secrand = new SecureRandom();//SunJCE Provider 中只支持ECB mode,試了一下只有PKCS1PADDING可以直接還原原始數據,//NOPadding導致解壓出來的都是blocksize長度的數據,還要自己處理//參見 http://java.sun.com/javase/6/docs/technotes/guides/security/SunProviders.html#SunJCEProvider////另外根據 Open-JDK-6.b17-src( http://www.docjar.com/html/api/com/sun/crypto/provider/RSACipher.java.html)// 中代碼的注釋,使用RSA來加密大量數據不是一種標準的用法。所以現有實現一次doFinal調用之進行一個RSA操作,//如果用doFinal來加密超過的一個操作所允許的長度數據將拋出異常。//根據keysize的長度,典型的1024個長度的key和PKCS1PADDING一起使用時//一次doFinal調用只能加密117個byte的數據。(NOPadding 和1024 keysize時128個位元組長度)//(2048長度的key和PKCS1PADDING 最多允許245位元組一次)//想用來加密大量數據的只能自己用其他辦法實現了。可能RSA加密速度比較慢吧,要用AES才行rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (NoSuchPaddingException e) {e.printStackTrace();throw e;}ObjectInputStream in;try {in = new ObjectInputStream(new FileInputStream(KEY_FILENAME));} catch (FileNotFoundException e) {if (false == GenerateKeys()){throw e;}LoadKeys();return;}keys = (KeyPair) in.readObject();in.close();LoadKeys();}/** 生成自己的公鑰和私鑰*/private Boolean GenerateKeys() {try {KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");// secrand = new SecureRandom();// sedSeed之後會造成 生成的密鑰都是一樣的// secrand.setSeed("chatencrptor".getBytes()); // 初始化隨機產生器//key長度至少512長度,不過好像說現在用2048才算比較安全的了keygen.initialize(KEY_SIZE, secrand); // 初始化密鑰生成器keys = keygen.generateKeyPair(); // 生成密鑰組AddKey("me", EncodeKey(keys.getPublic()));} catch (NoSuchAlgorithmException e) {e.printStackTrace();return false;}ObjectOutputStream out;try {out = new ObjectOutputStream(new FileOutputStream(KEY_FILENAME));} catch (IOException e) {e.printStackTrace();return false;}try {out.writeObject(keys);} catch (IOException e) {e.printStackTrace();return false;} finally {try {out.close();} catch (IOException e) {e.printStackTrace();return false;}}return true;}public String EncryptMessage(String toUser, String Message) throws IOException {Key pubkey = allUserKeys.get(toUser);if ( pubkey == null ){throw new IOException("NoKeyForThisUser") ;}try {//PublicKey pubkey = keys.getPublic();rsaCipher.init(Cipher.ENCRYPT_MODE, pubkey, secrand);//System.out.println(rsaCipher.getBlockSize()); 返回0,非block 加密演算法來的?//System.out.println(Message.getBytes("utf-8").length);//byte[] encryptedData = rsaCipher.doFinal(Message.getBytes("utf-8"));byte[] data = Message.getBytes("utf-8");int blocks = data.length / BLOCK_SIZE ;int lastBlockSize = data.length % BLOCK_SIZE ;byte [] encryptedData = new byte[ (lastBlockSize == 0 ? blocks : blocks + 1)* OUTPUT_BLOCK_SIZE];for (int i=0; i < blocks; i++){//int thisBlockSize = ( i + 1 ) * BLOCK_SIZE > data.length ? data.length - i * BLOCK_SIZE : BLOCK_SIZE ;rsaCipher.doFinal(data,i * BLOCK_SIZE, BLOCK_SIZE, encryptedData ,i * OUTPUT_BLOCK_SIZE);}if (lastBlockSize != 0 ){rsaCipher.doFinal(data, blocks * BLOCK_SIZE, lastBlockSize,encryptedData ,blocks * OUTPUT_BLOCK_SIZE);}//System.out.println(encrypted.length); 如果要機密的數據不足128/256位元組,加密後補全成為變為256長度的。//數量比較小時,Base64.GZIP產生的長度更長,沒什麼優勢//System.out.println(Base64.encodeBytes(encrypted,Base64.GZIP).length());//System.out.println(Base64.encodeBytes(encrypted).length());//System.out.println (rsaCipher.getOutputSize(30));//這個getOutputSize 只對 輸入小於最大的block時才能得到正確的結果。其實就是補全 數據為128/256 位元組return Base64.encodeBytes(encryptedData);} catch (InvalidKeyException e) {e.printStackTrace();throw new IOException("InvalidKey") ;}catch (ShortBufferException e) {e.printStackTrace();throw new IOException("ShortBuffer") ;}catch (UnsupportedEncodingException e) {e.printStackTrace();throw new IOException("UnsupportedEncoding") ;} catch (IllegalBlockSizeException e) {e.printStackTrace();throw new IOException("IllegalBlockSize") ;} catch (BadPaddingException e) {e.printStackTrace();throw new IOException("BadPadding") ;}finally {//catch 中 return 或者throw之前都會先調用一下這里}}public String DecryptMessage(String Message) throws IOException {byte[] decoded = Base64.decode(Message);PrivateKey prikey = keys.getPrivate();try {rsaCipher.init(Cipher.DECRYPT_MODE, prikey, secrand);int blocks = decoded.length / OUTPUT_BLOCK_SIZE;ByteArrayOutputStream decodedStream = new ByteArrayOutputStream(decoded.length);for (int i =0 ;i < blocks ; i ++ ){decodedStream.write (rsaCipher.doFinal(decoded,i * OUTPUT_BLOCK_SIZE, OUTPUT_BLOCK_SIZE));}return new String(decodedStream.toByteArray(), "UTF-8");} catch (InvalidKeyException e) {e.printStackTrace();throw new IOException("InvalidKey");} catch (UnsupportedEncodingException e) {e.printStackTrace();throw new IOException("UnsupportedEncoding");} catch (IllegalBlockSizeException e) {e.printStackTrace();throw new IOException("IllegalBlockSize");} catch (BadPaddingException e) {e.printStackTrace();throw new IOException("BadPadding");} finally {// catch 中 return 或者throw之前都會先調用一下這里。}}public boolean AddKey(String user, String key) {PublicKey publickey;try {publickey = DecodePublicKey(key);} catch (Exception e) {return false;}allUserKeys.put(user, publickey);SaveKeys();return true;}private boolean LoadKeys() {BufferedReader input;try {input = new BufferedReader(new InputStreamReader(new FileInputStream(OTHERS_KEY_FILENAME)));} catch (FileNotFoundException e1) {// e1.printStackTrace();return false;}

閱讀全文

與javarsa加密工具相關的資料

熱點內容
windows重啟mysql命令 瀏覽:729
單片機輸入輸出口接收脈沖 瀏覽:120
控制電腦滑鼠的命令 瀏覽:212
男男強暴電影 瀏覽:604
便利店送貨上門app叫什麼 瀏覽:468
win8怎麼打開命令行 瀏覽:129
p開頭的一個看片軟體 瀏覽:755
西班牙電影不準備的愛情 瀏覽:177
python轉換器使用教程 瀏覽:629
cad圖紙重復圖形命令 瀏覽:769
法國女同床戲多私處可見的電影 瀏覽:926
那你給年齡那邊電影想電影想一起電影 瀏覽:994
原耽小說下載 瀏覽:873
香港一級紅色電影 瀏覽:505
三級倫理電影胸大女主角拍的電影有哪些 瀏覽:170
但為君故by龍彌txt 瀏覽:384
mac安裝不了python庫 瀏覽:258
現代父子訓誡墨唯瑾 瀏覽:290
linux應用防火牆 瀏覽:500
百度雲伺服器白嫖 瀏覽:270