當前位置:首頁 » 操作系統 » rsa解密源碼

rsa解密源碼

發布時間: 2022-07-24 08:58:57

⑴ 求RSA演算法的源代碼(c語言

這個是我幫個朋友寫的,寫的時候發現其實這個沒那麼復雜,不過,時間復雜度要高於那些成型了的,為人所熟知的rsa演算法的其他語言實現.
#include
int
candp(int
a,int
b,int
c)
{
int
r=1;
b=b+1;
while(b!=1)
{
r=r*a;
r=r%c;
b--;
}
printf("%d",r);
return
r;
}
void
main()
{
int
p,q,e,d,m,n,t,c,r;
char
s;
{printf("input
the
p:\n");
scanf("%d\n",&p);
printf("input
the
q:\n");
scanf("%d%d\n",&p);
n=p*q;
printf("so,the
n
is
%3d\n",n);
t=(p-1)*(q-1);
printf("so,the
t
is
%3d\n",t);
printf("please
intput
the
e:\n");
scanf("%d",&e);
if(e<1||e>t)
{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
%5d",d);
printf("if
you
want
to
konw
the
cipher
please
input
1;\n
if
you
want
to
konw
the
plain
please
input
2;\n");
scanf("%d",&r);
if(r==1)
{
printf("input
the
m
:"
);/*輸入要加密的明文數字*/
scanf("%d\n",&m);
c=candp(m,e,n);
printf("so
,the
cipher
is
%4d",c);}
if(r==2)
{
printf("input
the
c
:"
);/*輸入要解密的密文數字*/
scanf("%d\n",&c);
m=candp(c,d,n);
printf("so
,the
cipher
is
%4d\n",m);
printf("do
you
want
to
use
this
programe:yes
or
no");
scanf("%s",&s);
}while(s=='y');
}
}

⑵ 求RSA加密解密演算法,c++源代碼

#include<iostream.h>
#include<stdio.h>
#include<math.h>
int pf_c(int m,int k);
int pf(int m1,int n1);
int gcd(int f);
int r;
int h;
void main()
{ int a,b,c,d,d1,a1,b1,c1;
cout<<"請輸入你選擇的2個大素數!"<<endl;
cin>>a1;
cin>>b1;
r=a1*b1;
c=(a1-1)*(b1-1);
c1=gcd(c);
cout<<"公開鑰為:"<<c1<<endl;
cout<<"請選擇你要的操作:1.加密 2.解密"<<endl;
cin>>a;
switch(a){
case 1: cout<<"請輸入明文:"<<endl;
cin>>b;
cout<<"密文為:"<<pf_c(b,c1)<<endl;
break;
case 2: cout<<"請輸入密文:"<<endl;
cin>>d;
d1=pf(c,c1);
cout<<"私密鑰為:"<<d1<<endl;
cout<<"明文為:"<<pf_c(d,d1)<<endl;
break;
}
getchar();
}
int pf_c(int m,int k)
{
int a,i1,a1,b[50],c1,c;
c=0;c1=1;i1=0;
do{
a=k/2;
a1=k%2;
b[i1]=a1;
k=a;
i1++;
}while(a>0);
i1--;
for(int i=i1;i>=0;i--)
{
c=2*c;
c1=(c1*c1)%r;
if(b[i]==1)
{
c=c+1;
c1=(c1*m)%r;
}
}
return c1;
}
int pf(int m1,int n1)
{
int x1=1,x2=0,x3;
int y1=0,y2=1,y3;
x3=m1;
y3=n1;
int d;
for(int i=0; ;i++)
{
int q=x3/y3;
int t1=x1-q*y1;
int t2=x2-q*y2;
int t3=x3-q*y3;
x1=y1;
x2=y2;
x3=y3;
y1=t1;
y2=t2;
y3=t3;
if(y3==1)
{
if(y2<0) d=m1+y2;
else d=y2;
break;
}
}
return d;
}
int gcd(int f)
{
int x1=1,x2=0,x3;
int y1=0,y2=1,y3;
for(int i1=2;i1<f;i1++)
{
x3=f;
y3=i1;
int q=x3/y3;
int t1=x1-q*y1;
int t2=x2-q*y2;
int t3=x3-q*y3;
x1=y1;
x2=y2;
x3=y3;
y1=t1;
y2=t2;
y3=t3;
if(y3==1)
{
return i1;
break;
}
}
}

⑶ 如何利用OpenSSL庫進行RSA加密和解密

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<openssl/rsa.h>
#include<openssl/engine.h>

intmain(intargc,char*argv[])
{
printf("openssl_testbegin ");
RSA*rsa=NULL;
charoriginstr[]="hello ";//這是我們需要加密的原始數據
//allocateRSAstructure,首先需要申請一個RSA結構題用於存放生成的公私鑰,這里rsa就是這個結構體的指針
rsa=RSA_new();
if(rsa==NULL)
{
printf("RSA_newfailed ");
return-1;
}

//generateRSAkeys
BIGNUM*exponent;
exponent=BN_new();//生成RSA公私鑰之前需要選擇一個奇數(oddnumber)來用於生成公私鑰
if(exponent==NULL)
{
printf("BN_newfailed ");
gotoFAIL1;
}
if(0==BN_set_word(exponent,65537))//這里選擇奇數65537
{
printf("BN_set_wordfailed ");
gotoFAIL1;
}


//這里molus的長度選擇4096,小於1024的molus長度都是不安全的,容易被破解
if(0==RSA_generate_key_ex(rsa,4096,exponent,NULL))
{
printf("RSA_generate_key_exfailed ");
gotoFAIL;
}
char*cipherstr=NULL;
//分配一段空間用於存儲加密後的數據,這個空間的大小由RSA_size函數根據rsa算出
cipherstr=malloc(RSA_size(rsa));
if(cipherstr==NULL)
{
printf("malloccipherstrbuffailed ");
gotoFAIL1;
}
//下面是實際的加密過程,最後一個參數paddingtype,有以下幾種。
/*
RSA_PKCS1_PADDINGPKCS#1v1.5padding..
RSA_PKCS1_OAEP_PADDING
EME-OAEPasdefinedinPKCS#1v2.0withSHA-1,..
RSA_SSLV23_PADDING
PKCS#1v1.5paddingwithanSSL-.
RSA_NO_PADDING
RawRSAencryption.ntheapplicationcode..
*/
//這里首先用公鑰進行加密,選擇了RSA_PKCS1_PADDING

if(RSA_size(rsa)!=RSA_public_encrypt(strlen(originstr)+1,originstr,cipherstr,rsa,RSA_PKCS1_PADDING))
{
printf("encryptionfailure ");
gotoFAIL2;
}
printf("theoriginalstringis%s ",originstr);
printf("theencryptedstringis%s ",cipherstr);


//Now,let'
//下面來用私鑰解密,首先需要一個buffer用於存儲解密後的數據,這個buffer的長度要足夠(小於RSA_size(rsa))
//這里分配一個長度為250的字元數組,應該是夠用的。
chardecrypted_str[250];
intdecrypted_len;
if(-1=(decrypted_len=RSA_private_decrypt(256,cipherstr,decrypted_str,rsa,RSA_PKCS1_PADDING)))
{
printf("decryptionfailure ");
gotoFAIL2;
}
printf("decryptedstringlengthis%d,decryped_stris%s ",decrypted_len,decrypted_str);
FAIL2:
free(cipherstr);
FAIL1:
BN_free(exponent);
FAIL:
RSA_free(rsa);
return0;
}

以上是源代碼,下面使用下面的編譯命令在源碼所在路徑下生成可執行文件
gcc *.c -o openssl_test -lcrypto -ldl -L/usr/local/ssl/lib -I/usr/local/ssl/include
其中,-lcrypto和-ldl是必須的,前者是OpenSSL中的加密演算法庫,後者是用於成功載入動態庫。

⑷ 用c#實現Rsa加密和解密

using System;
using System.Security.Cryptography;
using System.IO;
using System.Text;

namespace Microsoft.Samples.Security.PublicKey
{
class App
{
// Main entry point
static void Main(string[] args)
{
// Instantiate 3 People for example. See the Person class below
Person alice = new Person("Alice");
Person bob = new Person("Bob");
Person steve = new Person("Steve");

// Messages that will exchanged. See CipherMessage class below
CipherMessage aliceMessage;
CipherMessage bobMessage;
CipherMessage steveMessage;

// Example of encrypting/decrypting your own message
Console.WriteLine("Encrypting/Decrypting Your Own Message");
Console.WriteLine("-----------------------------------------");

// Alice encrypts a message using her own public key
aliceMessage = alice.EncryptMessage("Alice wrote this message");
// then using her private key can decrypt the message
alice.DecryptMessage(aliceMessage);
// Example of Exchanging Keys and Messages
Console.WriteLine();
Console.WriteLine("Exchanging Keys and Messages");
Console.WriteLine("-----------------------------------------");

// Alice Sends a of her public key to Bob and Steve
bob.GetPublicKey(alice);
steve.GetPublicKey(alice);

// Bob and Steve both encrypt messages to send to Alice
bobMessage = bob.EncryptMessage("Hi Alice! - Bob.");
steveMessage = steve.EncryptMessage("How are you? - Steve");

// Alice can decrypt and read both messages
alice.DecryptMessage(bobMessage);
alice.DecryptMessage(steveMessage);

Console.WriteLine();
Console.WriteLine("Private Key required to read the messages");
Console.WriteLine("-----------------------------------------");

// Steve cannot read the message that Bob encrypted
steve.DecryptMessage(bobMessage);
// Not even Bob can use the Message he encrypted for Alice.
// The RSA private key is required to decrypt the RS2 key used
// in the decryption.
bob.DecryptMessage(bobMessage);

} // method Main
} // class App

class CipherMessage
{
public byte[] cipherBytes; // RC2 encrypted message text
public byte[] rc2Key; // RSA encrypted rc2 key
public byte[] rc2IV; // RC2 initialization vector
}

class Person
{
private RSACryptoServiceProvider rsa;
private RC2CryptoServiceProvider rc2;
private string name;

// Maximum key size for the RC2 algorithm
const int keySize = 128;

// Person constructor
public Person(string p_Name)
{
rsa = new RSACryptoServiceProvider();
rc2 = new RC2CryptoServiceProvider();
rc2.KeySize = keySize;
name = p_Name;
}

// Used to send the rsa public key parameters
public RSAParameters SendPublicKey()
{
RSAParameters result = new RSAParameters();
try
{
result = rsa.ExportParameters(false);
}
catch (CryptographicException e)
{
Console.WriteLine(e.Message);
}
return result;
}

// Used to import the rsa public key parameters
public void GetPublicKey(Person receiver)
{
try
{
rsa.ImportParameters(receiver.SendPublicKey());
}
catch (CryptographicException e)
{
Console.WriteLine(e.Message);
}
}

public CipherMessage EncryptMessage(string text)
{
// Convert string to a byte array
CipherMessage message = new CipherMessage();
byte[] plainBytes = Encoding.Unicode.GetBytes(text.ToCharArray());

// A new key and iv are generated for every message
rc2.GenerateKey();
rc2.GenerateIV();

// The rc2 initialization doesnt need to be encrypted, but will
// be used in conjunction with the key to decrypt the message.
message.rc2IV = rc2.IV;
try
{
// Encrypt the RC2 key using RSA encryption
message.rc2Key = rsa.Encrypt(rc2.Key, false);
}
catch (CryptographicException e)
{
// The High Encryption Pack is required to run this sample
// because we are using a 128-bit key. See the readme for
// additional information.
Console.WriteLine("Encryption Failed. Ensure that the" +
" High Encryption Pack is installed.");
Console.WriteLine("Error Message: " + e.Message);
Environment.Exit(0);
}
// Encrypt the Text Message using RC2 (Symmetric algorithm)
ICryptoTransform sse = rc2.CreateEncryptor();
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, sse, CryptoStreamMode.Write);
try
{
cs.Write(plainBytes, 0, plainBytes.Length);
cs.FlushFinalBlock();
message.cipherBytes = ms.ToArray();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
ms.Close();
cs.Close();
}
return message;
} // method EncryptMessage

public void DecryptMessage(CipherMessage message)
{
// Get the RC2 Key and Initialization Vector
rc2.IV = message.rc2IV;
try
{
// Try decrypting the rc2 key
rc2.Key = rsa.Decrypt(message.rc2Key, false);
}
catch (CryptographicException e)
{
Console.WriteLine("Decryption Failed: " + e.Message);
return;
}

ICryptoTransform ssd = rc2.CreateDecryptor();
// Put the encrypted message in a memorystream
MemoryStream ms = new MemoryStream(message.cipherBytes);
// the CryptoStream will read cipher text from the MemoryStream
CryptoStream cs = new CryptoStream(ms, ssd, CryptoStreamMode.Read);
byte[] initialText = new Byte[message.cipherBytes.Length];

try
{
// Decrypt the message and store in byte array
cs.Read(initialText, 0, initialText.Length);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
ms.Close();
cs.Close();
}

// Display the message received
Console.WriteLine(name + " received the following message:");
Console.WriteLine(" " + Encoding.Unicode.GetString(initialText));
} // method DecryptMessage
} // class Person
} // namespace PublicKey

⑸ rsa解密演算法

我剛剛復習完關於rsa的演算法知識,告訴你吧:
RSA公鑰密碼系統:
1.密鑰對的產生:隨機產生兩個大的素數:p,q 計算n=p×q
2.隨機產生加密密鑰e:選擇一個隨機的e使Gcd(e,(p-1)*(q-1))= 1就是選擇一個隨機的e,使e和 (p-1)*(q-1)互素。通常e也選擇成素數。
這樣,公鑰對(n,e)就產生了
3.計算解密密鑰d:計算一個數d 條件是使得e*d mod (p-1)*(q-1)=1,其中n與d也要互素。
這樣就產生了私鑰對(n,d)

發送者給持有密鑰(n,d)的人發送某數M
發送密文C=M^e mod n

接受者利用私鑰解密M=C^d mod n

計算模指數當然需要特殊的演算法啦,要不然計算機也沒辦法算啊:演算法如下:
#include <iostream>
#include <cmath>
using namespace std;

int exp_mod(int a,int n,int z)
{
int exp = 1;
int x = a % z;
while (n>0)
{
if(n%2==1)
exp = (exp * x) % z;
x = (x * x) % z;
n = n/2;
}
return exp;

}

int main()
{
int a,n,z;
cout<< "請輸入底數: ";
cin>>a;
cout<< "請輸入指數: ";
cin>>n;
cout<< "請輸入被模數: ";
cin>>z;
int result = exp_mod(a,n,z);

cout<< "結果是:"<<result<<endl;
cout<<"普通演算法結果"<<long(pow(a,n))%z <<endl;/*double pow(int
x,int y)求x的y次方*/

return 0;
}
這個是算A^B mod C 的C++源碼。

希望對你有幫助,好的話別忘了加分啊!

⑹ 求正確的RSA加密解密演算法C語言的,多謝。

RSA演算法它是第一個既能用於數據加密也能用於數字簽名的演算法。它易於理解和操作,也很流行。演算法的名字以發明者的名字命名:RonRivest,AdiShamir和LeonardAdleman。但RSA的安全性一直未能得到理論上的證明。它經歷了各種攻擊,至今未被完全攻破。一、RSA演算法:首先,找出三個數,p,q,r,其中p,q是兩個相異的質數,r是與(p-1)(q-1)互質的數p,q,r這三個數便是privatekey接著,找出m,使得rm==1mod(p-1)(q-1)這個m一定存在,因為r與(p-1)(q-1)互質,用輾轉相除法就可以得到了再來,計算n=pqm,n這兩個數便是publickey編碼過程是,若資料為a,將其看成是一個大整數,假設a=n的話,就將a表成s進位(s因為rm==1mod(p-1)(q-1),所以rm=k(p-1)(q-1)+1,其中k是整數因為在molo中是preserve乘法的(x==ymodzan==vmodz=>xu==yvmodz),所以,c==b^r==(a^m)^r==a^(rm)==a^(k(p-1)(q-1)+1)modpq1.如果a不是p的倍數,也不是q的倍數時,則a^(p-1)==1modp(費馬小定理)=>a^(k(p-1)(q-1))==1modpa^(q-1)==1modq(費馬小定理)=>a^(k(p-1)(q-1))==1modq所以p,q均能整除a^(k(p-1)(q-1))-1=>pq|a^(k(p-1)(q-1))-1即a^(k(p-1)(q-1))==1modpq=>c==a^(k(p-1)(q-1)+1)==amodpq2.如果a是p的倍數,但不是q的倍數時,則a^(q-1)==1modq(費馬小定理)=>a^(k(p-1)(q-1))==1modq=>c==a^(k(p-1)(q-1)+1)==amodq=>q|c-a因p|a=>c==a^(k(p-1)(q-1)+1)==0modp=>p|c-a所以,pq|c-a=>c==amodpq3.如果a是q的倍數,但不是p的倍數時,證明同上4.如果a同時是p和q的倍數時,則pq|a=>c==a^(k(p-1)(q-1)+1)==0modpq=>pq|c-a=>c==amodpqQ.E.D.這個定理說明a經過編碼為b再經過解碼為c時,a==cmodn(n=pq)但我們在做編碼解碼時,限制0intcandp(inta,intb,intc){intr=1;b=b+1;while(b!=1){r=r*a;r=r%c;b--;}printf("%d\n",r);returnr;}voidmain(){intp,q,e,d,m,n,t,c,r;chars;printf("pleaseinputthep,q:");scanf("%d%d",&p,&q);n=p*q;printf("thenis%3d\n",n);t=(p-1)*(q-1);printf("thetis%3d\n",t);printf("pleaseinputthee:");scanf("%d",&e);if(et){printf("eiserror,pleaseinputagain:");scanf("%d",&e);}d=1;while(((e*d)%t)!=1)d++;printf("thencaculateoutthatthedis%d\n",d);printf("thecipherpleaseinput1\n");printf("theplainpleaseinput2\n");scanf("%d",&r);switch(r){case1:printf("inputthem:");/*輸入要加密的明文數字*/scanf("%d",&m);c=candp(m,e,n);printf("thecipheris%d\n",c);break;case2:printf("inputthec:");/*輸入要解密的密文數字*/scanf("%d",&c);m=candp(c,d,n);printf("thecipheris%d\n",m);break;}getch();}

⑺ 求一個實現RSA加解密的程序源碼 匯編 JAVA C 都可以

首先你要了解rsa演算法和會用c語言
然後到網上搜索大數運算庫
因為rsa得大數運算分解要用到它
首先你要了解rsa演算法和會用c語言
然後到網上搜索大數運算庫

⑻ 求RSA 的C++源代碼 !謝謝!

請注意保存,以防失效,如果幫到你,請採納

⑼ 求RSA加解密系統的C++代碼

//下面程序由520huiqin編寫,已在VC++ 6.0下編譯通過

#include <iostream.h>
#include <math.h>
#include <stdio.h>

typedef int Elemtype;
Elemtype p,q,e;
Elemtype fn;
Elemtype m,c;
int flag = 0;
typedef void (*Msghandler) (void);
struct MsgMap {
char ch;
Msghandler handler;
};
/* 公鑰 */
struct PU {
Elemtype e;
Elemtype n;
} pu;
/* 私鑰 */
struct PR {
Elemtype d;
Elemtype n;
} pr;
/* 判定一個數是否為素數 */
bool test_prime(Elemtype m) {
if (m <= 1) {
return false;
}
else if (m == 2) {
return true;
}
else {
for(int i=2; i<=sqrt(m); i++) {
if((m % i) == 0) {
return false;
break;
}
}
return true;
}
}
/* 將十進制數據轉化為二進制數組 */
void switch_to_bit(Elemtype b, Elemtype bin[32]) {
int n = 0;
while( b > 0) {
bin[n] = b % 2;
n++;
b /= 2;
}
}
/* 候選菜單,主界面 */
void Init() {
cout<<"*********************************************"<<endl;
cout<<"*** Welcome to use RSA encoder ***"<<endl;
cout<<"*** a.about ***"<<endl;
cout<<"*** e.encrypt ***"<<endl;
cout<<"*** d.decrypt ***"<<endl;
cout<<"*** s.setkey ***"<<endl;
cout<<"*** q.quit ***"<<endl;
cout<<"**********************************by*Terry***"<<endl;
cout<<"press a key:"<<endl;
}
/* 將兩個數排序,大的在前面*/
void order(Elemtype &in1, Elemtype &in2) {
Elemtype a = ( in1 > in2 ? in1 : in2);
Elemtype b = ( in1 < in2 ? in1 : in2);
in1 = a;
in2 = b;
}
/* 求最大公約數 */
Elemtype gcd(Elemtype a, Elemtype b) {
order(a,b);
int r;
if(b == 0) {
return a;
}
else {
while(true) {
r = a % b;
a = b;
b = r;
if (b == 0) {
return a;
break;
}
}
}

}
/* 用擴展的歐幾里得演算法求乘法逆元 */
Elemtype extend_euclid(Elemtype m, Elemtype bin) {
order(m,bin);
Elemtype a[3],b[3],t[3];
a[0] = 1, a[1] = 0, a[2] = m;
b[0] = 0, b[1] = 1, b[2] = bin;
if (b[2] == 0) {
return a[2] = gcd(m, bin);
}
if (b[2] ==1) {
return b[2] = gcd(m, bin);
}
while(true) {
if (b[2] ==1) {
return b[1];
break;
}
int q = a[2] / b[2];
for(int i=0; i<3; i++) {
t[i] = a[i] - q * b[i];
a[i] = b[i];
b[i] = t[i];
}
}
}
/* 快速模冪演算法 */
Elemtype molar_multiplication(Elemtype a, Elemtype b, Elemtype n) {
Elemtype f = 1;
Elemtype bin[32];
switch_to_bit(b,bin);
for(int i=31; i>=0; i--) {
f = (f * f) % n;
if(bin[i] == 1) {
f = (f * a) % n;
}
}
return f;
}
/* 產生密鑰 */
void proce_key() {
cout<<"input two primes p and q:";
cin>>p>>q;
while (!(test_prime(p)&&test_prime(q))){
cout<<"wrong input,please make sure two number are both primes!"<<endl;
cout<<"input two primes p and q:";
cin>>p>>q;
};
pr.n = p * q;
pu.n = p * q;
fn = (p - 1) * (q - 1);
cout<<"fn = "<<fn<<endl;
cout<<"input e :";
cin>>e;
while((gcd(fn,e)!=1)) {
cout<<"e is error,try again!";
cout<<"input e :";
cin>>e;
}
pr.d = (extend_euclid(fn,e) + fn) % fn;
pu.e = e;
flag = 1;
cout<<"PR.d: "<<pr.d<<" PR.n: "<<pr.n<<endl;
cout<<"PU.e: "<<pu.e<<" PU.n: "<<pu.n<<endl;
}
/* 加密 */
void encrypt() {
if(flag == 0) {
cout<<"setkey first:"<<endl;
proce_key();
}
cout<<"input m:";
cin>>m;
c = molar_multiplication(m,pu.e,pu.n);
cout<<"c is:"<<c<<endl;
}
/* 解密 */
void decrypt() {
if(flag == 0) {
cout<<"setkey first:"<<endl;
proce_key();
}
cout<<"input c:";
cin>>c;
m = molar_multiplication(c,pr.d,pr.n);
cout<<"m is:"<<m<<endl;
}
/* 版權信息 */
void about() {
cout<<"*********************************************"<<endl;
cout<<"*** by Terry ***"<<endl;
cout<<"*** right 2010,All rights reserved by ***"<<endl;
cout<<"*** Terry,technology supported by weizuo !***"<<endl;
cout<<"*** If you have any question, please mail ***"<<endl;
cout<<"*** to [email protected] ! ***"<<endl;
cout<<"*** Computer of science and engineering ***"<<endl;
cout<<"*** XiDian University 2010-4-29 ***"<<endl;
cout<<"*********************************************"<<endl;
cout<<endl<<endl;
Init();
}
/* 消息映射 */
MsgMap Messagemap[] = {
{'a',about},
{'s',proce_key},
{'d',decrypt},
{'e',encrypt},
{'q',NULL}
};
/* 主函數,提供循環 */
void main() {
Init();
char d;
while((d = getchar())!='q') {
int i = 0;
while(Messagemap[i].ch) {
if(Messagemap[i].ch == d) {
Messagemap[i].handler();
break;
}
i++;
}
}
}

⑽ C# Rsa加密解密

網上給出的rsa加密的源碼,希望可以幫到你:
using System;
using System.Security.Cryptography;
using System.IO;
using System.Text;

namespace Microsoft.Samples.Security.PublicKey
{
class App
{
// Main entry point
static void Main(string[] args)
{
// Instantiate 3 People for example. See the Person class below
Person alice = new Person("Alice");
Person bob = new Person("Bob");
Person steve = new Person("Steve");

// Messages that will exchanged. See CipherMessage class below
CipherMessage aliceMessage;
CipherMessage bobMessage;
CipherMessage steveMessage;

// Example of encrypting/decrypting your own message
Console.WriteLine("Encrypting/Decrypting Your Own Message");
Console.WriteLine("-----------------------------------------");

// Alice encrypts a message using her own public key
aliceMessage = alice.EncryptMessage("Alice wrote this message");
// then using her private key can decrypt the message
alice.DecryptMessage(aliceMessage);
// Example of Exchanging Keys and Messages
Console.WriteLine();
Console.WriteLine("Exchanging Keys and Messages");
Console.WriteLine("-----------------------------------------");

// Alice Sends a of her public key to Bob and Steve
bob.GetPublicKey(alice);
steve.GetPublicKey(alice);

// Bob and Steve both encrypt messages to send to Alice
bobMessage = bob.EncryptMessage("Hi Alice! - Bob.");
steveMessage = steve.EncryptMessage("How are you? - Steve");

// Alice can decrypt and read both messages
alice.DecryptMessage(bobMessage);
alice.DecryptMessage(steveMessage);

Console.WriteLine();
Console.WriteLine("Private Key required to read the messages");
Console.WriteLine("-----------------------------------------");

// Steve cannot read the message that Bob encrypted
steve.DecryptMessage(bobMessage);
// Not even Bob can use the Message he encrypted for Alice.
// The RSA private key is required to decrypt the RS2 key used
// in the decryption.
bob.DecryptMessage(bobMessage);

} // method Main
} // class App

class CipherMessage
{
public byte[] cipherBytes; // RC2 encrypted message text
public byte[] rc2Key; // RSA encrypted rc2 key
public byte[] rc2IV; // RC2 initialization vector
}

class Person
{
private RSACryptoServiceProvider rsa;
private RC2CryptoServiceProvider rc2;
private string name;

// Maximum key size for the RC2 algorithm
const int keySize = 128;

// Person constructor
public Person(string p_Name)
{
rsa = new RSACryptoServiceProvider();
rc2 = new RC2CryptoServiceProvider();
rc2.KeySize = keySize;
name = p_Name;
}

// Used to send the rsa public key parameters
public RSAParameters SendPublicKey()
{
RSAParameters result = new RSAParameters();
try
{
result = rsa.ExportParameters(false);
}
catch (CryptographicException e)
{
Console.WriteLine(e.Message);
}
return result;
}

// Used to import the rsa public key parameters
public void GetPublicKey(Person receiver)
{
try
{
rsa.ImportParameters(receiver.SendPublicKey());
}
catch (CryptographicException e)
{
Console.WriteLine(e.Message);
}
}

public CipherMessage EncryptMessage(string text)
{
// Convert string to a byte array
CipherMessage message = new CipherMessage();
byte[] plainBytes = Encoding.Unicode.GetBytes(text.ToCharArray());

// A new key and iv are generated for every message
rc2.GenerateKey();
rc2.GenerateIV();

// The rc2 initialization doesnt need to be encrypted, but will
// be used in conjunction with the key to decrypt the message.
message.rc2IV = rc2.IV;
try
{
// Encrypt the RC2 key using RSA encryption
message.rc2Key = rsa.Encrypt(rc2.Key, false);
}
catch (CryptographicException e)
{
// The High Encryption Pack is required to run this sample
// because we are using a 128-bit key. See the readme for
// additional information.
Console.WriteLine("Encryption Failed. Ensure that the" +
" High Encryption Pack is installed.");
Console.WriteLine("Error Message: " + e.Message);
Environment.Exit(0);
}
// Encrypt the Text Message using RC2 (Symmetric algorithm)
ICryptoTransform sse = rc2.CreateEncryptor();
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, sse, CryptoStreamMode.Write);
try
{
cs.Write(plainBytes, 0, plainBytes.Length);
cs.FlushFinalBlock();
message.cipherBytes = ms.ToArray();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
ms.Close();
cs.Close();
}
return message;
} // method EncryptMessage

public void DecryptMessage(CipherMessage message)
{
// Get the RC2 Key and Initialization Vector
rc2.IV = message.rc2IV;
try
{
// Try decrypting the rc2 key
rc2.Key = rsa.Decrypt(message.rc2Key, false);
}
catch (CryptographicException e)
{
Console.WriteLine("Decryption Failed: " + e.Message);
return;
}

ICryptoTransform ssd = rc2.CreateDecryptor();
// Put the encrypted message in a memorystream
MemoryStream ms = new MemoryStream(message.cipherBytes);
// the CryptoStream will read cipher text from the MemoryStream
CryptoStream cs = new CryptoStream(ms, ssd, CryptoStreamMode.Read);
byte[] initialText = new Byte[message.cipherBytes.Length];

try
{
// Decrypt the message and store in byte array
cs.Read(initialText, 0, initialText.Length);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
ms.Close();
cs.Close();
}

// Display the message received
Console.WriteLine(name + " received the following message:");
Console.WriteLine(" " + Encoding.Unicode.GetString(initialText));
} // method DecryptMessage
} // class Person
} // namespace PublicKey

熱點內容
安卓手機壁紙如何更換成動態壁紙 發布:2025-01-20 01:40:27 瀏覽:705
安卓微信簽名在哪裡修改 發布:2025-01-20 01:25:31 瀏覽:109
安卓電腦管家怎麼恢復出廠設置 發布:2025-01-20 01:24:06 瀏覽:313
qt編譯sqlite庫 發布:2025-01-20 01:22:30 瀏覽:525
360攝像頭存儲設置 發布:2025-01-20 01:16:01 瀏覽:538
js防緩存 發布:2025-01-20 01:15:47 瀏覽:495
編程生日卡 發布:2025-01-20 01:15:14 瀏覽:206
android備忘錄源碼 發布:2025-01-20 01:06:32 瀏覽:455
怎麼禁用aspx緩存 發布:2025-01-20 01:00:50 瀏覽:688
我的手機如何恢復安卓系統 發布:2025-01-20 00:55:48 瀏覽:367