1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
|
// TestCrypto.cpp*: définit le point d'entrée pour l'application console.
//
#include "stdafx.h"
using namespace System;
using namespace System::Security::Cryptography;
using namespace System::Text;
using namespace System::IO;
array<Byte>^ EncryptStringToBytes_Aes(String ^ plainText, array<Byte>^ Key,array<Byte>^ IV)
{
array<Byte>^ encrypted;
// Create an AesCryptoServiceProvider object with the specified key and IV.
AesCryptoServiceProvider ^ aesAlg = gcnew AesCryptoServiceProvider;
aesAlg->Key = Key;
aesAlg->IV = IV;
// Create a decrytor to perform the stream transform.
ICryptoTransform ^ encryptor = aesAlg->CreateEncryptor(aesAlg->Key, aesAlg->IV);
// Create the streams used for encryption.
MemoryStream ^ msEncrypt = gcnew MemoryStream;
CryptoStream ^ csEncrypt = gcnew CryptoStream(msEncrypt, encryptor, CryptoStreamMode::Write);
StreamWriter ^ swEncrypt = gcnew StreamWriter(csEncrypt);
swEncrypt->Write(plainText);
encrypted = msEncrypt->ToArray();
return encrypted;
}
String ^ DecryptStringFromBytes_Aes(array<Byte>^ cipherText, array<Byte>^ Key, array<Byte>^ IV)
{
String ^ plaintext = "";
// Create an AesCryptoServiceProvider object with the specified key and IV.
AesCryptoServiceProvider ^ aesAlg = gcnew AesCryptoServiceProvider;
aesAlg->Key = Key;
aesAlg->IV = IV;
// Create a decrytor to perform the stream transform.
ICryptoTransform ^ decryptor = aesAlg->CreateDecryptor(aesAlg->Key, aesAlg->IV);
// Create the streams used for encryption.
MemoryStream ^ msDecrypt = gcnew MemoryStream(cipherText);
CryptoStream ^ csDecrypt = gcnew CryptoStream(msDecrypt, decryptor, CryptoStreamMode::Read);
StreamReader ^ srDecrypt = gcnew StreamReader(csDecrypt);
plaintext = srDecrypt->ReadToEnd();
return plaintext;
}
int _tmain(int argc, _TCHAR* argv[])
{
String ^ original = "Here is some data to encrypt!";
AesCryptoServiceProvider ^ myAes = gcnew AesCryptoServiceProvider;
array<Byte>^ encrypted = EncryptStringToBytes_Aes( original, myAes->Key, myAes->IV) ;
String ^ roundtrip = DecryptStringFromBytes_Aes(encrypted, myAes->Key, myAes->IV);
Console::WriteLine("Original: {0}\n", original);
Console::WriteLine("encrypted: {0}\n", encrypted);
Console::WriteLine("Decrypted: {0}\n", roundtrip );
return 0;
} |
Partager