導航:首頁 > 編程語言 > javarsa字元串

javarsa字元串

發布時間:2022-05-31 16:52:18

java通過RSA演算法獲取公私鑰對 將公鑰提供出去 如何獲取字元串的公鑰

直接將公匙BYTE數組轉換為16進制的串啊
private static char hexTable[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
public static String toHexString(byte bytes[])
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++)
{
char chars[] = new char[2];
int d = (bytes[i] & 240) >> 4;
int m = bytes[i] & 15;
chars[0] = hexTable[d];
chars[1] = hexTable[m];
sb.append(chars);
}

return sb.toString();
}

Ⅱ 關於java中rsa的問題

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

Ⅲ Java 第三方公鑰 RSA加密求助

下面是RSA加密代碼。

/**
* RSA演算法,實現數據的加密解密。
* @author ShaoJiang
*
*/
public class RSAUtil {

private static Cipher cipher;

static{
try {
cipher = Cipher.getInstance("RSA");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
}
}

/**
* 生成密鑰對
* @param filePath 生成密鑰的路徑
* @return
*/
public static Map<String,String> generateKeyPair(String filePath){
try {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
// 密鑰位數
keyPairGen.initialize(1024);
// 密鑰對
KeyPair keyPair = keyPairGen.generateKeyPair();
// 公鑰
PublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
// 私鑰
PrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
//得到公鑰字元串
String publicKeyString = getKeyString(publicKey);
//得到私鑰字元串
String privateKeyString = getKeyString(privateKey);

FileWriter pubfw = new FileWriter(filePath+"/publicKey.keystore");
FileWriter prifw = new FileWriter(filePath+"/privateKey.keystore");
BufferedWriter pubbw = new BufferedWriter(pubfw);
BufferedWriter pribw = new BufferedWriter(prifw);
pubbw.write(publicKeyString);
pribw.write(privateKeyString);
pubbw.flush();
pubbw.close();
pubfw.close();
pribw.flush();
pribw.close();
prifw.close();
//將生成的密鑰對返回
Map<String,String> map = new HashMap<String,String>();
map.put("publicKey",publicKeyString);
map.put("privateKey",privateKeyString);
return map;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

/**
* 得到公鑰
*
* @param key
* 密鑰字元串(經過base64編碼)
* @throws Exception
*/
public static PublicKey getPublicKey(String key) throws Exception {
byte[] keyBytes;
keyBytes = (new BASE64Decoder()).decodeBuffer(key);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
}

/**
* 得到私鑰
*
* @param key
* 密鑰字元串(經過base64編碼)
* @throws Exception
*/
public static PrivateKey getPrivateKey(String key) throws Exception {
byte[] keyBytes;
keyBytes = (new BASE64Decoder()).decodeBuffer(key);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return privateKey;
}

/**
* 得到密鑰字元串(經過base64編碼)
*
* @return
*/
public static String getKeyString(Key key) throws Exception {
byte[] keyBytes = key.getEncoded();
String s = (new BASE64Encoder()).encode(keyBytes);
return s;
}

/**
* 使用公鑰對明文進行加密,返回BASE64編碼的字元串
* @param publicKey
* @param plainText
* @return
*/
public static String encrypt(PublicKey publicKey,String plainText){
try {
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] enBytes = cipher.doFinal(plainText.getBytes());
return (new BASE64Encoder()).encode(enBytes);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}

/**
* 使用keystore對明文進行加密
* @param publicKeystore 公鑰文件路徑
* @param plainText 明文
* @return
*/
public static String encrypt(String publicKeystore,String plainText){
try {
FileReader fr = new FileReader(publicKeystore);
BufferedReader br = new BufferedReader(fr);
String publicKeyString="";
String str;
while((str=br.readLine())!=null){
publicKeyString+=str;
}
br.close();
fr.close();
cipher.init(Cipher.ENCRYPT_MODE,getPublicKey(publicKeyString));
byte[] enBytes = cipher.doFinal(plainText.getBytes());
return (new BASE64Encoder()).encode(enBytes);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

/**
* 使用私鑰對明文密文進行解密
* @param privateKey
* @param enStr
* @return
*/
public static String decrypt(PrivateKey privateKey,String enStr){
try {
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] deBytes = cipher.doFinal((new BASE64Decoder()).decodeBuffer(enStr));
return new String(deBytes);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

/**
* 使用keystore對密文進行解密
* @param privateKeystore 私鑰路徑
* @param enStr 密文
* @return
*/
public static String decrypt(String privateKeystore,String enStr){
try {
FileReader fr = new FileReader(privateKeystore);
BufferedReader br = new BufferedReader(fr);
String privateKeyString="";
String str;
while((str=br.readLine())!=null){
privateKeyString+=str;
}
br.close();
fr.close();
cipher.init(Cipher.DECRYPT_MODE, getPrivateKey(privateKeyString));
byte[] deBytes = cipher.doFinal((new BASE64Decoder()).decodeBuffer(enStr));
return new String(deBytes);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

Ⅳ java中的rsa\des演算法的方法

rsa加密解密演算法
1978年就出現了這種演算法,它是第一個既能用於數據加密
也能用於數字簽名的演算法。它易於理解和操作,也很流行。算
法的名字以發明者的名字命名:Ron Rivest, AdiShamir 和
Leonard Adleman。但RSA的安全性一直未能得到理論上的證明。

RSA的安全性依賴於大數分解。公鑰和私鑰都是兩個大素數
( 大於 100個十進制位)的函數。據猜測,從一個密鑰和密文
推斷出明文的難度等同於分解兩個大素數的積。

密鑰對的產生:選擇兩個大素數,p 和q 。計算:
n = p * q
然後隨機選擇加密密鑰e,要求 e 和 ( p - 1 ) * ( q - 1 )
互質。最後,利用Euclid 演算法計算解密密鑰d, 滿足

e * d = 1 ( mod ( p - 1 ) * ( q - 1 ) )

其中n和d也要互質。數e和
n是公鑰,d是私鑰。兩個素數p和q不再需要,應該丟棄,不要讓任
何人知道。 加密信息 m(二進製表示)時,首先把m分成等長數據
塊 m1 ,m2,..., mi ,塊長s,其中 2^s <= n, s 盡可能的大。對
應的密文是:

ci = mi^e ( mod n ) ( a )

解密時作如下計算:

mi = ci^d ( mod n ) ( b )

RSA 可用於數字簽名,方案是用 ( a ) 式簽名, ( b )
式驗證。具體操作時考慮到安全性和 m信息量較大等因素,一般是先
作 HASH 運算。

RSA 的安全性。
RSA的安全性依賴於大數分解,但是否等同於大數分解一直未能得到理
論上的證明,因為沒有證明破解RSA就一定需要作大數分解。假設存在
一種無須分解大數的演算法,那它肯定可以修改成為大數分解演算法。目前,
RSA的一些變種演算法已被證明等價於大數分解。不管怎樣,分解n是最顯
然的攻擊方法。現在,人們已能分解140多個十進制位的大素數。因此,
模數n必須選大一些,因具體適用情況而定。

RSA的速度:
由於進行的都是大數計算,使得RSA最快的情況也比DES慢上100倍,無論
是軟體還是硬體實現。速度一直是RSA的缺陷。一般來說只用於少量數據
加密。

RSA的選擇密文攻擊:
RSA在選擇密文攻擊面前很脆弱。一般攻擊者是將某一信息作一下偽裝
(Blind),讓擁有私鑰的實體簽署。然後,經過計算就可得到它所想要的信
息。實際上,攻擊利用的都是同一個弱點,即存在這樣一個事實:乘冪保
留了輸入的乘法結構:

( XM )^d = X^d *M^d mod n

前面已經提到,這個固有的問題來自於公鑰密碼系統的最有用的特徵
--每個人都能使用公鑰。但從演算法上無法解決這一問題,主要措施有
兩條:一條是採用好的公鑰協議,保證工作過程中實體不對其他實體
任意產生的信息解密,不對自己一無所知的信息簽名;另一條是決不
對陌生人送來的隨機文檔簽名,簽名時首先使用One-Way HashFunction
對文檔作HASH處理,或同時使用不同的簽名演算法。在中提到了幾種不
同類型的攻擊方法。

RSA的公共模數攻擊。
若系統中共有一個模數,只是不同的人擁有不同的e和d,系統將是危險
的。最普遍的情況是同一信息用不同的公鑰加密,這些公鑰共模而且互
質,那末該信息無需私鑰就可得到恢復。設P為信息明文,兩個加密密鑰
為e1和e2,公共模數是n,則:

C1 = P^e1 mod n

C2 = P^e2 mod n

密碼分析者知道n、e1、e2、C1和C2,就能得到P。

因為e1和e2互質,故用Euclidean演算法能找到r和s,滿足:

r * e1 + s * e2 = 1

假設r為負數,需再用Euclidean演算法計算C1^(-1),則

( C1^(-1) )^(-r) * C2^s = P mod n

另外,還有其它幾種利用公共模數攻擊的方法。總之,如果知道給定模數
的一對e和d,一是有利於攻擊者分解模數,一是有利於攻擊者計算出其它
成對的e』和d』,而無需分解模數。解決辦法只有一個,那就是不要共享
模數n。

RSA的小指數攻擊。 有一種提高
RSA速度的建議是使公鑰e取較小的值,這樣會使加密變得易於實現,速度
有所提高。但這樣作是不安全的,對付辦法就是e和d都取較大的值。

RSA演算法是第一個能同時用於加密和數字簽名的演算法,也易於理解和操作。
RSA是被研究得最廣泛的公鑰演算法,從提出到現在已近二十年,經歷了各
種攻擊的考驗,逐漸為人們接受,普遍認為是目前最優秀的公鑰方案之一。
RSA的安全性依賴於大數的因子分解,但並沒有從理論上證明破譯RSA的難
度與大數分解難度等價。即RSA的重大缺陷是無法從理論上把握它的保密性
能如何,而且密碼學界多數人士傾向於因子分解不是NPC問題。

RSA的缺點主要有:
A)產生密鑰很麻煩,受到素數產生技術的限制,因而難以做到一次
一密。B)分組長度太大,為保證安全性,n 至少也要 600 bits
以上,使運算代價很高,尤其是速度較慢,較對稱密碼演算法慢幾個數量級;
且隨著大數分解技術的發展,這個長度還在增加,不利於數據格式的標准化。
目前,SET(Secure Electronic Transaction)協議中要求CA採用2048比特長
的密鑰,其他實體使用1024比特的密鑰。
參考資料:http://superpch.josun.com.cn/bbs/PrintPost.asp?ThreadID=465
CRC加解密演算法
http://www.bouncycastle.org/

Ⅳ java RSA 加密解密,漢字亂碼怎麼辦

這個問題不是加密和解密的事件,而是沒能正確地使用相同的字元集編碼。

加密之前就應該約定雙方使用同一個字元集編碼來做編解碼,比如用 UTF8,我們在用一個 byte[] 創建一個 String 時應該明確地指定字元集編碼而不能使用默認值,因此默認值是跟操作系統或程序啟動時的命令行有依賴關系的,這很難預料誰會使用你的程序,又會如何使用你的程序,我們明確地指定字元集就不會受此影響。

String a = "漢字「

byte[] bytes = a.getBytes("UTF8");

byte[] encoded = encode(bytes);

byte[] decoded = decode(encoded);

String received = new String(decoded, "UTF8");

Ⅵ 高分求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加密演算法的使用

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;}

Ⅷ java給漢字進行RSA加密

//加密操作
Mtext="ninhao!123您好!";
Mtext=java.net.URLEncoder.encode(Mtext,"GBK");
byte ptext[]=Mtext.getBytes("GBK");//將字元串轉換成byte類型數組,實質是各個字元的二進制形式
BigInteger m=new BigInteger(ptext);//二進制串轉換為一個大整數
...
...
//解密操作
...
...
byte[]mt=m.toByteArray();//m為密文的BigInteger類型
String str=(new String(mt,"GBK"));
str=java.net.URLDecoder.decode(str,"GBK");

Ⅸ java字元串轉換為一個RSA公鑰問題,怎麼解決

//將byte數組變成RSAPublicKey
publicRSAPublicKeybytes2PK(byte[]buf){
buf=Base64.decode(buf);
bytesize=buf[0];
bytesize2=buf[1];
byte[]b1=newbyte[size];
System.array(buf,2,b1,0,b1.length);
byte[]b2=newbyte[size2];
System.array(buf,b1.length+2,b2,0,b2.length);
BigIntegerB1=newBigInteger(b1);
BigIntegerB2=newBigInteger(b2);
RSAPublicKeySpecspec=newRSAPublicKeySpec(B1,B2);//存儲的就是這兩個大整形數
KeyFactorykeyFactory;
PublicKeypk=null;
try{
keyFactory=KeyFactory.getInstance("RSA");
pk=keyFactory.generatePublic(spec);
}catch(Exceptione){
e.printStackTrace();
}
return(RSAPublicKey)pk;
}

Ⅹ 在java中使用KeyFactory將給定字元串轉換為RSAPublicKey對象時報錯公鑰非法

//將byte數組變成RSAPublicKey
publicRSAPublicKeybytes2PK(byte[]buf){
buf=Base64.decode(buf);
bytesize=buf[0];
bytesize2=buf[1];
byte[]b1=newbyte[size];
System.array(buf,2,b1,0,b1.length);
byte[]b2=newbyte[size2];
System.array(buf,b1.length+2,b2,0,b2.length);
BigIntegerB1=newBigInteger(b1);
BigIntegerB2=newBigInteger(b2);
RSAPublicKeySpecspec=newRSAPublicKeySpec(B1,B2);//存儲的就是這兩個大整形數
KeyFactorykeyFactory;
PublicKeypk=null;
try{
keyFactory=KeyFactory.getInstance("RSA");
pk=keyFactory.generatePublic(spec);
}catch(Exceptione){
e.printStackTrace();
}
return(RSAPublicKey)pk;
}

公鑰所包含的數據,實際上就是molus、publicExponent這兩個。都可以用byte數組的方式表示。我這邊為了網路傳輸方便,將兩個byte數組拼接在了一起。實際上分開存儲更容易理解。

閱讀全文

與javarsa字元串相關的資料

熱點內容
加密媒體怎麼輸密碼 瀏覽:161
方舟如何刪除伺服器數據 瀏覽:600
用閱讀app怎麼看18 瀏覽:689
gn文件編譯 瀏覽:783
酷閃加密系統 瀏覽:820
區塊鏈數據加密 瀏覽:389
3d命令集 瀏覽:289
單片機的智能產品工廠里有 瀏覽:300
事業單位程序員有必要去嗎 瀏覽:583
人工智慧訓練小鳥python 瀏覽:132
怎樣把兩個pdf合並成一個 瀏覽:681
什麼app帶仿製圖章 瀏覽:420
單片機CJNE什麼意思 瀏覽:569
廊坊伺服器是什麼 瀏覽:763
客戶解壓要打欠條還是收據 瀏覽:774
通過app組件啟動有什麼壞處 瀏覽:775
不屬於國產密碼演算法 瀏覽:861
單片機LED顯示字型檔 瀏覽:353
日本文件夾品牌十大名牌 瀏覽:397
靜脈壓縮襪和打底褲的區別 瀏覽:345