Error occurred while decoding oaep padding

Error occurred while decoding oaep padding This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions. Asked by: Question I’m using a certificate to encrypt/decrypt the data using Key Vault. Here is the flow of actions I’m trying to do. 1. Encrypt the Data. 2. Store at some location. Say […]

Содержание

  1. Error occurred while decoding oaep padding
  2. Asked by:
  3. Question
  4. Error occurred while decoding oaep padding
  5. Answered by:
  6. Question
  7. Answers
  8. All replies
  9. Ошибка при декодировании заполнения OAEP
  10. 8 ответы
  11. Error occurred while decoding oaep padding
  12. Answered by:
  13. Question
  14. Answers
  15. All replies

Error occurred while decoding oaep padding

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Asked by:

Question

I’m using a certificate to encrypt/decrypt the data using Key Vault. Here is the flow of actions I’m trying to do.

1. Encrypt the Data.

2. Store at some location. Say SQL. (byte[])

3. Retrieve it from SQL.

Here is my methods.

During Decrypt, I end up with the error message » Error occurred while decoding OAEP padding. ExceptionType Microsoft.Azure.KeyVault.KeyVaultClientException Message An error has occurred. StackTrace at Microsoft.Azure.KeyVault.KeyVaultClient. d__11b`1.MoveNext() «

However, If I encrypt the data and then decrypt it directly without storing it to SQL then it is working fine.

Not sure What difference it is making while i am storing it in SQL. I’m storing the byte[] directly into the database without converting it to string. (I also get the issue if i convert it to string)

Источник

Error occurred while decoding oaep padding

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Answered by:

Question

while doing asymetic encryption method I am using public key of a digital signature for encrypting. and private key for decrypting. I am able to encrypt the data successfully. but while decrypting i am getting the error as

Error occurred while decoding OAEP padding.

my piece of code is

using ( var rsa = new RSACryptoServiceProvider ())

// This String consists only Public Key Information

String publicKeyOnly = rsa.ToXmlString( false );

// This String consists both Private/Public Key information

String publicPrivate = rsa.ToXmlString( true );

public byte [] b( String publicKeyOnly)

String s = » vi74tqVrIHSyFELPThmQHUmkZsPx+baueW1reayVWzUe1nT0mZCCqPOcCYKT25E5TLpAh/bMQReLGIvokK+EzzFPqT2Ka0oK0LgPgO2LGZECR4PHdW/UH+bSwWaxN4rikEQGEr0M7rVv5wBFxhcZ/EFv40im+MVIkiM7W2P8PTM= AQAB » ;

using ( var rsaPublicOnly = new RSACryptoServiceProvider ())

encryptedData = rsaPublicOnly.Encrypt( Encoding .UTF8.GetBytes( «This String is to be Secured.» ), true );

public String c( byte [] encryptedData)

using ( var rsaPublicPrivate = new RSACryptoServiceProvider ())

RSACryptoServiceProvider .UseMachineKeyStore = true ;

// Providing Private key information to RSA Object

// Decrypting the encrypted data by using RSA object «rsaPublicPrivate»

decryptedPassword = rsaPublicPrivate.Decrypt(encryptedData, true ).ToString(); //error at this line

Thanks and Regards
Meetu Choudhary

Answers

I had exactly the same problem. Initially I thought it was due to not having permissions to the certificate’s private key. I have found that in certain cases, Encoding.Unicode.GetBytes is not the inverse of Encoding.Unicode.GetString

RandomNumberGenerator gen = new RNGCryptoServiceProvider();
byte[] randomBytes = new byte[32];
gen.GetBytes(randomBytes);

This surprised me to say the least. Many examples online serialize and deserialize strings to byte arrays using Unicode encoding.

This is why the decryption fails. The Decrypt function is decrypting the incorrect byte array.

Use Convert.FromBase64String and Convert.ToBase64String instead. These functions are inverses.

  • Marked as answer by Karel Zikmund Microsoft employee Sunday, February 14, 2010 12:01 AM

I have modified my code and now i am trying this code

cspParam = new CspParameters ();

cspParam = new CspParameters ();

cspParam.Flags = CspProviderFlags .UseMachineKeyStore;

clsCertificates cc = new clsCertificates ();

cc.OpenStoreIE( ref a);

X509Certificate2 cert = new X509Certificate2 ();

RSACryptoServiceProvider rsa = new RSACryptoServiceProvider (cspParam);

//to gentrate private and public keys from the certificate

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( «
Encrypting the string »HelloThere» with the public Key:
» );

String str = «HelloThere» ;

RSACryptoServiceProvider RSA2 = new RSACryptoServiceProvider (cspParam);

//—Load the Public key—

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

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

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

Response.Write( «
Decrypting the Encrypted String with the Private key:
» );

RSACryptoServiceProvider RSA3 = new RSACryptoServiceProvider (cspParam);

//—Load the Private key—

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

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

The whole is working if i am not using the keys of digital certificate. but if the keys are of digital certificate eroors are there please help me urgently.

Источник

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

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

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

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

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

задан 05 июн ’09, 02:06

У вас может быть больше шансов получить ответ, если вы сообщили нам сообщение об ошибке, а не только то, что произошла ошибка. Кто-то мог столкнуться с той же ошибкой и вспомнить, что решило проблему. — Accipitridae

Пожалуйста, не публикуйте повторяющиеся вопросы. Это принадлежит вашему исходному сообщению (stackoverflow.com/questions/949907/…). — Matthew Flaschen

Я также пробовал Array.Reverse (EncryptedStrAsByt); перед Byte [] DecryptedStrAsByt = RSA3.Decrypt (EncryptedStrAsByt, true); но по-прежнему нет ошибок результатов. — Meetu Choudhary

Я попытался опубликовать комментарий в этом вопросе, но ограничение по количеству слов, поэтому я опубликовал новый вопрос, извините — Meetu Choudhary

Произошла ошибка при декодировании заполнения OAEP. Описание: Необработанное исключение произошло во время выполнения текущего веб-запроса. Просмотрите трассировку стека для получения дополнительных сведений об ошибке и ее происхождении в коде. Сведения об исключении: System.Security.Cryptography.CryptographicException: Ошибка при декодировании заполнения OAEP. Ошибка источника: Строка 83: Байт [] DecryptedStrAsByt = RSA3.Decrypt (EncryptedStrAsByt, true); — Meetu Choudhary

8 ответы

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

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

Я хочу зашифровать данные своим закрытым ключом, а затем расшифровать их своим открытым ключом на клиентском компьютере. Почему это ошибка? Я думал, что это нормальный способ использования RSA. 🙁 — Никто

Нет, «нормальным» способом является шифрование открытым ключом и дешифрование закрытым ключом. Если вы зашифруете данные с помощью закрытого ключа, любой, у кого есть ваш открытый ключ, сможет расшифровать эти данные. Хотя это бесполезно для сохранения конфиденциальности данных, is полезно для проверки того, что данные действительно поступили из ожидаемого источника. — Старый

(Это в общем случае. Я почти уверен, что функции RSA_encrypt / decrypt библиотеки OpenSSL не могут выполнить это действие). — Старый

@Ни один. Никто: «Я хочу зашифровать данные своим закрытым ключом, а затем расшифровать их своим открытым ключом» — да, это не так. Возможно, вы хотите Схема подписи с восстановлением. — jww

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

Источник

Error occurred while decoding oaep padding

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Answered by:

Question

I have some code:

The first ‘GetKeyFromContainer’ gets the public and private key using (privateExport is true).

The second false (privateExport is false). Simply changing this value to true (public AND private keys) makes everything work.

Answers

To transfer certificates with a private key you can export the certificate with the private key to a PFX file and import it in another machine. That way the private key is not compromised.

I am sorry I had the logic backward. You encrypt with a public key and decrypt with the private key. Being somewhat new to asymmetric keys how do I pass an ecyrypted secret out with only supplying a public key. Or is this just not possible? I want to have an application use a password but I don’t want to hard-code the password. Any suggestions on how I might do this?

To decrypt data encrypted with a public key the recipient MUST have the corresponding private key. In other words, if I want to send a message to you I must use your public key to encrypt it. then you’d use your private key to decrypt it. That’s how public key encryption works and is why it’s also called asymmetrical encryption. A good article to read (a bit dated. but still accurate) is located here:

If you just want to encrypt a message with a key and pass out the key to your recipients then that’s just plain old symmetrical encryption.

If you can provide a bit more detail on your project maybe I can be of more assistance.

Thank you. Yea, I realized that I got it reversed. Sorry.

So given that my application is .NET what would you suggest to be the best way to have the application use a password without the password hard-coded in the code? In other words how would I implement essential the inverse of a typical public/private key scenario? I want to encrypt a password and put that password as a string (probably base64) then at runtime have the application decrypt this password using the equivalent of a public key with the same assurances.

I’m not clear on where/how you plan to store/retrieve the password data on the machine that’s running your app (via a local file? retrieved via a web server?).

At any rate, I think you may want to look at using salts to generate a one-way password hash instead and store that on the application’s local machine. The way this would work is that you’d generate a one-way hash of the password on your end and pass the salt bytes/initialization vector, hash value and possibly the algorithm used to the user. When they type in the password, your app would regenerate the hash on their machine using the provided information and compare that to the stored hash (in a local file most likely). If the hash matches then the password matched. and you never exposed the actual password to anyone.

Note however that you don’t get the same assurances with this. since it’s a symmetrical algorithm. but it can be combined with public/private key encryption to make it more secure. I hope that made sense.

This link should give you some ideas:

Thank you very much. This should get me started.

As far as where I plan to store the password. I was planning on storing the password as a const/static string in the app itself. So this is the reason I don’t want to store the actual password since as you are well aware it is so easy to get the strings used in an app.

The problem with the hash is that the user of the app needs to know the password. I want to use a password (without the user of the app knowing it) but I also want the password to be «undescoverable», hence encrypted. I had thought of using a certificate and forcing the user to install a certificate (which would have a public/private key pair in it, right?) But being relatively new although the idea computes I am not sure how to practically implement it. How do I generate a certificate? How do I encrypt using the public key in the certificate? How do I transfer the certifcate and deploy it with the app? Is there a programmatic was to install/deploy this certificate so it is «automatic» without user intervention. I want to prevent the user from keeping a file version of the certificate around. Finally what APIs are available to get the private key and subsequently using it to decrypt the password?

Question 1: How do I generate a certificate?

You can use the certificate creation tool “makecert.exe” to create test certificates. Reference: http://msdn.microsoft.com/en-us/library/bfsktky3(VS.80).aspx.
However for commercial usage certificates can be obtained from a certificate authority (CA) after you create the request and submit it to a CA for signing.

Example: I can generate a request using the Web enrollment page shown below and submit the request to the CA for signing. Once the CA sends me the certificate I can download it to a file or directly install it to my certificate store.

To install a CA you have to have a server OS (example: Windows Server 2003 or Windows Server 2008/ R2) and you can add/ install a standalone/ root or an enterprise CA depending on your requirement.

For most commercial usages certificates are purchased from Verisign (http://www.verisign.com/), Thawte (http://www.thawte.com/) etc.

Question 2: How do I encrypt using the public key in the certificate?

[Shamik] Use RSACryptoServiceProvider class.

// Get the certifcate.
X509Certificate2 x509cert = GetCertificateFromStore(«CN=xxx», «MY»); // The second parameter is the store name.

RSACryptoServiceProvider key = null;
key = (RSACryptoServiceProvider)x509cert.PublicKey.Key;
byte[] password = key.Encrypt(dataToDecrypt, false);

where GetCertificateFromStore() is defined as:

private static X509Certificate2 GetCertificateFromStore(string certName, string storename)
<
// Get the certificate store for the current user.
X509Store store = new X509Store(storename, StoreLocation.CurrentUser); // or if you want to get the certificate from the local machine use StoreLocation.LocalMachine
try
<
store.Open(OpenFlags.ReadOnly);
// Place all certificates in an X509Certificate2Collection object.
X509Certificate2Collection certCollection = store.Certificates;

// Find the certificate by its distinguished name.
// The last parameter to Find() is true to allow only valid certificates to be returned from the search; otherwise pass false.
X509Certificate2Collection currentCerts = certCollection.Find(X509FindType.FindBySubjectDistinguishedName, certName, true);
if (currentCerts.Count == 0)
<
return null;
>
// Return the first certificate in the collection, has the right name and is current.
return currentCerts[0];
>
finally
<
store.Close();
>
>

Question 3: How do I transfer the certificate and deploy it with the app?

[Shamik] Transfer where? To other machine? This is not clear. Please see http://technet.microsoft.com/en-us/library/cc738545(WS.10).aspx for importing and exporting certificates.
• However you can save the public/private keys to a XML file.
Example:
RSACryptoServiceProvider key = null;
string PrivateAndPublickey = «»;

if (x509cert.HasPrivateKey)
<
key = (RSACryptoServiceProvider)x509cert.PrivateKey;

PrivateAndPublickey = key.ToXmlString(true); // true to include a public and private RSA key; false to include only the public key.

StreamWriter sw = new StreamWriter(@»C:TempPublicAndPrivate.xml»);
sw.Write(PrivateAndPublickey);
sw.Close();
>

Question 4: Is there a programmatic was to install/deploy this certificate so it is «automatic» without user intervention.

[Shamik] Yes, use the X509Store class to open the respective store of your choice and add the certificate to the store. Reference: http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509store.aspx

Question 5: Finally what APIs are available to get the private key and subsequently using it to decrypt the password?

[Shamik] Use RSACryptoServiceProvider class.

// Get the certifcate.
X509Certificate2 x509cert = GetCertificateFromStore(«CN=xxx», «MY»);

RSACryptoServiceProvider key = null;
if (x509cert.HasPrivateKey)
<
key = (RSACryptoServiceProvider)x509cert.PrivateKey;

byte[] password = key.Decrypt(dataToDecrypt, false);
>

where GetCertificateFromStore() is defined above.

Источник

При расшифровке текста с помощью 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 задайте свой вопрос.

See more:

Hi all,

I have developed a web service that encrypts a connection string and passes back the encrypted string to a console application (test purposes).

The web service runs on a different PC than the console application. But I keep receiving the following exception message: Error occurred while decoding OAEP padding.

When I run the encrypt and decrypt code on the same PC everything works just fine?!?! Both the web service and the console application makes use of the same KeyContainerName.

Encryption Method:

private static string EncryptString(string inputString, int dwKeySize, string keyContainerName)
{
    
    CspParameters cspParams = new CspParameters();
    cspParams.KeyContainerName = keyContainerName;
    RSACryptoServiceProvider rsaCryptoServiceProvider = new RSACryptoServiceProvider(dwKeySize, cspParams);
    
    int keySize = dwKeySize / 8;
    byte[] bytes = Encoding.UTF32.GetBytes(inputString);
    
    
    
    
    int maxLength = keySize - 42;
    int dataLength = bytes.Length;
    int iterations = dataLength / maxLength;
    StringBuilder stringBuilder = new StringBuilder();
    for (int i = 0; i <= iterations; i++)
    {
        byte[] tempBytes = new byte[(dataLength - maxLength * i > maxLength) ? maxLength : dataLength - maxLength * i];
        Buffer.BlockCopy(bytes, maxLength * i, tempBytes, 0, tempBytes.Length);
        byte[] encryptedBytes = rsaCryptoServiceProvider.Encrypt(tempBytes, true);
        
        
        
        
        
        
        
        
        
        stringBuilder.Append(Convert.ToBase64String(encryptedBytes));
    }
    return stringBuilder.ToString();
}

Decryption Method:

private static string DecryptString(string inputString, int dwKeySize, string keyContainerName)
{
    
    CspParameters cspParams = new CspParameters();
    cspParams.KeyContainerName = keyContainerName;
    RSACryptoServiceProvider rsaCryptoServiceProvider = new RSACryptoServiceProvider(dwKeySize, cspParams);
    int base64BlockSize = ((dwKeySize / 8) % 3 != 0) ? (((dwKeySize / 8) / 3) * 4) + 4 : ((dwKeySize / 8) / 3) * 4;
    int iterations = inputString.Length / base64BlockSize;
    ArrayList arrayList = new ArrayList();
    for (int i = 0; i < iterations; i++)
    {
        byte[] encryptedBytes = Convert.FromBase64String(inputString.Substring(base64BlockSize * i, base64BlockSize));
        
        
        
        
        
        
        Array.Reverse(encryptedBytes);
        arrayList.AddRange(rsaCryptoServiceProvider.Decrypt(encryptedBytes, true));
    }
    return Encoding.UTF32.GetString(arrayList.ToArray(Type.GetType("System.Byte")) as byte[]);
}

Can anyone please assist me in the matter?
Many thanks in advance.
Kind regards,

I am making a class that can decrypt the incoming message and verify that the content hasnt changed. For this I have access to the signature, message and the public key. Here are the values:

Signature: YyZbWivunozg9zosPkRoBLv+yOnsaZb39E5mnHSgPtFdbIX7KA8E1xibw5qpM3hog1dB99h6mIe45zh/Ezn+42N2+twXJMedkvJnbv/DJLr7KAISmkKeRGuA3WQt/KA6v9W+g1FTQhXOzNnUUWLKuucs6KKdg0FrS2fHi4+KYQM= 
Public Key (Base64): LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS1NSUdmTUEwR0NTcUdTSWIzRFFFQkFRVUFBNEdOQURDQmlRS0JnUUM4TlpkLzhUYUxSMStyT0JYRjdGYzZ2RFA0blRUdTlQNmVjcDd2YzRhTk1pVUorRXM2b2YrRFNvY25wL0drazJVa0k5OHlmVTZwMHNTa3NEcWV1R0hwc1AwaS9oYnlRYlM5RVBreW5HT1VicVpnRSt1SVN0SHVyd2ozaFJKQ1ZkbktKWkxVRVYvSDZCM3Z0SGZITG5GemIrd0E4VkhPeWlEWjVZenp3RHRoR1FJREFRQUItLS0tLUVORCBQVUJMSUMgS0VZLS0tLS0= 

With these values and hash method SHA 256 Im trying to verify the message. This is my current code.

using System;
using System.Security.Cryptography;
using System.Text;

namespace RestAPI_TheCircle.Core.HTTP.REST.API.Validation
{
    public class RequestValidation
    {
        public bool ValidateIncomingRequest(string signature, string message, string publicKey)
        {            
            Console.WriteLine("Signature: " + signature);
            Console.WriteLine("Message: " + message);
            Console.WriteLine("Public Key: " + publicKey);

            string hashedMessage = ComputeSha256Hash(message);
            byte[] byteKey = getByteArray(publicKey);
            byte[] byteSignature = getByteArrayS(signature);
            byte[] byteDecrypted = decryptSignature(byteKey, byteSignature);
            string decrypted = getStringValue(byteDecrypted);

            Console.WriteLine("Hashed message: " + hashedMessage);
            Console.WriteLine("Decrypted signature: " + decrypted);

            return true;
        }

        private string ComputeSha256Hash(string rawData)
        {
            using (SHA256 sha256Hash = SHA256.Create())
            {
                byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(rawData));
                
                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < bytes.Length; i++)
                {
                    builder.Append(bytes[i].ToString("x2"));
                }
                return builder.ToString();
            }
        }

        private byte[] getByteArray(string data)
        {
            byte[] keyBytes = Convert.FromBase64String(data);
            return keyBytes;
        }

        private byte[] getByteArrayS(string data)
        {
            byte[] keyBytes = Encoding.ASCII.GetBytes(data);
            return keyBytes;
        }

        private byte[] decryptSignature(byte[] key, byte[] signature)
        {
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
            RSAParameters RSAKeyInfo = RSA.ExportParameters(false);
            RSAKeyInfo.Modulus = key;
            RSA.ImportParameters(RSAKeyInfo);
            byte[] decrypted = RSA.Decrypt(signature, true);
            return decrypted;
        }

        private string getStringValue(byte[] data)
        {
            string value = data.ToString();
            return value;
        }
    }
}

This code give the following error:

System.Security.Cryptography.CryptographicException: Er is een fout opgetreden bij het decoderen van OAEP-opvulling.rn   bij System.Security.Cryptography.RSACryptoServiceProvider.DecryptKey(SafeKeyHandle pKeyContext, Byte[] pbEncryptedKey, Int32 cbEncryptedKey, Boolean fOAEP, ObjectHandleOnStack ohRetDecryptedKey)rn   bij System.Security.Cryptography.RSACryptoServiceProvider.Decrypt(Byte[] rgb, Boolean fOAEP)rn   bij RestAPI_TheCircle.Core.HTTP.REST.API.Validation.RequestValidation.decryptSignature(Byte[] key, Byte[] signature) in D:\GitDesktop\the-circle-server\RestAPI_TheCircle\RestAPI_TheCircle\Core\Extensions\HTTP\REST\API\Validation\RequestValidation.cs:regel 60rn   bij RestAPI_TheCircle.Core.HTTP.REST.API.Validation.RequestValidation.ValidateIncomingRequest(String signature, String message, String publicKey) in D:\GitDesktop\the-circle-server\RestAPI_TheCircle\RestAPI_TheCircle\Core\Extensions\HTTP\REST\API\Validation\RequestValidation.cs:regel 18rn   bij RestAPI_TheCircle.Core.HTTP.REST.Stream.StreamRoutes.StreamViewerRating(IHttpContext context) in D:\GitDesktop\the-circle-server\RestAPI_TheCircle\RestAPI_TheCircle\Core\Extensions\HTTP\REST\Stream\StreamRoutes.cs:regel 537",
        "Message": "Er is een fout opgetreden bij het decoderen van OAEP-opvulling.

Error occurred while decoding OAEP padding

I want to eventually compare the hashed message with the decrypted signature to check if theyre the same (they should).

What am I doing wrong here? Any help would be appreciated.

Staff

Rank: #42

Hi Neil,

Usually that error occurs when we are using the wrong keystore (ie, private key) to decrypt the assertion.If before it was working, or in the past ADFS was not encrypting the assertion, or the configured certificates changed. However would say to go to IdP component, export the sp_metadata xml file and import it again on ADFS to refresh the configuration regarding this Sp client.

Regards

Telmo Martins wrote:

Hi Neil,

Usually that error occurs when we are using the wrong keystore (ie, private key) to decrypt the assertion.If before it was working, or in the past ADFS was not encrypting the assertion, or the configured certificates changed. However would say to go to IdP component, export the sp_metadata xml file and import it again on ADFS to refresh the configuration regarding this Sp client.

Regards

Hi Telmo,

Thanks the guy who looks after the ADFS won’t be available until tomorrow , I will get him to try it and I will report back then.

Forgot to Attach Keystore

autogen_keystore_024220_passwd_P931569.zip

Staff

Rank: #42

Hi Neil,

Usually that error occurs when we are using the wrong keystore (ie, private key) to decrypt the assertion.If before it was working, or in the past ADFS was not encrypting the assertion, or the configured certificates changed. However would say to go to IdP component, export the sp_metadata xml file and import it again on ADFS to refresh the configuration regarding this Sp client.

Regards

Telmo Martins wrote:

Hi Neil,

Usually that error occurs when we are using the wrong keystore (ie, private key) to decrypt the assertion.If before it was working, or in the past ADFS was not encrypting the assertion, or the configured certificates changed. However would say to go to IdP component, export the sp_metadata xml file and import it again on ADFS to refresh the configuration regarding this Sp client.

Regards

Hi Telmo,

Thanks the guy who looks after the ADFS won’t be available until tomorrow , I will get him to try it and I will report back then.

Hi,

Issue is solved, seems when ADFS issues the Federation.xml it can issue expired certificates even though active ones are present. Security Guy had to physically delete the old certs from adfs then the federation.xml when applied had the correct certificates and it worked

Thanks

Понравилась статья? Поделить с друзьями:
  • Error occurred when installing package pygame
  • Error occurred when installing package pycharm как исправить
  • Error occurred when installing package pandas
  • Error occurred when installing package numpy
  • Error occurred when installing package dlib pycharm