Feedback

C++ - C++/CLI Encrypt und Decrypt Strings

Veröffentlicht von am 7/10/2010
(0 Bewertungen)
Eine Adaption von "Encrypt and Decrypt Strings" von Jan Welker nach C++/CLI.

Einfach als simple Funktionen.
using namespace System;
using namespace System::IO;
using namespace System::Security::Cryptography;

array<System::Byte> ^ diubEncryptString(array<System::Byte> ^ clearText, array<System::Byte> ^ Key, array<System::Byte> ^ IV) {
    MemoryStream ^ms = gcnew MemoryStream();
    Rijndael ^alg = Rijndael::Create();
    alg->Key = Key;
    alg->IV = IV;
    CryptoStream ^cs = gcnew CryptoStream(ms, alg->CreateEncryptor(), CryptoStreamMode::Write);
    cs->Write(clearText, 0, clearText->Length);
    cs->Close();
    array<System::Byte> ^ encryptedData = ms->ToArray();
    return encryptedData;
}

String ^ diubEncryptString(String ^ clearText, String ^ Password) {
    array<System::Byte> ^ clearBytes = System::Text::Encoding::Unicode->GetBytes(clearText);
    Rfc2898DeriveBytes ^pdb = gcnew Rfc2898DeriveBytes(Password, gcnew array<System::Byte>  { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
    array<System::Byte> ^ encryptedData = diubEncryptString(clearBytes, pdb->GetBytes(32), pdb->GetBytes(16));
    return Convert::ToBase64String(encryptedData);
}

array<System::Byte> ^ diubDecryptString(array<System::Byte> ^ cipherData, array<System::Byte> ^ Key, array<System::Byte> ^ IV) {
    MemoryStream ^ms = gcnew MemoryStream();
    Rijndael ^alg = Rijndael::Create();
    alg->Key = Key;
    alg->IV = IV;
    CryptoStream ^cs = gcnew CryptoStream(ms, alg->CreateDecryptor(), CryptoStreamMode::Write);
    cs->Write(cipherData, 0, cipherData->Length);
    cs->Close();
    array<System::Byte> ^ decryptedData = ms->ToArray();
    return decryptedData;
}

String ^ diubDecryptString(String ^ cipherText, String ^ Password) {
	if (!cipherText) return "";
    array<System::Byte> ^ cipherBytes = Convert::FromBase64String(cipherText);
    Rfc2898DeriveBytes ^pdb = gcnew Rfc2898DeriveBytes(Password, gcnew array<System::Byte>  { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
    array<System::Byte> ^ decryptedData = diubDecryptString(cipherBytes, pdb->GetBytes(32), pdb->GetBytes(16));
    return System::Text::Encoding::Unicode->GetString(decryptedData);
}

Kommentare zum Snippet

 

Logge dich ein, um hier zu kommentieren!