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
8,3994 gold badges45 silver badges79 bronze badges
asked Jun 5, 2009 at 5:48
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
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
62.8k17 gold badges141 silver badges172 bronze badges
answered Jan 29, 2010 at 18:25
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
6,5593 gold badges33 silver badges45 bronze badges
answered Sep 23, 2010 at 22:55
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_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
galaxisgalaxis
9058 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 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
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
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"); } } |
В настоящее время я работаю над классом, который шифрует большие объемы текста с помощью случайно сгенерированного ключа шифрования, зашифрованного сертификатом 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;
}
}
}
- Remove From My Forums
-
Вопрос
-
Добрый день, коллеги!
Пытаюсь настроить работу WAC (2009) WinRM for HTTPS, провел подготовительные работы на удаленном ПК согласно
статье. Но при попытке подключиться выходит следующая ошибка и не могу понять почему:
Connecting to remote server srv01.contoso.local failed with the following error message : The server certificate on the destination computer (srv1.contoso.local:5986) has the following errors: The SSL certificate could not be checked for revocation. The server used to check for revocation might be unreachable. For more information, see the about_Remote_Troubleshooting Help topic.
Проверил CRL доступны, в Enterprise PKI тоже все ОК, в чем проблема не могу понять, есть у кого соображения по этому поводу?
Даже сам на себя через WAC не получается зайти :-(, когда-то пробовал данный функционал все без проблем работало, может глюк новой версии?
Ответы
-
Действительно как только я настроил OCSP и выпустил новый сертификат все заработало.
-
Помечено в качестве ответа
30 декабря 2020 г. 13:10
-
Помечено в качестве ответа