Меню

Ошибка при декодировании заполнения oaep delphi

При расшифровке текста с помощью RSACryptoServiceProvider.Decrypt, Я получаю сообщение об ошибке:

Ошибка при декодировании заполнения OAEP.

Вот мой код:

CspParameters cspParam = new CspParameters();

cspParam = new CspParameters();

cspParam.Flags = CspProviderFlags.UseMachineKeyStore;

clsCertificates cc = new clsCertificates();

string a = "";

cc.OpenStoreIE(ref a);

cc.SetProperties();

X509Certificate2 cert = new X509Certificate2();

cert = cc.x509_2Cert;

RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cspParam);

//to gentrate private and public keys from the certificate

rsa.FromXmlString(cert.PublicKey.Key.ToXmlString(false));


String publicKey = rsa.ToXmlString(false); // gets the public key 
String privateKey = rsa.ToXmlString(true); // gets the private key working if paramter is false if true give error key is not valid for use in specified state

Response.Write("<Textarea rows=10 cols=100>PUBLIC: " + publicKey + "</TextArea>");

Response.Write("<Textarea rows=10 cols=100>PRIVATE: " + privateKey + "</Textarea>");

Response.Write("<BR>Encrypting the string "HelloThere" with the public Key:<BR>");

String str = "HelloThere";

RSACryptoServiceProvider RSA2 = new RSACryptoServiceProvider(cspParam);



//---Load the Public key---

RSA2.FromXmlString(publicKey);

//working with the folowing line instead of above but i need the keys of he certificte

//RSA2.ToXmlString(true);

Byte[] EncryptedStrAsByt = RSA2.Encrypt(System.Text.Encoding.Unicode.GetBytes(str), true);

String EncryptedStr = System.Text.Encoding.Unicode.GetString(EncryptedStrAsByt);

Response.Write("<Textarea rows=10 cols=100>Encrypted String: " + EncryptedStr + "</Textarea>");

Response.Write("<BR>Decrypting the Encrypted String with the Private key:<BR>");



RSACryptoServiceProvider RSA3 = new RSACryptoServiceProvider(cspParam);



//---Load the Private key---

RSA3.FromXmlString(privateKey);

//working with the folowing line instead of above but i need the keys of he certificte

//RSA3.ToXmlString(true);

Byte[] DecryptedStrAsByt = RSA3.Decrypt(EncryptedStrAsByt, true );//Error if true then error is error occured while decoding the OAE$P padding and if false then error is bad key i am using windows xp so it should be true.

String DecryptedStr = System.Text.Encoding.Unicode.GetString(DecryptedStrAsByt);

Response.Write("<Textarea rows=10 cols=100>Decrypted String: " + DecryptedStr + "</Textarea>");

Вышеуказанное работает, если я не использую ключи своего цифрового сертификата. но если ключи взяты из цифрового сертификата, я получаю ошибку заполнения OAEP.

Примечание. Этот вопрос является продолжением Ошибка при декодировании заполнения OAEP вопрос

8 ответы

Распространенная ошибка — попытаться расшифровать с помощью открытого ключа.

ответ дан 24 окт ’09, 18:10

Я столкнулся с этой проблемой. UnicodeEncoding.GetBytes не всегда противоположен UnicodeEncoding.GetString.

byte[] a = new byte[32];

RandomNumberGenerator gen = new RNGCryptoServiceProvider();
gen.GetBytes(a);

UnicodeEncoding byteConverter = new UnicodeEncoding();

byte[] b = byteConverter.GetBytes(byteConverter.GetString(a));

//byte array 'a' and byte array 'b' will not always contain the same elements.

Вот почему RSACryptoServiceProvider.Decrypt терпит неудачу. Многие примеры шифрования / дешифрования в Интернете используют кодировку Unicode. Не используйте кодировку Unicode. Использовать Convert.FromBase64String и Convert.ToBase64String .

ответ дан 19 окт ’11, 02:10

Эта ошибка обычно указывает на то, что вы используете открытый ключ для расшифровки, тогда как вы должны использовать закрытый ключ для расшифровки. Попробуйте.

Создан 06 фев.

В моем случае ошибка была вызвана неправильными настройками заполнения.

Error: RSA decrypt: error:0407A079:rsa routines:RSA_padding_check_PKCS1_OAEP:oaep decoding error

У меня было openssl_public_encrypt() с OPENSSL_PKCS1_PADDING как значение по умолчанию в PHP и keypair.decrypt() со значением по умолчанию RSA_PKCS1_OAEP_PADDING in узел-rsa.

