导航:首页 > 源码编译 > 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算法相关的资料

热点内容
服务器一直崩应该用什么指令 浏览:916
cm202贴片机编程 浏览:724
php构造函数带参数 浏览:175
解压电波歌曲大全 浏览:336
为啥文件夹移到桌面成word了 浏览:858
命令符的安全模式是哪个键 浏览:758
编程中学 浏览:956
单片机求助 浏览:993
ug加工侧面排铣毛坯怎么编程 浏览:271
程序员有关的介绍 浏览:736
支付宝使用的什么服务器 浏览:210
安卓看本地书用什么软件好 浏览:921
经传软件滚动净利润指标源码 浏览:522
萤石云视频已加密怎么解除 浏览:574
一命令四要求五建议 浏览:30
qq文件夹迁移不了 浏览:19
液体粘滞系数测定不确定度算法 浏览:332
轻栈源码 浏览:426
把图片压缩到500k 浏览:35
命令你自己 浏览:369