當前位置:首頁 » 編程語言 » javarsa的是

javarsa的是

發布時間: 2025-08-22 21:51:58

java鐢熸垚RSA闈炲圭О鍨嬪姞瀵嗙殑鍏閽ュ拰縐侀掗

銆銆闈炲圭О鍨嬪姞瀵嗛潪甯擱傚悎澶氫釜瀹㈡埛絝鍜屾湇鍔″櫒涔嬮棿鐨勭樺瘑閫氳 瀹㈡埛絝浣跨敤鍚屼竴涓鍏閽ュ皢鏄庢枃鍔犲瘑 鑰岃繖涓鍏閽ヤ笉鑳介嗗悜鐨勮В瀵 瀵嗘枃鍙戦佸埌鏈嶅姟鍣ㄥ悗鏈夋湇鍔″櫒絝鐢ㄧ侀掗瑙e瘑 榪欐牱灝卞仛鍒頒簡鏄庢枃鐨勫姞瀵嗕紶閫

銆銆闈炲圭О鍨嬪姞瀵嗕篃鏈夊畠鍏堝ぉ鐨勭己鐐 鍔犲瘑 瑙e瘑閫熷害鎱㈠埗綰︿簡瀹冪殑鍙戞尌 濡傛灉浣犳湁澶ч噺鐨勬枃瀛楅渶瑕佸姞瀵嗕紶閫 寤鴻浣犻氳繃闈炲圭О鍨嬪姞瀵嗘潵鎶婂圭О鍨 瀵嗛掗 鍒嗗彂鍒板㈡埛絝 鍙婃椂鏇存柊瀵圭О鍨 瀵嗛掗

銆銆import java io *;

銆銆import java security *;

銆銆import javax crypto *;

銆銆import javax crypto spec *;

銆銆/**

銆銆* <p>Title: RSA闈炲圭О鍨嬪姞瀵嗙殑鍏閽ュ拰縐侀掗</p>

銆銆* <p>Description: </p>

銆銆* <p>Copyright: Copyright (c) </p>

銆銆* <p>Company: </p>

銆銆* @author not attributable

銆銆* @version

銆銆*/

