当前位置:首页 » 操作系统 » rsa算法源码

rsa算法源码

发布时间: 2022-03-01 05:46:17

❶ RSA算法的实现

RSA毕业设计论文
http://wenku..com/view/8b1804c42cc58bd63186bd77.html

❷ 求RSA算法源代码 请教大哥们

google cryptopp

❸ rsa算法实现代码

你看看这个行不行,位数可以自己改,今天在网上找到了,我也想用C生成512、1024位的大素数进行RSA加密。。如果谁有好方法麻烦共享下:[email protected],跪谢

package test;

import java.math.BigInteger;

// 生成一个随机大整数,然后找出比这个整数大的下一个素数
public class Primes {
// 下面的 BigInteger.ZERO 和 BigInteger.ONE 在 JDK 1.1 中是无效的
private static final BigInteger ZERO = BigInteger.ZERO;
private static final BigInteger ONE = BigInteger.ONE;
private static final BigInteger TWO = new BigInteger("2");

// 产生一个错误素数的概率小于 1/2 的 ERR_VAL 次方,可以将 ERR_VAL 定义为 200,降低其错误率
// Java 应该使用的是 Miller-Rabin 测试法,这种错误概率基本上可以认为是无错误。
private static final int ERR_VAL = 100;
private static StringBuffer[] digits = { new StringBuffer("0"), new StringBuffer("1"), new StringBuffer("2"), new StringBuffer("3"), new StringBuffer("4"), new StringBuffer("5"),
new StringBuffer("6"), new StringBuffer("7"), new StringBuffer("8"), new StringBuffer("9") };

private static StringBuffer randomDigit(boolean isZeroOK) {
// 产生一个随机的数字(字符串形式的),isZeroOK 决定这个数字是否可以为 0
int index;
if (isZeroOK)
index = (int) Math.floor(Math.random() * 10);
else
index = 1 + (int) Math.floor(Math.random() * 9);
return (digits[index]);
}

public static BigInteger bigRandom(int numDigits) {
// 产生一个随机大整数,各位上的数字都是随机产生的,首位不为 0
StringBuffer s = new StringBuffer("");
for (int i = 0; i < numDigits; i++)
if (i == 0)
s.append(randomDigit(false));
else
s.append(randomDigit(true));
return (new BigInteger(s.toString()));
}

private static boolean isEven(BigInteger n) {
// 测试一个大整数是否为偶数
return (n.mod(TWO).equals(ZERO));
}

public static BigInteger nextPrime(BigInteger start) {
// 产生一个比给定大整数 start 大的素数,错误率低于 1/2 的 ERR_VAL 次方
if (isEven(start))
start = start.add(ONE);
else
start = start.add(TWO);
if (start.isProbablePrime(ERR_VAL))
return (start);
else
// 采用递归方式(递归的层数会是个天文数字吗?)
return (nextPrime(start));
}

// 一个基于命令行的测试程序,如果位数错误,默认 150 位,输出 20 个素数
public static void main(String[] args) {
int numDigits;
try {
numDigits = Integer.parseInt(args[0]);
} catch (Exception e) {
numDigits = 128;
}
BigInteger start = bigRandom(numDigits);

start = nextPrime(start);
BigInteger end = bigRandom(5);
end = nextPrime(end);
System.out.println("大素数" + start);
System.out.println("大素数" + end);
BigInteger result = start.multiply(end);
System.out.println("结果数" + result);

❹ rsa算法c语言实现

程序修改如下: (主要是你的循环写的不对,输入的字符应该-'0'才能与正常的数字对应)
#include<stdio.h>
#include<math.h>
int candp(int a,int b,int c)
{int r=1;
int s;
int i=1;
for(i=1;i<=b;i++)r=r*a;

printf("%d\n",r);
s=r%c;
printf("%d\n",s);
return s;}
void main()
{
int p,q,e,d,m,n,t,c,r
;
char s;
printf("please input the p,q:");
scanf("%d%d",&p,&q);
n=p*q;
t=(p-1)*(q-1);
printf("the n is %12d\n",n);
printf("please input the e:");
scanf("%d",&e);
while(e<1||e>n) //此处修改为while循环
{
printf("e is error,please input again:");
scanf("%d",&e);

}
d=1;
while(((e*d)%t)!=1) d++;
printf("then caculate out that the d is %d\n",d);
printf("the cipher please input 1\n");
printf("the plain please input 2\n");
scanf("%c",&s);
while((s-'0')!=1&&(s-'0')!=2) //消除后面的getchar() 此处增加while循环注意括号内的字符
{scanf("%c",&s);}
switch(s-'0')
{
case 1:printf("intput the m:");
scanf("%d",&m);
c=candp(m,e,n);
printf("the plain is %d\n",c);break;
case 2:printf("input the c:");
scanf("%d",&c);
m=candp(c,d,n);
printf("the cipher is %8d\n",m); break;

}
}

❺ 本人急需C语言实现RSA算法的源程序

****************************
第一问输出d,e,r,我写出来了。
后面的加密,解密不难,但是我不知道怎么求那么大的幂次然后再求余,所以没写,函数原型我写出来了,你可以自己填上,如果你有什么好想法的话,请给我在网络上发消息,谢谢。输出的d,e,r我用验证过了,是正确的
下面是输出效果
***************************************
E:\编程\C\知道\RSA\debug>rsa
Invaild Parameters!
Usage:
RSA -e Express e r
RSA -d Ciphertext d r
RSA Prime1 Prime2

E:\编程\C\知道\RSA\debug>rsa 23 12
Invaild Parameters
should be PRIME!
Usage: RSA Prime1 Prime2

E:\编程\C\知道\RSA\debug>rsa 19 23
d=115 e=31 r=437
***************************************

#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>
#include <math.h>

int str2num(char *str) //字符转数字
{
int i=0,num=0;

for(i=0;i<(int)strlen(str);i++)
num=num*10+str[i]-'0';
return num;

}

float CarmSqrt(float x) //求平方根 系统的太慢,用了别人的
{
union
{
int intPart;
float floatPart;
}convertor;

union
{
int intPart;
float floatPart;
}convertor2;

convertor.floatPart = x;
convertor2.floatPart = x;
convertor.intPart = 0x1FBCF800 + (convertor.intPart >> 1);
convertor2.intPart = 0x5f3759df - (convertor2.intPart >> 1);
return 0.5f*(convertor.floatPart + (x * convertor2.floatPart));
}//可以不用,用sqrt()也可以

int isPrime(int n) //判断是否为素数
{
int i=0,k=2;

k=(int)CarmSqrt(n);
for(i=2;i<=k;i++)
{
if(n%i==0)
break;
}

if(i>k)
return 1;
else
return 0;

}

int rnd(int max) //生成随机数 2~max 用来生成e,
{ //取系统时间做随机数种子
int range,n;
int min=2,flag=0;
time_t t;
double j;

range=max-min;
t=time(NULL);
srand((unsigned)t);

n=rand();

j=((double)n/(double)RAND_MAX);

n=(int)(j*(double)range);
n+=min;

return n;

}

int co_prime(int a ,int b) // 求互质
{
int c;
do
{
if(b==1)
return 1;
c=a%b;
a=b;
b=c;

}while(c!=0);
return 0;
}

void get_d_e(int p,int q)
{
int r,t,e,d,i=2,k=0;

if(isPrime(p)!=1||isPrime(q)!=1)
{
printf("Invaild Parameters\nshould be PRIME!\n");
printf("Usage:RSA Prime1 Prime2\n");
exit(0);
}

r=p*q;

t=(p-1)*(q-1);
e=rnd(t)/10;
while(co_prime(t,e)!=1)
{
e=e+1;

}

for(d=2;d<t;d++)
{
if((e*d)%t==1)
break;
}

printf("d=%d e=%d r=%d\n",d,e,r);
}

void en(int n,int e,int r)
{
//加密
}

void de(int c,int d,int r)
{
//解密
}

void main(int argc,char* argv[])
{
int n1,n2;

if(argc!=3&&argc!=5)
{
printf("Invaild Parameters!\n");
printf("Usage: \nRSA -e Express e r\n");
printf("RSA -d Ciphertext d r\n");
printf("RSA Prime1 Prime2\n");//错误输出
exit(0);
}
else

if(argv[1][0]!='-')
{
n1=str2num(argv[1]);
n2=str2num(argv[2]);
get_d_e(n1,n2);
exit(0);
}

else
if(argv[1][1]=='e') //加密
{
n1=str2num(argv[3]);
n2=str2num(argv[4]);
en(str2num(argv[2]),n1,n2);
exit(0);

}

if(argv[1][1]=='d') //解密
{
n1=str2num(argv[3]);
n2=str2num(argv[4]);
en(str2num(argv[2]),n1,n2);
exit(0);

}

else{
printf("Invaild Parameters!\n");
printf("Usage: \nRSA -e Express e r\n");
printf("RSA -d Ciphertext d r\n");
printf("RSA Prime1 Prime2\n");
exit(0);
}
}

❻ 求RSA算法用VERILOG语言实现的代码

找毕设杀手吧,很厉害的.qq:781185763

❼ 求RSA算法的源代码(c语言)

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MM 7081
#define KK 1789
#define PHIM 6912
#define PP 85
typedef char strtype[10000];
int len;
long nume[10000];
int change[126];
char antichange[37];

void initialize()
{ int i;
char c;
for (i = 11, c = 'A'; c <= 'Z'; c ++, i ++)
{ change[c] = i;
antichange[i] = c;
}
}
void changetonum(strtype str)
{ int l = strlen(str), i;
len = 0;
memset(nume, 0, sizeof(nume));
for (i = 0; i < l; i ++)
{ nume[len] = nume[len] * 100 + change[str[i]];
if (i % 2 == 1) len ++;
}
if (i % 2 != 0) len ++;
}
long binamod(long numb, long k)
{ if (k == 0) return 1;
long curr = binamod (numb, k / 2);
if (k % 2 == 0)
return curr * curr % MM;
else return (curr * curr) % MM * numb % MM;
}
long encode(long numb)
{ return binamod(numb, KK);
}
long decode(long numb)
{ return binamod(numb, PP);
}
main()
{ strtype str;
int i, a1, a2;
long curr;
initialize();
puts("Input 'Y' if encoding, otherwise input 'N':");
gets(str);
if (str[0] == 'Y')
{ gets(str);
changetonum(str);
printf("encoded: ");
for (i = 0; i < len; i ++)
{ if (i) putchar('-');
printf(" %ld ", encode(nume[i]));
}
putchar('\n');
}
else
{ scanf("%d", &len);
for (i = 0; i < len; i ++)
{ scanf("%ld", &curr);
curr = decode(curr);
a1 = curr / 100;
a2 = curr % 100;
printf("decoded: ");
if (a1 != 0) putchar(antichange[a1]);
if (a2 != 0) putchar(antichange[a2]);
}
putchar('\n');
}
putchar('\n');
system("PAUSE");
return 0;
}
测试:
输入:
Y
FERMAT
输出:
encoded: 5192 - 2604 - 4222
输入
N
3 5192 2604 4222
输出
decoded: FERMAT

❽ RSA算法C语言源代码有哪位大哥大姐有啊,小妹我先谢过了!!!!!!!

string ls_str
string sn = ""
ulong lul_temp
ulong lul_x
ulong lul_x0
ulong lul_x1
integer i
integer li_d
integer li_n

li_d = 7
li_n = 33
ls_str = trim(id) //id 为序列号

do until ls_str = ""

if left(ls_str,1) = "2" then
lul_temp = integer(mid(ls_str,2,2))
ls_str = right(ls_str,len(ls_str) - 3)
else
lul_temp = integer(mid(ls_str,2,1))
ls_str = right(ls_str,len(ls_str) - 2)
end if

lul_x0 = 1
lul_x1 = 1

for i = 1 to 4
lul_x0 = lul_x0 * lul_temp
next

lul_x0 = mod(lul_x0,33)

for i = 1 to li_d - 4
lul_x1 = lul_x1 * lul_temp
next

lul_x1 = mod(lul_x1,33)
lul_x = mod(lul_x0 * lul_x1,33)
sn = trim(sn) + string(lul_x)
loop

❾ 求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

热点内容
循迹小车算法 发布:2024-12-22 22:28:41 浏览:82
scss一次编译一直生成随机数 发布:2024-12-22 22:04:24 浏览:956
嫁接睫毛加密 发布:2024-12-22 21:50:12 浏览:975
linuxbin文件的安装 发布:2024-12-22 21:46:07 浏览:798
vlcforandroid下载 发布:2024-12-22 21:45:26 浏览:664
电脑做网关把数据发送至服务器 发布:2024-12-22 21:44:50 浏览:432
新华三代理什么牌子的服务器 发布:2024-12-22 21:33:21 浏览:342
欢太会员密码是什么 发布:2024-12-22 20:57:28 浏览:74
sqllocaldb 发布:2024-12-22 20:07:08 浏览:126
如何找到我的服务器 发布:2024-12-22 19:52:14 浏览:301