Так что не забудьте проверить и эти параметры.

ответ дан 13 авг.

К вашему сведению, вы все еще можете (en / de) шифровать в правильной последовательности ключей (encr: pub key, decr: priv key) — то есть все еще можете получить эту ошибку, расшифровывая закрытым ключом — это просто может быть неправильно закрытый ключ (то есть из другой пары сертификат / ключ), а не тот, который связан с ключом публикации, с помощью которого вы зашифровали изначально. Если вы отключите заполнение OAEP и получите исключение «неверные данные», это еще один признак.

Создан 10 июн.

Шифрование RSA может привести к нечитаемому символу, убедитесь, что строка не обрезана из-за специального символа, указывающего конец чего-либо во время записи / чтения результата шифрования; например, вы не должны использовать strlen, потому что он остановится, когда встретит ‘ 0’ в строке.

ответ дан 26 мая ’14, 03:05

Еще одна вещь, которую нужно проверить: это выдавало мне эту ошибку при операции дешифрования в результате того, что я забыл передать открытый ключ в RSACryptoServiceProvider для операции шифрования.

ответ дан 24 апр.

У нас возникла эта проблема, когда мы использовали неправильный ключ для расшифровки.

Создан 27 янв.

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками

c#
encryption
rsa
digital-signature
rsacryptoserviceprovider

or задайте свой вопрос.

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
void EncryptFile(string inputFile, string outputFile)
        {
 
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
            {
                RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
               
                var rsaOpenKey = RSA.ExportParameters(false);//экспорт открытого ключа
 
                rsa.ImportParameters(rsaOpenKey);
 
                using (var fstreamIn = new FileStream(inputFile, FileMode.Open, FileAccess.Read))
                using (var fstreamOut = new FileStream(outputFile, FileMode.Create, FileAccess.Write))
                {
                    byte[] buf = new byte[64];
                    for (; ; )
                    {
                        int bytesRead = fstreamIn.Read(buf, 0, buf.Length);
                        if (bytesRead == 0) break;
                        byte[] encrypted = bytesRead == buf.Length ? rsa.Encrypt(buf, true) : rsa.Encrypt(buf.Take(bytesRead).ToArray(), true);
                        fstreamOut.Write(encrypted, 0, encrypted.Length);
                    }
                }
            }
        }
 
        void DecryptFile(string inputFile, string outputFile)
        {
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
            {
                RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
                var rsaPrivateKey = RSA.ExportParameters(true);//экспорт закрытого ключа
                rsa.ImportParameters(rsaPrivateKey);
 
                using (var fstreamIn = new FileStream(inputFile, FileMode.Open, FileAccess.Read))
                using (var fstreamOut = new FileStream(outputFile, FileMode.Create, FileAccess.Write))
                {
                    byte[] buf = new byte[128];
                    for (; ; )
                    {
                        int bytesRead = fstreamIn.Read(buf, 0, buf.Length);
                        if (bytesRead == 0) break;
                        byte[] decrypted = rsa.Decrypt(buf, true);
                        fstreamOut.Write(decrypted, 0, decrypted.Length);
                    }
                }
            }
        }
 
        private void Button1_Click(object sender, EventArgs e)
        {
            
            EncryptFile(Environment.CurrentDirectory+"in.txt",Environment.CurrentDirectory+"out.txt");
        }
 
        private void Button2_Click(object sender, EventArgs e)
        {
 
            DecryptFile(Environment.CurrentDirectory + "out.txt", Environment.CurrentDirectory + "in1.txt");
        }
    }

The problem you are describing is likely caused by using a different Private Key to Public Key.

If you generate the public and public+private key using the same instance of the RSA provider, then the keys would match. e.g.

string publicRSAKey = null;
string publicPlusPrivateRSAKey = null;

using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
    publicRSAKey = rsa.ToXmlString(false);
    publicPlusPrivateRSAKey = rsa.ToXmlString(true);
}

If you create the keys from two different instances of the RSA provider, then the public and public+private key’s won’t match. e.g.

string publicRSAKey = null;
string publicPlusPrivateRSAKey = null;

using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
    publicRSAKey = rsa.ToXmlString(false);
}

using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
    publicPlusPrivateRSAKey = rsa.ToXmlString(true);
}

When the keys match, I could round-trip without a problem. When the keys don’t match, I get the «Error occured while decoding OAEP padding.».