銆銆public class KeyRSA {

銆銆private KeyPairGenerator kpg = null;

銆銆private KeyPair kp = null;

銆銆private PublicKey public_key = null;

銆銆private PrivateKey private_key = null;

銆銆private FileOutputStream public_file_out = null;

銆銆private ObjectOutputStream public_object_out = null;

銆銆private FileOutputStream private_file_out = null;

銆銆private ObjectOutputStream private_object_out = null;

銆銆/**

銆銆* 鏋勯犲嚱鏁

銆銆* @param in 鎸囧畾瀵嗗寵闀垮害錛堝彇鍊艱寖鍥 鍀 錛

銆銆* @throws NoSuchAlgorithmException 寮傚父

銆銆*/

銆銆public KeyRSA(int in String address) throws NoSuchAlgorithmException FileNotFoundException IOException

銆銆{

銆銆kpg = KeyPairGenerator getInstance( RSA ); //鍒涘緩 瀵嗗寵瀵 鐢熸垚鍣

銆銆kpg initialize(in); //鎸囧畾瀵嗗寵闀垮害錛堝彇鍊艱寖鍥 鍀 錛

銆銆kp = kpg genKeyPair(); //鐢熸垚 瀵嗗寵瀵 鍏朵腑鍖呭惈鐫涓涓鍏鍖欏拰涓涓縐佸寵鐨勪俊鎮

銆銆public_key = kp getPublic(); //鑾峰緱鍏鍖

銆銆private_key = kp getPrivate(); //鑾峰緱縐佸寵

銆銆//淇濆瓨鍏鍖

銆銆public_file_out = new FileOutputStream(address + /public_key dat );

銆銆public_object_out = new ObjectOutputStream(public_file_out);

銆銆public_object_out writeObject(public_key);

銆銆//淇濆瓨縐佸寵

銆銆private_file_out = new FileOutputStream(address + /private_key dat );

銆銆private_object_out = new ObjectOutputStream(private_file_out);

銆銆private_object_out writeObject(private_key);

銆銆}

銆銆public static void main(String[] args) {

銆銆try {

銆銆System out println( 縐佸寵鍜屽叕鍖欎繚瀛樺埌C鐩樹笅鐨勬枃浠朵腑 );

銆銆new KeyRSA( c:/ );

銆銆}

銆銆catch (IOException ex) {

銆銆}

銆銆catch (NoSuchAlgorithmException ex) {

銆銆}

銆銆}

lishixin/Article/program/Java/hx/201311/26592

Ⅱ 非對稱加密解密RSA的實現例子

最近有接觸到加密相關的內容,本期以非對稱加密為例子,做個簡單的總結和記錄。首先了解下非對稱加密,簡單來說非對稱指的是加密和解密用不同的秘鑰,典型的RSA,這個演算法名稱是基於三個發明人的名字首字母取的;辯含碧而對稱加密必須要在加解密使用相同的秘鑰攜舉,典型的AES。這里細節不多展開闡述,涉及到很多數學原理,如大數的質因數分解等,感興趣的可以找找李永樂等網上比較優秀的科普。這篇文章只是java原生實現的加解密例子。至於其他的如md5,hash等,如果從主觀可讀的角度來說,也可以稱為加密。

如下的示例是使用Java原生實現RSA的加密解密,包括用公鑰加密,然後私鑰解密;或者使用私鑰加密,然後公鑰解密。注意不同key大小,限制的解密內容大小也不一樣,感老備興趣的同學可以試試修改key大小和加密內容長度來試試。還有要注意的是RSA加密有一定的性能損耗。

想了解原理相關的內容可以看如下的參考內容。
[1]. RSA原理

Ⅲ JAVA 實現 RSA加解密演算法以及代碼樣例

Java中實現RSA加解密演算法的示例代碼如下:

**RSA密鑰對生成:**

java

import java.math.BigInteger;

import java.security.KeyPair;

import java.security.KeyPairGenerator;

public class RSAKeyPairGenerator {

public static void main(String[] args) throws Exception {

int keySize = 2048;

KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");

generator.initialize(keySize);

KeyPair keyPair = generator.generateKeyPair();

PrivateKey privateKey = (PrivateKey) keyPair.getPrivate();

PublicKey publicKey = keyPair.getPublic();

System.out.println("公鑰:" + publicKey);

System.out.println("私鑰:" + privateKey);

}

}

**RSA加密和解密:**

java

import java.math.BigInteger;

import javax.crypto.Cipher;

public class RSADemo {

public static void main(String[] args) throws Exception {

PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec("public_key_hex"));

String plainText = "Hello, World!";

Cipher cipher = Cipher.getInstance("RSA");

cipher.init(Cipher.ENCRYPT_MODE, publicKey);

byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());

System.out.println("加密:" + DatatypeConverter.printHexBinary(encryptedBytes));

PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec("private_key_hex"));

cipher.init(Cipher.DECRYPT_MODE, privateKey);

byte[] decryptedBytes = cipher.doFinal(encryptedBytes);

System.out.println("解密:" + new String(decryptedBytes));

}

}

以上代碼展示了如何在Java中使用RSA演算法進行密鑰對生成、加密和解密操作。

Ⅳ 關於java中rsa的問題

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

Ⅳ 我想把java文件先加密然後打包,請高手指教怎麼加密,有那種好的加密演算法嗎

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/
參考資料:http://www.lenovonet.com/proct/showarticle.asp?id=118

熱點內容
數控車床電腦編程 發布:2025-08-23 00:40:32 瀏覽:241
安卓手機如何一鍵修改序列號 發布:2025-08-23 00:31:33 瀏覽:426
vsqt編譯通過 發布:2025-08-23 00:29:58 瀏覽:458
android設置sd卡 發布:2025-08-23 00:18:47 瀏覽:861
混合存儲提供商 發布:2025-08-23 00:06:08 瀏覽:434
行鎖演算法 發布:2025-08-23 00:05:05 瀏覽:901
手機編程蘋果 發布:2025-08-23 00:02:41 瀏覽:285
腳本會被殺毒軟體 發布:2025-08-22 23:56:03 瀏覽:138
gta5車文件夾 發布:2025-08-22 23:47:58 瀏覽:182
編譯標准 發布:2025-08-22 23:45:59 瀏覽:171