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

javarsa演算法

發布時間:2022-01-13 10:22:00

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

importjavax.crypto.Cipher;
importsun.misc.BASE64Decoder;
importsun.misc.BASE64Encoder;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.io.ObjectInputStream;
importjava.io.ObjectOutputStream;
importjava.security.Key;
importjava.security.KeyPair;
importjava.security.KeyPairGenerator;
importjava.security.SecureRandom;

publicclassRSA_Encrypt{
/**指定加密演算法為DESede*/
privatestaticStringALGORITHM="RSA";
/**指定key的大小*/
privatestaticintKEYSIZE=128;
/**指定公鑰存放文件*/
privatestaticStringPUBLIC_KEY_FILE="PublicKey";
/**指定私鑰存放文件*/
privatestaticStringPRIVATE_KEY_FILE="PrivateKey";
//privatestaticStringPUBLIC_KEY_FILE="D://PublicKey.a";
//privatestaticStringPRIVATE_KEY_FILE="D://PrivateKey.a";


/**
*生成密鑰對
*/
()throwsException{
/**RSA演算法要求有一個可信任的隨機數源*/
SecureRandomsr=newSecureRandom();
/**為RSA演算法創建一個KeyPairGenerator對象*/
KeyPairGeneratorkpg=KeyPairGenerator.getInstance(ALGORITHM);
/**利用上面的隨機數據源初始化這個KeyPairGenerator對象*/
kpg.initialize(KEYSIZE,sr);
/**生成密匙對*/
KeyPairkp=kpg.generateKeyPair();
/**得到公鑰*/
KeypublicKey=kp.getPublic();
/**得到私鑰*/
KeyprivateKey=kp.getPrivate();
/**用對象流將生成的密鑰寫入文件*/
ObjectOutputStreamoos1=newObjectOutputStream(newFileOutputStream(PUBLIC_KEY_FILE));
ObjectOutputStreamoos2=newObjectOutputStream(newFileOutputStream(PRIVATE_KEY_FILE));
oos1.writeObject(publicKey);
oos2.writeObject(privateKey);
/**清空緩存,關閉文件輸出流*/
oos1.close();
oos2.close();
}
/**
*加密方法
*source:源數據
*/
publicstaticStringencrypt(Stringsource)throwsException{
generateKeyPair();
/**將文件中的公鑰對象讀出*/
ObjectInputStreamois=newObjectInputStream(newFileInputStream(PUBLIC_KEY_FILE));
Keykey=(Key)ois.readObject();
ois.close();
/**得到Cipher對象來實現對源數據的RSA加密*/
Ciphercipher=Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE,key);
byte[]b=source.getBytes();
/**執行加密操作*/
byte[]b1=cipher.doFinal(b);
BASE64Encoderencoder=newBASE64Encoder();
returnencoder.encode(b1);
}
/**
*解密演算法
*cryptograph:密文
*/
publicstaticStringdecrypt(Stringcryptograph)throwsException{
/**將文件中的私鑰對象讀出*/
ObjectInputStreamois=newObjectInputStream(newFileInputStream(PRIVATE_KEY_FILE));
Keykey=(Key)ois.readObject();
/**得到Cipher對象對已用公鑰加密的數據進行RSA解密*/
Ciphercipher=Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE,key);
BASE64Decoderdecoder=newBASE64Decoder();
byte[]b1=decoder.decodeBuffer(cryptograph);
/**執行解密操作*/
byte[]b=cipher.doFinal(b1);
returnnewString(b);
}

publicstaticvoidmain(String[]args){
try{
Stringsource="HelloWorld!";//要加密的字元串
Stringcryptograph=encrypt(source);
System.out.println(cryptograph);

Stringtarget=decrypt(cryptograph);//解密密文
System.out.println(target);
}catch(Exceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}//生成的密文
}
}

⑵ java RSA演算法

RSA演算法加密本來就是很慢的。一般對某個文件加密的話用DES演算法加密,然後對密鑰用RSA演算法加密。RSA加密慢的問題目前無法解決;

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

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

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

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

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

import javax.crypto.Cipher;

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

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

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

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

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

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

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

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

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

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

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

}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

⑺ java加密問題,RSA演算法

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

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

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

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

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

⑼ 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();
}

閱讀全文

與javarsa演算法相關的資料

熱點內容
程序員智商劃分 瀏覽:332
修煉一套好演算法 瀏覽:294
空氣凈化pdf 瀏覽:309
necc文件夾 瀏覽:16
linux跑火車 瀏覽:355
androidsdk版本兼容 瀏覽:1002
果加密碼鎖開鎖記錄 瀏覽:446
python導入模塊的形式 瀏覽:259
shor演算法 瀏覽:58
python交易日歷 瀏覽:47
怎樣用雲伺服器組網 瀏覽:294
cass垂直執行命令 瀏覽:211
安卓數據線長什麼樣子教學視頻 瀏覽:794
紅米安卓12系統怎麼升級 瀏覽:917
菜鳥裹裹加密包裹啥樣的 瀏覽:374
時差測量與無源定位演算法 瀏覽:946
學習通app如何調二倍速 瀏覽:873
中鐵四院平差軟體加密狗價格 瀏覽:732
maj命令 瀏覽:923
精品php源碼 瀏覽:960