Can you verify that the keys match at runtime?

Since the Private Key will contain the Public Key as well, you can look a the contents of each key variable in xml string form, specifically the XML paths of /RSAKeyValue/Modulus and /RSAKeyValue/Exponent, as these should match between the two.

The problem you are describing is likely caused by using a different Private Key to Public Key.

If you generate the public and public+private key using the same instance of the RSA provider, then the keys would match. e.g.

string publicRSAKey = null;
string publicPlusPrivateRSAKey = null;

using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
    publicRSAKey = rsa.ToXmlString(false);
    publicPlusPrivateRSAKey = rsa.ToXmlString(true);
}

If you create the keys from two different instances of the RSA provider, then the public and public+private key’s won’t match. e.g.

string publicRSAKey = null;
string publicPlusPrivateRSAKey = null;

using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
    publicRSAKey = rsa.ToXmlString(false);
}

using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
    publicPlusPrivateRSAKey = rsa.ToXmlString(true);
}

When the keys match, I could round-trip without a problem. When the keys don’t match, I get the «Error occured while decoding OAEP padding.».

Can you verify that the keys match at runtime?

Since the Private Key will contain the Public Key as well, you can look a the contents of each key variable in xml string form, specifically the XML paths of /RSAKeyValue/Modulus and /RSAKeyValue/Exponent, as these should match between the two.

В принципе проблема решена, но так как считывание происходит поблочно, размер блока сильно влияет на скорость. С шифрованием все гуд. Метод для шифрования:

public bool Encrypt_RSA_File(string inputFile, string outFile, string fileext, int keySize, string xmLstring)
    {
        try
        {
            var rsa = new RSACryptoServiceProvider(keySize);
            rsa.FromXmlString(xmLstring);
            using (var fstreamIn = new FileStream(inputFile, FileMode.Open, FileAccess.Read))
            using (var fstreamOut = new FileStream(outFile, FileMode.Append, FileAccess.Write))
            using (var bw = new BinaryWriter(fstreamOut))
            {
                byte[] extbytes = Encoding.Unicode.GetBytes(fileext);
                byte[] extencrypted = rsa.Encrypt(extbytes, true);
                bw.Write(extencrypted, 0, extencrypted.Length);

                byte[] buf = new byte[64];
                byte[] temp = File.ReadAllBytes(inputFile);
                _currentMaxProg = temp.Length;

                for (; ; )
                {
                    if (_cancelled)
                    {
                        _currentProg = 0;
                        _currentMaxProg = 0;
                        return false;
                    }
                    int bytesRead = fstreamIn.Read(buf, 0, buf.Length);
                    _currentProg += bytesRead;
                    if (bytesRead == 0) break;
                    byte[] encrypted = bytesRead == buf.Length ? rsa.Encrypt(buf, true) : rsa.Encrypt(buf.Take(bytesRead).ToArray(), true);
                    fstreamOut.Write(encrypted, 0, encrypted.Length);
                    if (CurrentProgressChanged != null) CurrentProgressChanged(_currentProg);
                    Application.DoEvents();
                }
                _currentProg = 0;
                _currentMaxProg = 0;
                if (CurrentProgressChanged != null) CurrentProgressChanged(_currentProg);
            }
            return true;
        }
        catch (Exception ex) { MessageBox.Show(ex.Message); return false; }
    }

бинарным писателем пишем в выходной файл расширение исходного файла в зашифрованном виде — работает.

сам метод вызывается так:

 if (_crypter.Encrypt_RSA_File(path, path.Replace(fileext, ".crypt"), fileext, _view.RsAstrength, _xmLstring))
                {
                    _view.LogContent += _logger.WriteToLog("шифрование файла " + path + " завершилось успешно");
                    _view.LogContent += _logger.WriteToLog(string.Concat("файл сохранен как ", path.Replace(fileext, ".crypt")));
                }
                else
                {
                    _view.LogContent += _logger.WriteToLog("операция прервана. Файл" + path + " не обработан.");
                    _manager.Delete((T)Convert.ChangeType(path.Replace(fileext, ".crypt"), typeof(T)));
                    return;
                }

Теперь непосредственно о том, что под вопросом. Следующим способом

