Ошибка при декодировании заполнения 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;
    }
}
}

Поюзал много веток но толком описания восстановления, прошивки и т.д автокомов тут нет или я плохо смотрел? Неужели я первый у кого всё работало прекрасно на версиях до 2014.3.2 а после установки и активации при первой же попытке обновить прошивку выдаёт ответ об ошибке! Железо программа видит но работать с ним не хочет пока не увидит новое ПО головы! Направьте куда нибудь…

Если стабильно работала со старой версией — не надо обновлять.

Перед запуском новой версии закидывайте папку Firmware от старой.

Запуск проги, тест и работайте.

Если слетела прошивка — востанавливайте старой версией.

While decrypting text using RSACryptoServiceProvider.Decrypt, I am getting the error:

Error occurred while decoding OAEP padding.

Here’s my code:

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>");

The above is works if I am not using the keys of my digital certificate. but if the keys are from the digital certificate, I get the OAEP padding error.

Note: This question is in continuation of the Error occurred while decoding OAEP padding question

Luke Willis's user avatar

Luke Willis

8,4094 gold badges46 silver badges79 bronze badges

asked Jun 5, 2009 at 5:48

Meetu Choudhary's user avatar

Meetu ChoudharyMeetu Choudhary

1,3634 gold badges14 silver badges26 bronze badges

10

A common mistake is to try to decrypt using the public key.

answered Oct 24, 2009 at 17:23

rohancragg's user avatar

5

I ran into this exact problem. UnicodeEncoding.GetBytes is not always the inverse of 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.

This is why RSACryptoServiceProvider.Decrypt fails. A lot of encrypt/decrypt examples on the web use Unicode encoding. Do not use Unicode encoding. Use Convert.FromBase64String and Convert.ToBase64String instead.

user7116's user avatar

user7116

62.8k17 gold badges141 silver badges172 bronze badges

answered Jan 29, 2010 at 18:25

anvilis's user avatar

anvilisanvilis

2312 silver badges4 bronze badges

3

This error normally indicates you are using a public key to decrypt, while you should be using a private key for decryption. Give it a try.

gitsitgo's user avatar

gitsitgo

6,5593 gold badges33 silver badges45 bronze badges

answered Sep 23, 2010 at 22:55

user456732's user avatar

user456732user456732

511 silver badge1 bronze badge

1

In my case the error has been caused by wrong padding settings.

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

I had openssl_public_encrypt() with OPENSSL_PKCS1_PADDING as a default value in PHP and keypair.decrypt() with the default value RSA_PKCS1_OAEP_PADDING in node-rsa.

So don’t forget to check these options too.

answered Aug 13, 2012 at 14:09

o_nix's user avatar

o_nixo_nix

1,1461 gold badge16 silver badges30 bronze badges

FYI, you can still be (en/de)crypting in the right key sequence (encr:pub key, decr:priv key) — i.e. can still get this error decrypting with a private key — it just may be the wrong private key (i.e. from another cert/key pair), not the one paired w/ the pub key with which u encrypted initially. If u turn off OAEP padding and get a «bad data» exception, that’s another indication.

answered Oct 10, 2018 at 21:35

galaxis's user avatar

galaxisgalaxis

9158 silver badges10 bronze badges

1

We were getting this issue when we were using the wrong key for decryption.

answered Jan 27, 2017 at 17:20

Zach Wymer's user avatar

Zach WymerZach Wymer

5409 silver badges11 bronze badges

RSA encryption may result non readable character, make sure not to cut the string due to special character indicating end of something during write/read the encryption result; e.g you must not use strlen for it will stop when encounter a » in the string.

answered May 26, 2014 at 2:52

user3121260's user avatar

Another thing to check: it was giving me this error, on the decrypt operation, as a result of forgetting to pass the public key into the RSACryptoServiceProvider for the encrypt operation.

answered Apr 24, 2015 at 20:28

user1454265's user avatar

user1454265user1454265

85811 silver badges25 bronze badges

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");
        }
    }

Cборка для виртуальной машины VMware.

В сборку включены:
— Delphi/Autocom CARS 2014.3.2 RU
— Delphi/Autocom TRUCKS 2014.3.2 RU
— WOW! 4.15.3 RU
— WOW! 5.00.8 RU
Все программы исцелены от жадности и работают без каких-либо патчей или активаторов, всё уже активировано и пропатчено.

Delphi CARS и TRUCKS активированы на прибор с популярным серийным номером 100251. Введены все дополнительные лицензии включая Turbo Сharger и Diesel Max. Для того чтобы работали все дополнительные функции программы Delphi в сборке установлена программа RunAsDate, т.е. Delphi всегда запускается с датой 12.12.2013г. Используется прошивка 1521, т.е. потребуется обновить прошивку адаптера тем кто этого сделать еще не успел.

  • Ошибка при двусторонней печати
  • Ошибка при генерации кода для свойства cursor
  • Ошибка при генерации карты rimworld multiplayer
  • Ошибка при вычислении 7 букв
  • Ошибка при выставлении счета