當前位置:首頁 » 操作系統 » 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

熱點內容
dhcp伺服器如何更新ip地址 發布:2024-11-15 23:18:40 瀏覽:125
ai清除緩存 發布:2024-11-15 23:12:38 瀏覽:602
電腦版我的世界如何退出伺服器 發布:2024-11-15 23:00:39 瀏覽:312
哪裡有存儲器零售商 發布:2024-11-15 22:55:42 瀏覽:46
手機如何設置鎖屏密碼個性 發布:2024-11-15 22:44:08 瀏覽:417
mysql導入存儲過程 發布:2024-11-15 22:43:18 瀏覽:638
net連接資料庫代碼 發布:2024-11-15 22:40:16 瀏覽:61
編程計算nk 發布:2024-11-15 22:35:07 瀏覽:833
資料庫第一章 發布:2024-11-15 22:27:07 瀏覽:593
測試php性能工具 發布:2024-11-15 22:19:37 瀏覽:580