string fileext = _crypter.DecryptRsaExtension(path, _view.RsAstrength, _xmLstring);
            if (_crypter.Decrypt_RSA_File(path, path.Replace(".crypt", fileext), _view.RsAstrength, _xmLstring))
            {
                _view.LogContent += _logger.WriteToLog("расшифровка файла " + path + " завершилась успешно");
                _view.LogContent += _logger.WriteToLog(string.Concat("файл сохранен как ", path.Replace(".crypt", "")));
            }
            else
            {
                _view.LogContent += _logger.WriteToLog("операция прервана. Файл" + path + " не обработан.");
                _manager.Delete((T)Convert.ChangeType(path.Replace(".crypt", ""), typeof(T)));
                return;
            }

сначала выдираем и расшифровываем расширение файла и передаем его как один из параметров для расшифровки основной части зашифрованного файла. Расширение выдирается так:

public string DecryptRsaExtension(string path, int keySize, string xmLstring)
    {
        var fstreamIn = new FileStream(path, FileMode.Open, FileAccess.Read);
        byte[] buf = new byte[RsaEncFileExtSize(keySize)];
        var rsa = new RSACryptoServiceProvider(keySize);
        rsa.FromXmlString(xmLstring);
        fstreamIn.Read(buf, 0, buf.Length);
        byte[] decrypted = rsa.Decrypt(buf, true);
        var ext = Encoding.Unicode.GetString(decrypted);
        return ext;
    }

RsaEncFileExtSize(keySize) нужен для того, чтобы на основе размера ключа с которым шифровали файл определить количество байт, которые нам нужны для получения расширения. Работает очень просто:

private int RsaEncFileExtSize(int keySize)
    {
        int result = 0;
        switch (keySize)
        {
            case 1024: result = 128; break;
            case 2048: result = 256; break;
            case 3072: result = 384; break;
            case 4096: result = 512; break;
            case 5120: result = 640; break;
        }
        return result;
    }

Далее сам метод расшифровки:

public bool Decrypt_RSA_File(string encryptedFile, string decryptedFile, int keySize, string xmLstring)
    {
        try
        {
            var rsa = new RSACryptoServiceProvider(keySize);
            rsa.FromXmlString(xmLstring);
            using (var fstreamIn = new FileStream(encryptedFile, FileMode.Open, FileAccess.Read))
            using (var fstreamOut = new FileStream(decryptedFile, FileMode.Create, FileAccess.Write))
            {
                int ext = RsaEncFileExtSize(keySize);
                byte[] buf = new byte[384];
                byte[] temp = File.ReadAllBytes(encryptedFile);

                _currentMaxProg = temp.Length;
                for (; ; )
                {
                    if (_cancelled)
                    {
                        _currentProg = 0;
                        _currentMaxProg = 0;
                        return false;
                    }

                    var bytesRead = fstreamIn.Read(buf, 0, buf.Length);
                    _currentProg += bytesRead;
                    if (bytesRead == 0) break;
                    if (_currentProg > ext)
                    {
                        byte[] decrypted = rsa.Decrypt(buf, true);
                        fstreamOut.Write(decrypted, 0, decrypted.Length);
                        if (CurrentProgressChanged != null) CurrentProgressChanged(_currentProg);
                        Application.DoEvents();
                    }
                }
                _currentProg = 0;
                _currentMaxProg = 0;
                if (CurrentProgressChanged != null) CurrentProgressChanged(_currentProg);
            }
            return true;
        }
        catch (Exception ex) { MessageBox.Show(ex.Message); return false; }
    }

Если я указываю размер buf = 384, все работает, но оооооочень медленно. Файл, который занимает в исходном и зашифрованном виде 10 с чем-то и 30 с чем-то метров соответственно расшифровывается 10-15 минут. И да, я помню, что вместо 384 надо писать RsaEncFileExtSize(int keySize), но на данный момент тестирую с ключом 3072. Если же пишу 64, 128, 192, 256, выдает ошибку декодирования заполнения OAEP на строке byte[] decrypted = rsa.Decrypt(buf, true);, когда _currentProg > 384. Внимание вопрос: Как можно уменьшить размер считываемого блока, чтобы не было ошибки заполнения? Либо как повысить производительность для buf=384 или RsaEncFileExtSize(intkeySize)?

P.S. просто решил избавиться от зашифрованных файлов с двойным расширением. Если при шифровании расширение записывать в чистом виде(без шифрования), проблема та же.
замена на byte[] buf = new byte[ext]; где ext = RsaEncFileExtSize(keySize); не решает проблемы.

