|
|
Pubblicato su 04/11/2015 12:37:23
|
|
|

I requisiti del progetto: generare una chiave privata e una chiave pubblica, criptare con chiave pubblica, decriptare con chiave privata, l'ho implementato così,
Spero di poter essere d'aiuto agli amici che hanno questo bisogno.
Il codice sorgente è il seguente:
1. Generare una coppia di chiavi:
/// <summary> Genera chiave privata e chiave pubblica arr[0] per chiave privata arr[1] per chiave pubblica /// </summary> /// <returns></returns> stringa statica pubblica[] GenerateKeys() { string[] sKeys = nuova stringa[2]; RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); sKeys[0] = rsa. ToXmlString(true); sKeys[1] = rsa. ToXmlString(falso); return sKeys; }
2. Crittografia:
/// <summary> /// RSA Encrypt /// </summary> <param name="sSource" >Stringa sorgente</param> <param name="sPublicKey" >chiave pubblica</param> /// <returns></returns> stringa statica pubblica EncryptString(stringa sSource, stringa sPublicKey) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); string in chiaro = sSource; RSA. FromXmlString(sPublicKey); byte[] cipherbiti; byte[] byteEn = rsa. Encrypt(Encoding.UTF8.GetBytes("a"), false); cipherbytes = RSA. Encrypt(Encoding.UTF8.GetBytes(testo in chiaro), falso);
StringBuilder sbString = nuovo StringBuilder(); per (int i = 0; Io < Cipherbytes. Lunghezza; i++) { sbString.Append(cipherbytes+ ","); }
3. Decrittazione:
/// <summary> Decrittografia RSA /// </summary> <param name="sSource">Stringa sorgente</param> <param name="sPrivateKey">Chiave privata</param> /// <returns></returns> stringa statica pubblica DecryptString(Stringa sSource, stringa sPrivateKey) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); RSA. FromXmlString(sPrivateKey); byte[] byteEn = rsa. Encrypt(Encoding.UTF8.GetBytes("a"), false); string[] sBytes = sSource.Split(',');
per (int j = 0; j < sBytes. Lunghezza; j++) { if (sBytes[j] != "") { byteEn[j] = Byte.Parse(sBytes[j]); } } byte[] plaintbytes = rsa. Decrittatura (byteEn, falso); return Encoding.UTF8.GetString(plaintbytes); } return sbString.ToString(); }
--------------------------------------------------------------------
Codice sorgente per cifratura e decrittazione RSA:
usando Sistema; usando System.Collections.Generic; usando System.Linq; usando System.Text; utilizzando System.Security.Cryptography;
Spazio di nomi MyRSA Spazio di nomi MyRSA
{
pubblicclass MyRSA
{
privatestaticstring publicKey =
"<RSAKeyValue><Modulus>6CdsXgYOyya/yQH"+
"TO96dB3gEurM2UQDDVGrZoe6RcAVTxAqDDf5L"+
"wPycZwtNOx3Cfy44/D5Mj86koPew5soFIz9sx"+
"PAHRF5hcqJoG+q+UfUYTHYCsMH2cnqGVtnQiE"+
"/PMRMmY0RwEfMIo+TDpq3QyO03MaEsDGf13sP"+
"w9YRXiac=</Modulus><Exponent>AQAB";</Exponent></RSAKeyValue>
privatestaticstring privateKey =
"<RSAKeyValue><Modulus>6CdsXgYOyya/yQH"+
"TO96dB3gEurM2UQDDVGrZoe6RcAVTxAqDDf5L"+
"wPycZwtNOx3Cfy44/D5Mj86koPew5soFIz9sx"+
"PAHRF5hcqJoG+q+UfUYTHYCsMH2cnqGVtnQiE"+
"/PMRMmY0RwEfMIo+TDpq3QyO03MaEsDGf13sP"+
"w9YRXiac=</Modulus><Exponent>AQAB</Exponent>"+
"<P>/aoce2r6tonjzt1IQI6FM4ysR40j/gKvt4d"+
"L411pUop1Zg61KvCm990M4uN6K8R/DUvAQdrRd"+
"VgzvvAxXD7ESw==</P><Q>6kqclrEunX/fmOle"+
"VTxG4oEpXY4IJumXkLpylNR3vhlXf6ZF9obEpG"+
"lq0N7sX2HBxa7T2a0WznOAb0si8FuelQ==</Q>"+
"<DP>3XEvxB40GD5v/Rr4BENmzQW1MBFqpki6FU"+
"GrYiUd2My+iAW26nGDkUYMBdYHxUWYlIbYo6Te"+
"zc3d/oW40YqJ2Q==</DP><DQ>LK0XmQCmY/ArY"+
"gw2Kci5t51rluRrl4f5l+aFzO2K+9v3PGcndjA"+
"StUtIzBWGO1X3zktdKGgCLlIGDrLkMbM21Q==</DQ><InverseQ>"+
"GqC4Wwsk2fdvJ9dmgYlej8mTDBWg0Wm6aqb5kjn"+
"cWK6WUa6CfD+XxfewIIq26+4Etm2A8IAtRdwPl4"+
"aPjSfWdA==</InverseQ><D>a1qfsDMY8DSxB2D"+
"Cr7LX5rZHaZaqDXdO3GC01z8dHjI4dDVwOS5ZFZ"+
"s7MCN3yViPsoRLccnVWcLzOkSQF4lgKfTq3IH40"+
"H5N4gg41as9GbD0g9FC3n5IT4VlVxn9ZdW+WQry"+
"oHdbiIAiNpFKxL/DIEERur4sE1Jt9VdZsH24CJE=</D></RSAKeyValue>";
staticpublicstring Decripta(stringa base64code)
{
prova
{
Crea un UnicodeEncoder per convertire tra array di byte e stringa.
UnicodeEncoding ByteConverter = nuovo UnicodeEncoding();
Crea una nuova istanza di RSACryptoServiceProvider per generare
dati a chiave pubblica e privata.
RSACryptoServiceProvider RSA =new RSACryptoServiceProvider();
RSA. FromXmlString(chiaviPrivata);
byte[] cifratoData;
byte[] decrittoData;
encryptedData = Convert.FromBase64String(base64code);
Passa i dati a DECRYPT, le informazioni della chiave privata
(usando RSACryptoServiceProvider.ExportParameters(true),
e una bandiera booleana che specifica l'assenza di rivestimento OAEP.
decryptedData = RSADecrypt(
encryptedData, RSA. ExportParameters (vero), falso);
Visualizza il testo in chiaro decriptato alla console.
return ByteConverter.GetString(decryptedData);
}
presa (eccezione ecc.)
{
Exceptions.LogException(exc);
Console.WriteLine(ecc. Messaggio);
ritorno"";
}
}
staticpublicstring Encrypt(stringa aEncryptString)
{
prova
{
Crea un UnicodeEncoder per convertire tra array di byte e stringa.
UnicodeEncoding ByteConverter = nuovo UnicodeEncoding();
Crea array di byte per contenere dati originali, criptati e decriptati.
byte[] dataToEncrypt =
ByteConverter.GetBytes(toEncryptString);
byte[] cifratoData;
byte[] decrittoData;
Crea una nuova istanza di RSACryptoServiceProvider per generare
dati a chiave pubblica e privata.
RSACryptoServiceProvider RSA =new RSACryptoServiceProvider();
RSA. FromXmlString(chiaviPrivata);
Passa i dati a ENCRYPT, le informazioni della chiave pubblica
(usando RSACryptoServiceProvider.ExportParameters(false),
e una bandiera booleana che specifica l'assenza di rivestimento OAEP.
encryptedData = RSAEncrypt(
dataToEncrypt, RSA. ExportParameters (falso), falso);
stringa base64code = Convert.ToBase64String(encryptedData);
restituisci base64code;
}
presa (eccezione ecc.)
{
Individua questa eccezione nel caso la crittografia lo facesse
non ci riesce.
Exceptions.LogException(exc);
Console.WriteLine(ecc. Messaggio);
ritorno"";
}
}
staticprivatebyte[] RSAEncrypt(
byte[] DataToEncrypt,
RSAParameters RSAKeyInfo,
bool DoOAEPPaggiunta)
{
prova
{
Crea una nuova istanza di RSACryptoServiceProvider.
RSACryptoServiceProvider RSA =new RSACryptoServiceProvider();
Importa le informazioni chiave RSA. Questo serve solo
per includere le informazioni della chiave pubblica.
RSA. ImportParameters (RSAKeyInfo);
Cripta l'array di byte passati e specifica il riempimento OAEP.
Il rifornimento OAEP è disponibile solo su Microsoft Windows XP o
Dopo.
Restituisci RSA. Encrypt(DataToEncrypt, DoOAEPPadding);
}
Cattura e visualizza un'eccezione criptografica
alla console.
catch (CryptographicException e)
{
Eccezioni. LogException(e);
Console.WriteLine(e.Message);
returnnull;
}
}
staticprivatebyte[] RSADecrypt(
byte[] DataToDecrypt,
RSAParameters RSAKeyInfo,
bool DoOAEPPaggiunta)
{
prova
{
Crea una nuova istanza di RSACryptoServiceProvider.
RSACryptoServiceProvider RSA =new RSACryptoServiceProvider();
Importa le informazioni chiave RSA. Questo deve
includere le informazioni della chiave privata.
RSA. ImportParameters (RSAKeyInfo);
Decripta l'array di byte passati e specifica il riempimento OAEP.
Il rifornimento OAEP è disponibile solo su Microsoft Windows XP o
Dopo.
Restituisci RSA. Decriptazione(DataToDecrypt, DoOAEPPaggiunta);
}
Cattura e visualizza un'eccezione criptografica
alla console.
catch (CryptographicException e)
{
Eccezioni. LogException(e);
Console.WriteLine(e.Message);
returnnull;
}
}
}
}
- static void Main(string[] args)
- {
- string encodeString = MyRSA.Encrypt("1234567");
- Console.WriteLine(encodeString);
- string decode = MyRSA.Decrypt(encodeString);
- Console.WriteLine(decode);
- Console.ReadLine();
- }
Copia codice
|
Precedente:Crea il tuo forum personale gratuitamente, puoi guadagnare costruendo per conto tuo, e puoi farlo in tre minutiProssimo:Uso di onclick e href nel tag A in HTML
|