В настоящее время я работаю над классом, который шифрует большие объемы текста с помощью случайно сгенерированного ключа шифрования, зашифрованного сертификатом X509 со смарт-карты, используя RSACryptoServiceProvider для выполнения операций шифрования и дешифрования главного ключа. Однако, когда для параметра заполнения fOEAP установлено значение true, при расшифровке каждый раз возникает ошибка «Ошибка при декодировании заполнения OAEP». Я проверил размер ключа, он находится в допустимых пределах. И я прошел через точки останова, чтобы убедиться, что строка Base64, возвращаемая функцией шифрования, точно такая же, как зашифрованная строка Base64, которая возвращается обратно в функцию дешифрования при повторной загрузке файла.

Пара ключей определенно верна, поскольку она отлично работает без OAEP. И кодировку текста я тоже проверил.

РЕДАКТИРОВАТЬ: Оказывается, это может быть проблема со смарт-картой, когда я попытался расшифровать с помощью локального сертификата X509, расшифровка прошла успешно.

РЕДАКТИРОВАТЬ: это код дешифрования, который не работает:

string TestString = "Hello World!";
X509Certificate2 cert = DRXEncrypter.GetCertificate("Select a test certificate", "Select a certificate to use for this test from the local store.");
string key = DRXEncrypter.GenerateEncryptionKey(214);
Console.WriteLine("Encryption Key: " + key);

string encrypted = DRXEncrypter.EncryptBody(TestString, key);
Console.WriteLine("Encrypted Body: " + encrypted);

string cryptokey = DRXEncrypter.EncryptWithCert(cert, key);
Console.WriteLine("Encrypted Decryption Key: " + cryptokey);

string decrypted = DRXEncrypter.DecryptBody(encrypted, cryptokey, cert);
Console.WriteLine("Decrypted Body: " + decrypted);

Console.WriteLine("Output String: " + decrypted + ".");

Вот код из класса поставщика криптографии, который я написал. Я застрял в этом вопросе несколько часов, поэтому было бы здорово, если бы кто-нибудь мог мне помочь.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.IO;

namespace CoreDRXEditor
{
public class DRXEncrypter
{
    private byte[] Salt = Encoding.ASCII.GetBytes("81PO9j8I1a94j");
    private string EncryptionKey;
    private const bool UseOAEP = true;

    public DRXEncrypter(string EncryptionKey)
    {
        this.EncryptionKey = EncryptionKey;
    }

    public static string EncryptBody(string body, string encryptionkey)
    {
        // Use the plaintext master key to encrypt the body.
        DRXEncrypter enc = new DRXEncrypter(encryptionkey);

        // Encrypt the body.
        return enc.Encrypt(body);
    }

    public static int GetMaxKeySize(X509Certificate2 cert)
    {
        RSACryptoServiceProvider csp = cert.PublicKey.Key as RSACryptoServiceProvider;

        return csp.KeySize;
    }

    public static string DecryptBody(string body, string encryptionkey, X509Certificate2 cert)
    {
        // Decrypt the encrypted encryption key with the certificate.
        string DecryptedKey = Convert.ToBase64String(DecryptWithCert(cert, encryptionkey));

        // Create a new DRXEncrypter using the decrypted encryption key to decrypt the body.
        DRXEncrypter enc = new DRXEncrypter(DecryptedKey);

        // Return the decrypted body.
        return enc.Decrypt(body);
    }

    public static string GenerateEncryptionKey(int KeyLength)
    {
        using (RandomNumberGenerator rng = new RNGCryptoServiceProvider())
        {
            byte[] CryptoBytes = new byte[KeyLength];
            rng.GetBytes(CryptoBytes);

            return Convert.ToBase64String(CryptoBytes);
        }
    }

    public static X509Certificate2 GetCertificate(string title, string message)
    {
        X509Store cstore = new X509Store(StoreLocation.CurrentUser);
        cstore.Open(OpenFlags.ReadOnly);

        X509CertificateCollection certs = X509Certificate2UI.SelectFromCollection(cstore.Certificates, title, message, X509SelectionFlag.SingleSelection);

        if (certs.Count == 1)
        {
            X509Certificate2 mcert = certs[0] as X509Certificate2;
            return mcert;
        }
        else
        {
            return null;
        }
    }

    public static string EncryptWithCert(X509Certificate2 cert, string PlainText)
    {
        RSACryptoServiceProvider csp = cert.PublicKey.Key as RSACryptoServiceProvider;

        byte[] PlainBytes = Convert.FromBase64String(PlainText);

        // This converts the plain text into a byte array and then encrypts the raw bytes.
        byte[] CryptoBytes = csp.Encrypt(PlainBytes, UseOAEP);

        // This converts the encrypted bytes into a Base64 string.
        string ReturnString = Convert.ToBase64String(CryptoBytes);

        return ReturnString;
    }

    public static byte[] DecryptWithCert(X509Certificate2 cert, string EncryptedText)
    {
        RSACryptoServiceProvider csp = cert.PrivateKey as RSACryptoServiceProvider;

        //CspParameters csps = new CspParameters();

        byte[] EncryptedBytes = Convert.FromBase64String(EncryptedText);

        // This converts the encrypted, Base64 encoded byte array from EncryptWithCert() to a byte[] and decrypts it.
        byte[] CryptoBytes = csp.Decrypt(EncryptedBytes, UseOAEP);

        return CryptoBytes;
    }

    public string Encrypt(string PlainText)
    {
        RijndaelManaged Algorithm = null;
        string Output = null;

        try
        {
            Rfc2898DeriveBytes PrivateKey = new Rfc2898DeriveBytes(this.EncryptionKey, this.Salt);


            Algorithm = new RijndaelManaged();
            Algorithm.Key = PrivateKey.GetBytes(Algorithm.KeySize / 8);
            Algorithm.Padding = PaddingMode.PKCS7;

            ICryptoTransform Encryption = Algorithm.CreateEncryptor(Algorithm.Key, Algorithm.IV);

            using (MemoryStream msa = new MemoryStream())
            {
                msa.Write(BitConverter.GetBytes(Algorithm.IV.Length), 0, sizeof(int));
                msa.Write(Algorithm.IV, 0, Algorithm.IV.Length);
                using (CryptoStream csa = new CryptoStream(msa, Encryption, CryptoStreamMode.Write))
                {
                    using (StreamWriter swa = new StreamWriter(csa))
                    {
                        swa.Write(PlainText);
                    }
                }
                Output = Convert.ToBase64String(msa.ToArray());
            }
        }
        finally
        {
            if (Algorithm != null)
            {
                Algorithm.Clear();
            }
        }

        return Output;
    }

    public string Decrypt(string EncryptedText)
    {
        RijndaelManaged Algorithm = null;
        string Output = null;

        try
        {
            Rfc2898DeriveBytes PrivateKey = new Rfc2898DeriveBytes(this.EncryptionKey, this.Salt);

            byte[] KeyBytes = Convert.FromBase64String(EncryptedText);
            using (MemoryStream msb = new MemoryStream(KeyBytes))
            {
                Algorithm = new RijndaelManaged();
                Algorithm.Key = PrivateKey.GetBytes(Algorithm.KeySize / 8);
                Algorithm.IV = ReadByteArray(msb);
                Algorithm.Padding = PaddingMode.PKCS7;
                ICryptoTransform Decryption = Algorithm.CreateDecryptor(Algorithm.Key, Algorithm.IV);
                using (CryptoStream csb = new CryptoStream(msb, Decryption, CryptoStreamMode.Read))
                {
                    using (StreamReader srb = new StreamReader(csb))
                    {
                        Output = srb.ReadToEnd();
                    }
                }

            }
        }
        finally
        {
            if (Algorithm != null)
            {
                Algorithm.Clear();
            }
        }

        return Output;
    }

    public static string Sha512(string ToHash)
    {
        using (SHA512 SHA = new SHA512Managed())
        {
            byte[] HashByte = Encoding.UTF8.GetBytes(ToHash);
            byte[] HashBytes = SHA.ComputeHash(HashByte);
            string Hash = System.Text.Encoding.UTF8.GetString(HashBytes, 0, HashBytes.Length);
            return Hash;
        }
    }

    public static string Base64Encode(string data)
    {
        byte[] str = Encoding.UTF8.GetBytes(data);
        return Convert.ToBase64String(str);
    }

    public static string Base64Decode(string data)
    {
        byte[] str = Convert.FromBase64String(data);
        return Encoding.UTF8.GetString(str);
    }

    private byte[] ReadByteArray(Stream st)
    {
        byte[] Length = new byte[sizeof(int)];
        st.Read(Length, 0, Length.Length);
        byte[] Buffer = new byte[BitConverter.ToInt32(Length, 0)];
        st.Read(Buffer, 0, Buffer.Length);

        return Buffer;
    }
}
}

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка при загрузке выбранной карты warcraft 3
  • Ошибка при ддос атаке