Search Results

Search found 37 results on 2 pages for 'rsacryptoserviceprovider'.

Page 1/2 | 1 2  | Next Page >

  • How do I manually Dispose RSACryptoServiceProvider?

    - by phq
    I have read on MSDN(see Important note) that RSACryptoServiceProvider must be disposed. They give the example: using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider()) Now I'm trying to include RSACryptoServiceProvider into MyClass making use of it in several Methods. With this setup I cannot use the using statement. Instead I try to call the .Dispose() Method of the RSACryptoServiceProvider object at a suitable time but then I get the compile error message: `System.Security.Cryptography.AsymmetricAlgorithm.Dispose(bool)' is inaccessible due to its protection level Is RSACryptoServiceProvider not supposed to be used longer than one function call(using the using statement)? How can I fix this, is not making the Dispose call an option?

    Read the article

  • [C#] RSACryptoServiceProvider Using the Public Key to decrypt Private Key encrypted Data ?

    - by prixone
    Hello, i went thru lots and lots of searchs and results and pages considering this matter but havent found the solution yet. Like i described in the title i want to decrypt data using my Public Key which is something i am able to do with my PHP code, my certificate is generated from my PHP page. Here is a sample of what i am trying: public string Decrypt(string data) { X509Certificate2 cert = new X509Certificate2(); cert.Import(Encoding.ASCII.GetBytes(webApi["PublicDefaultKey"])); RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert.PublicKey.Key; byte[] ciphertextBytes = Convert.FromBase64String(data); byte[] plaintextBytes = rsa.Decrypt(ciphertextBytes, false); return System.Text.Encoding.UTF8.GetString(plaintextBytes); } MessageBox.Show(Decrypt("pgcl93TpVfyHubuRlL72/PZN0nA4Q+HHx8Y15qGvUyTNpI6y7J13YG07ZVEyB7Dbgx63FSw9vEw1D1Z3bvNbI0gqalVfKTfHv5tKVc7Y6nQwQYwoODpUhVpa/K9OP1lqx4esnxqwJx95G0rqgJTdS+Yo773s5UcJrHzzbsX2z+w=")); here is the public key i am using for tests: -----BEGIN CERTIFICATE----- MIIDxDCCAy2gAwIBAgIBADANBgkqhkiG9w0BAQUFADCBozELMAkGA1UEBhMCVUsx EDAOBgNVBAgTB0VuZ2xhbmQxDzANBgNVBAcTBkxvbmRvbjESMBAGA1UEChMJTU1P Q2xldmVyMSMwIQYDVQQLExpNTU9DbGV2ZXIgRGV2ZWxvcGVyJ3MgVGVhbTESMBAG A1UEAxMJTU1PQ2xldmVyMSQwIgYJKoZIhvcNAQkBFhVzdXBwb3J0QG1tb2NsZXZl ci5jb20wHhcNMTAwNTE2MTkxNDQ4WhcNMTEwNTE2MTkxNDQ4WjCBozELMAkGA1UE BhMCVUsxEDAOBgNVBAgTB0VuZ2xhbmQxDzANBgNVBAcTBkxvbmRvbjESMBAGA1UE ChMJTU1PQ2xldmVyMSMwIQYDVQQLExpNTU9DbGV2ZXIgRGV2ZWxvcGVyJ3MgVGVh bTESMBAGA1UEAxMJTU1PQ2xldmVyMSQwIgYJKoZIhvcNAQkBFhVzdXBwb3J0QG1t b2NsZXZlci5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMozHr17PL+N seZyadobUmpIV+RKqmRUGX0USIdj0i0yvwvltu3AIKAyRhGz16053jZV2WeglCEj qfiewF9sYTAAoIVGtdd/sZvO4uUcng9crSzDo0CrEPs/Tn5SunmlmyFlZfdlqpAM XXLno/HMo9cza0CrcMnRokaTiu8szBeBAgMBAAGjggEEMIIBADAdBgNVHQ4EFgQU zip+3/hBIpjvdcSoWQ2rW+xDEWAwgdAGA1UdIwSByDCBxYAUzip+3/hBIpjvdcSo WQ2rW+xDEWChgamkgaYwgaMxCzAJBgNVBAYTAlVLMRAwDgYDVQQIEwdFbmdsYW5k MQ8wDQYDVQQHEwZMb25kb24xEjAQBgNVBAoTCU1NT0NsZXZlcjEjMCEGA1UECxMa TU1PQ2xldmVyIERldmVsb3BlcidzIFRlYW0xEjAQBgNVBAMTCU1NT0NsZXZlcjEk MCIGCSqGSIb3DQEJARYVc3VwcG9ydEBtbW9jbGV2ZXIuY29tggEAMAwGA1UdEwQF MAMBAf8wDQYJKoZIhvcNAQEFBQADgYEAyU6RLifBXSyQUkBFnTcI6h5ryujh+6o6 eQ1wuPOPmRdYJZuWx/5mjMpIF13sYlNorcOv5WaEnp8/Jfuwc9h/jXlcujser0UE WoaaFwK81O801Xkv2zEm2UUWiOabrGTIT4FVy3gCUXJYjaCnvfSdmkfLJOQxNHVt 4NTMp7IeF60= -----END CERTIFICATE----- by default, the PHP generates the key in PKCS as far as i know, from my C# code i can encrypt using my publick key with out any problems and decrypt it on my php page but so far i was not able to decrypt data sent from my php page encrypted with the private key which is something i can do on my php... i did like some help to understand what i am doing wrong... the error when i run the functions is "bad data" at rsa.Decrypt(ciphertextBytes, false); which i couldnt found anymore information at it... Thanks for any and all the help :)

    Read the article

  • File not found on RSACryptoServiceProvider, service account permissions?

    - by Ben Scheirman
    Our web service wraps around a third party library that contains the following code. We are using an Active Directory service account in the IIS 6 app pool (no interactive login abilities). Our service fails with the error “The system cannot find the file specified”. We’ve traced the error to the “RSACryptoServiceProvider provider = new RSACryptoServiceProvider();”. The third party assembly depends on a x509 file based certificate for its encryption process and the Service Account has Read / Write access to the keys folder. Additionally, the service account has Read, Write, Modify rights to “C:\Documents and Settings\All Users\Application Data\Microsoft\Crypto\RSA\MachineKeys”. Code: StringBuilder builder = new StringBuilder(publicKeyData); builder.Replace("-----BEGIN CERTIFICATE-----", ""); builder.Replace("-----END CERTIFICATE-----", ""); X509Certificate2 certificate = new X509Certificate2( Convert.FromBase64String(builder.ToString())); string xmlString = certificate.PublicKey.Key.ToXmlString(false); RSACryptoServiceProvider provider = new RSACryptoServiceProvider(); //BOOM CspKeyContainerInfo containerInfo = provider.CspKeyContainerInfo; provider.PersistKeyInCsp = false; provider.FromXmlString(xmlString); loadedKeys.Add(key, provider); provider2 = provider; We cracked open FileMon and noticed that there is a FILE NOT FOUND for that AppPool, followed by another SUCCESS for the same exact file. I'm out of my element here, anybody have an idea as to why we're seeing this?

    Read the article

  • RSACryptoServiceProvider CryptographicException System Cannot Find the File Specified under ASP.NET

    - by Will Hughes
    I have an application which is making use of the RSACryptoServiceProvider to decrypt some data using a known private key (stored in a variable). When the IIS Application Pool is configured to use Network Service, everything runs fine. However, when we configure the IIS Application Pool to run the code under a different Identity, we get the following: System.Security.Cryptography.CryptographicException: The system cannot find the file specified. at System.Security.Cryptography.Utils.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer) at System.Security.Cryptography.RSACryptoServiceProvider.ImportParameters(RSAParameters parameters) at System.Security.Cryptography.RSA.FromXmlString(String xmlString) The code is something like this: byte[] input; byte[] output; string private_key_xml; var provider = new System.Cryptography.RSACryptoServiceProvider(this.m_key.Key_Size); provider.FromXmlString(private_key_xml); // Fails Here when Application Pool Identity != Network Service ouput = provider.Decrypt(input, false); // False = Use PKCS#1 v1.5 Padding There are resources which attempt to answer it by stating that you should give the user read access to the machine key store - however there is no definitive answer to solve this issue. Environment: IIS 6.0, Windows Server 2003 R2, .NET 3.5 SP1

    Read the article

  • How to store a public key in a machine-level RSA key container

    - by Andrew Kimball
    I'm having a problem using a machine level RSA key container when storing only the public key of a public/private key pair. The following code creates a public/private pair and extracts the public key from that pair. The pair and the public key are stored in separate key containers. The keys are then obtained from those key containers at which point they should be the same as the keys going into the containers. The code works when CspProviderFlags.UseDefaultKeyContainer is specified for CspParameters.Flags (i.e. the key read back out from the PublicKey container is the same), but when CspProviderFlags.UseMachineKeyStore is specified for CspParameters.Flags the key read back from PublicKey is different. Why is the behaviour different, and what do I need to do differently to retrieve the public key from a machine-level RSA key container? var publicPrivateRsa = new RSACryptoServiceProvider(new CspParameters() { KeyContainerName = "PublicPrivateKey", Flags = CspProviderFlags.UseMachineKeyStore //Flags = CspProviderFlags.UseDefaultKeyContainer } ) { PersistKeyInCsp = true, }; var publicRsa = new RSACryptoServiceProvider(new CspParameters() { KeyContainerName = "PublicKey", Flags = CspProviderFlags.UseMachineKeyStore //Flags = CspProviderFlags.UseDefaultKeyContainer } ) { PersistKeyInCsp = true }; //Export the key. publicRsa.ImportParameters(publicPrivateRsa.ExportParameters(false)); Console.WriteLine(publicRsa.ToXmlString(false)); Console.WriteLine(publicPrivateRsa.ToXmlString(false)); //Dispose those two CSPs. using (publicRsa) { publicRsa.Clear(); } using (publicPrivateRsa) { publicRsa.Clear(); } publicPrivateRsa = new RSACryptoServiceProvider(new CspParameters() { KeyContainerName = "PublicPrivateKey", Flags = CspProviderFlags.UseMachineKeyStore //Flags = CspProviderFlags.UseDefaultKeyContainer } ); publicRsa = new RSACryptoServiceProvider(new CspParameters() { KeyContainerName = "PublicKey", Flags = CspProviderFlags.UseMachineKeyStore //Flags = CspProviderFlags.UseDefaultKeyContainer } ); Console.WriteLine(publicRsa.ToXmlString(false)); Console.WriteLine(publicPrivateRsa.ToXmlString(false)); using (publicRsa) { publicRsa.Clear(); } using (publicPrivateRsa) { publicRsa.Clear(); }

    Read the article

  • CryptographicException: Unknown Error '80007005'. when calling RSACryptoServiceProvider.Decrypt() in

    - by zensunnit
    Hello, I am trying to use the RSACryptoServiceProvider to encrypt/decrypt. Encrypting works fine, but the Decrypt method() throws an exception with the message: Unknown Error '80007005'. This is the code: Byte[] plainData = encoding.GetBytes(plainText); Byte[] encryptedData; RSAParameters rsap1; Byte[] decryptedData; using (RSACryptoServiceProvider rsa1 = new RSACryptoServiceProvider()) { encryptedData = rsa1.Encrypt(plainData, false); rsap1 = rsa1.ExportParameters(false); } using (RSACryptoServiceProvider rsa2 = new RSACryptoServiceProvider()) { rsa2.ImportParameters(rsap1); decryptedData = rsa2.Decrypt(encryptedData, false); } decryptedText = encoding.GetString(decryptedData, 0, decryptedData.Length); Is anyone aware of a workaround? Thanks!

    Read the article

  • How to encrypt Amazon CloudFront signature for private content access using canned policy

    - by Chet
    Has anyone using .net actually worked out how to successfully sign a signature to use with CloudFront private content? After a couple of days of attempts all I can get is Access Denied. I have been working with variations of the following code and also tried using OpenSSL.Net and AWSSDK but that does not have a sign method for RSA-SHA1 yet. The signature (data) looks like this {"Statement":[{"Resource":"http://xxxx.cloudfront.net/xxxx.jpg","Condition":?{"DateLessThan":?{"AWS:EpochTime":1266922799}}}]} This method attempts to sign the signature for use in the canned url. So of the variations have included chanding the padding used in the has and also reversing the byte[] before signing as apprently OpenSSL do it this way. public string Sign(string data) { using (SHA1Managed SHA1 = new SHA1Managed()) { RSACryptoServiceProvider provider = new RSACryptoServiceProvider(); RSACryptoServiceProvider.UseMachineKeyStore = false; // Amazon PEM converted to XML using OpenSslKey provider.FromXmlString("<RSAKeyValue><Modulus>....."); byte[] plainbytes = System.Text.Encoding.UTF8.GetBytes(data); byte[] hash = SHA1.ComputeHash(plainbytes); //Array.Reverse(sig); // I have see some examples that reverse the hash byte[] sig = provider.SignHash(hash, "SHA1"); return Convert.ToBase64String(sig); } } Its useful to note that I have verified the content is setup correctly in S3 and CloudFront by generating a CloudFront canned policy url using my CloudBerry Explorer. How do they do it? Any ideas would be much appreciated. Thanks

    Read the article

  • RSA_sign and RSACryptoProvider.VerifySignature

    - by Miky D
    I'm trying to get up to speed on how to get some code that uses OpenSSL for cryptography, to play nice with another program that I'm writing in C#, using the Microsoft cryptography providers available in .NET. More to the point, I'm trying to have the C# program verify an RSA message signature generated by the OpenSSL code. The code that generates the signature looks something like this: // Code in C, using the OpenSSL RSA implementation char msgToSign[] = "Hello World"; // the message to be signed char signature[RSA_size(rsa)]; // buffer that will hold signature int slen = 0; // will contain signature size // rsa is an OpenSSL RSA context, that's loaded with the public/private key pair memset(signature, 0, sizeof(signature)); RSA_sign(NID_sha1 , (unsigned char*)msgToSign , strlen(msgToSign) , signature , &slen , rsa); // now signature contains the message signature // and can be verified using the RSA_verify counterpart // .. I would like to verify the signature in C# In C#, I would do the following: import the other side's public key into an RSACryptoServiceProvider object receive the message and it's signature try to verify the signature I've got the first two parts working (I've verified that the public key is loading properly because I managed to send an RSA encrypted text from the C# code to the OpenSSL code in C and successfully have it decrypted) In order to verify the signature in C#, I've tried using the: VerifySignature method of the RSACryptoServiceProvider but that didn't work. And digging around the internet I was only able to find some vague information pointing out that .NET uses a different method for generating the signature than OpenSSL does. So, does anybody know how to accomplish this?

    Read the article

  • RSA Encryption C#

    - by Ryan
    Hi guys, I have a class which in C# doing RSA encryption where I used the default RSACryptoServiceProvider class. But I have a concern regarding the following; If you have the word hello for an input and the encrypted string is returned as ABCDE, if you perform another encrypt operation on the input hello, using the same keys (public and private) for the RSA will the output be again ABCDE? Thanks in advance

    Read the article

  • Web.config Encryption Error

    - by BKarms
    Having problem with encryption. I gave full permissions to all users to RSA folders. I did C:\>aspnet_regiis -pe "appSettings" -location "web.config" -prov "RsaProtectedCo nfigurationProvider" Encrypting configuration section... An error occurred executing the configuration section handler for appSettings. Failed to encrypt the section 'appSettings' using provider 'RsaProtectedConfigur ationProvider'. Error message from the provider: Object already exists. Failed! Then I did C:\>aspnet_regiis -pa "NetFrameworkConfigurationKey" "administrator" Adding ACL for access to the RSA Key container... The RSA key container was not found. Failed! Followed by C:\>aspnet_regiis -pc "NetFrameworkConfigurationKey" -exp Creating RSA Key container... The RSA key container could not be opened. Failed! Nothing is working for me. Can anyone help? Thanks

    Read the article

  • The RSA key container could not be opened

    - by TenaciousImpy
    Hi, I've been developing an ASP.NET site on an older machine running XP home. I recently got a new Win 7 PC and moved all my project files across. When I try and run the project, I get this error message: "Failed to decrypt using provider 'MyRsaProtectedConfigurationProvider'. Error message from the provider: The RSA key container could not be opened." I realised that I encrypted parts of my web.config file using a RSA encryption. This is where the problem now lies. I'm not sure how to get that key working again so that I can use it on my new machine. I exported the key from the older machine and imported it using: aspnet_regiis -pi "RSAProviderName" "C:\RSA_configkey.xml" This was imported successfully. I then ran the project, but the same error message came up. I figured it might be a permission thing, so I ran: aspnet_regiis -pa "RSAProviderName" "\Desktop" -full This was also successful, but I still get the error. From reading around, I've seen people use "ASPNET" instead of "\Desktop" (Desktop is my machine name). However, when I try and use "ASPNET", I get: No mapping between account name and security IDs was done. <Exception from HRESULT = 0x80070534 I can't work on the project until this is fixed, so any help is much appreciated. Thanks!

    Read the article

  • RSA Encrypt / Decrypt Problem in .NET

    - by Brendon Randall
    I'm having a problem with C# encrypting and decrypting using RSA. I have developed a web service that will be sent sensitive financial information and transactions. What I would like to be able to do is on the client side, Encrypt the certain fields using the clients RSA Private key, once it has reached my service it will decrypt with the clients public key. At the moment I keep getting a "The data to be decrypted exceeds the maximum for this modulus of 128 bytes." exception. I have not dealt much with C# RSA cryptography so any help would be greatly appreciated. This is the method i am using to generate the keys private void buttonGenerate_Click(object sender, EventArgs e) { string secretKey = RandomString(12, true); CspParameters param = new CspParameters(); param.Flags = CspProviderFlags.UseMachineKeyStore; SecureString secureString = new SecureString(); byte[] stringBytes = Encoding.ASCII.GetBytes(secretKey); for (int i = 0; i < stringBytes.Length; i++) { secureString.AppendChar((char)stringBytes[i]); } secureString.MakeReadOnly(); param.KeyPassword = secureString; RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(param); rsaProvider = (RSACryptoServiceProvider)RSACryptoServiceProvider.Create(); rsaProvider.KeySize = 1024; string publicKey = rsaProvider.ToXmlString(false); string privateKey = rsaProvider.ToXmlString(true); Repository.RSA_XML_PRIVATE_KEY = privateKey; Repository.RSA_XML_PUBLIC_KEY = publicKey; textBoxRsaPrivate.Text = Repository.RSA_XML_PRIVATE_KEY; textBoxRsaPublic.Text = Repository.RSA_XML_PUBLIC_KEY; MessageBox.Show("Please note, when generating keys you must sign on to the gateway\n" + " to exhange keys otherwise transactions will fail", "Key Exchange", MessageBoxButtons.OK, MessageBoxIcon.Information); } Once i have generated the keys, i send the public key to the web service which stores it as an XML file. Now i decided to test this so here is my method to encrypt a string public static string RsaEncrypt(string dataToEncrypt) { string rsaPrivate = RSA_XML_PRIVATE_KEY; CspParameters csp = new CspParameters(); csp.Flags = CspProviderFlags.UseMachineKeyStore; RSACryptoServiceProvider provider = new RSACryptoServiceProvider(csp); provider.FromXmlString(rsaPrivate); ASCIIEncoding enc = new ASCIIEncoding(); int numOfChars = enc.GetByteCount(dataToEncrypt); byte[] tempArray = enc.GetBytes(dataToEncrypt); byte[] result = provider.Encrypt(tempArray, true); string resultString = Convert.ToBase64String(result); Console.WriteLine("Encrypted : " + resultString); return resultString; } I do get what seems to be an encrypted value. In the test crypto web method that i created, i then take this encrypted data, try and decrypt the data using the clients public key and send this back in the clear. But this is where the exception is thrown. Here is my method responsible for this. public string DecryptRSA(string data, string merchantId) { string clearData = null; try { CspParameters param = new CspParameters(); param.Flags = CspProviderFlags.UseMachineKeyStore; RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(param); string merchantRsaPublic = GetXmlRsaKey(merchantId); rsaProvider.FromXmlString(merchantRsaPublic); byte[] asciiString = Encoding.ASCII.GetBytes(data); byte[] decryptedData = rsaProvider.Decrypt(asciiString, false); clearData = Convert.ToString(decryptedData); } catch (CryptographicException ex) { Log.Error("A cryptographic error occured trying to decrypt a value for " + merchantId, ex); } return clearData; } If anyone could help me that would be awesome, as i have said i have not done much with C# RSA encryption/decryption.

    Read the article

  • C# RSA Encrypt / Decrypt Problem

    - by Brendon Randall
    Hi All, Im having a problem with C# encrypting and decrypting using RSA. I have developed a web service that will be sent sensitive financial information and transactions. What I would like to be able to do is on the client side, Encrypt the certain fields using the clients RSA Private key, once it has reached my service it will decrypt with the clients public key. At the moment I keep getting a "The data to be decrypted exceeds the maximum for this modulus of 128 bytes." exception. I have not dealt much with C# RSA cryptography so any help would be greatly appreciated. This is the method i am using to generate the keys private void buttonGenerate_Click(object sender, EventArgs e) { string secretKey = RandomString(12, true); CspParameters param = new CspParameters(); param.Flags = CspProviderFlags.UseMachineKeyStore; SecureString secureString = new SecureString(); byte[] stringBytes = Encoding.ASCII.GetBytes(secretKey); for (int i = 0; i < stringBytes.Length; i++) { secureString.AppendChar((char)stringBytes[i]); } secureString.MakeReadOnly(); param.KeyPassword = secureString; RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(param); rsaProvider = (RSACryptoServiceProvider)RSACryptoServiceProvider.Create(); rsaProvider.KeySize = 1024; string publicKey = rsaProvider.ToXmlString(false); string privateKey = rsaProvider.ToXmlString(true); Repository.RSA_XML_PRIVATE_KEY = privateKey; Repository.RSA_XML_PUBLIC_KEY = publicKey; textBoxRsaPrivate.Text = Repository.RSA_XML_PRIVATE_KEY; textBoxRsaPublic.Text = Repository.RSA_XML_PUBLIC_KEY; MessageBox.Show("Please note, when generating keys you must sign on to the gateway\n" + " to exhange keys otherwise transactions will fail", "Key Exchange", MessageBoxButtons.OK, MessageBoxIcon.Information); } Once i have generated the keys, i send the public key to the web service which stores it as an XML file. Now i decided to test this so here is my method to encrypt a string public static string RsaEncrypt(string dataToEncrypt) { string rsaPrivate = RSA_XML_PRIVATE_KEY; CspParameters csp = new CspParameters(); csp.Flags = CspProviderFlags.UseMachineKeyStore; RSACryptoServiceProvider provider = new RSACryptoServiceProvider(csp); provider.FromXmlString(rsaPrivate); ASCIIEncoding enc = new ASCIIEncoding(); int numOfChars = enc.GetByteCount(dataToEncrypt); byte[] tempArray = enc.GetBytes(dataToEncrypt); byte[] result = provider.Encrypt(tempArray, true); string resultString = Convert.ToBase64String(result); Console.WriteLine("Encrypted : " + resultString); return resultString; } I do get what seems to be an encrypted value. In the test crypto web method that i created, i then take this encrypted data, try and decrypt the data using the clients public key and send this back in the clear. But this is where the exception is thrown. Here is my method responsible for this. public string DecryptRSA(string data, string merchantId) { string clearData = null; try { CspParameters param = new CspParameters(); param.Flags = CspProviderFlags.UseMachineKeyStore; RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(param); string merchantRsaPublic = GetXmlRsaKey(merchantId); rsaProvider.FromXmlString(merchantRsaPublic); byte[] asciiString = Encoding.ASCII.GetBytes(data); byte[] decryptedData = rsaProvider.Decrypt(asciiString, false); clearData = Convert.ToString(decryptedData); } catch (CryptographicException ex) { Log.Error("A cryptographic error occured trying to decrypt a value for " + merchantId, ex); } return clearData; If anyone could help me that would be awesome, as i have said i have not done much with C# RSA encryption/decryption. Thanks in advance

    Read the article

  • c# How to Verify Signature, Loading PUBLIC KEY From PEM file?

    - by bbirtle
    I'm posting this in the hope it saves somebody else the hours I lost on this really stupid problem involving converting formats of public keys. If anybody sees a simpler solution or a problem, please let me know! The eCommerce system I'm using sends me some data along with a signature. They also give me their public key in .pem format. The .pem file looks like this: -----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDe+hkicNP7ROHUssGNtHwiT2Ew HFrSk/qwrcq8v5metRtTTFPE/nmzSkRnTs3GMpi57rBdxBBJW5W9cpNyGUh0jNXc VrOSClpD5Ri2hER/GcNrxVRP7RlWOqB1C03q4QYmwjHZ+zlM4OUhCCAtSWflB4wC Ka1g88CjFwRw/PB9kwIDAQAB -----END PUBLIC KEY----- Here's the magic code to turn the above into an "RSACryptoServiceProvider" which is capable of verifying the signature. Uses the BouncyCastle library, since .NET apparently (and appallingly cannot do it without some major headaches involving certificate files): RSACryptoServiceProvider thingee; using (var reader = File.OpenText(@"c:\pemfile.pem")) { var x = new PemReader(reader); var y = (RsaKeyParameters)x.ReadObject(); thingee = (RSACryptoServiceProvider)RSACryptoServiceProvider.Create(); var pa = new RSAParameters(); pa.Modulus = y.Modulus.ToByteArray(); pa.Exponent = y.Exponent.ToByteArray(); thingee.ImportParameters(pa); } And then the code to actually verify the signature: var signature = ... //reads from the packet sent by the eCommerce system var data = ... //reads from the packet sent by the eCommerce system var sha = new SHA1CryptoServiceProvider(); byte[] hash = sha.ComputeHash(Encoding.ASCII.GetBytes(data)); byte[] bSignature = Convert.FromBase64String(signature); ///Verify signature, FINALLY: var hasValidSig = thingee.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), bSignature);

    Read the article

  • RSA Decrypting a string in C# which was encrypted with openssl in php 5.3.2

    - by panny
    maybe someone can clear me up. I have been surfing on this a while now. I used openssl from console to create a root certificate for me (privatekey.pem, publickey.pem, mycert.pem, mycertprivatekey.pfx). See the end of this text on how. The problem is still to get a string encrypted on the PHP side to be decrypted on the C# side with RSACryptoServiceProvider. Any ideas? PHP side I used the publickey.pem to read it into php: $server_public_key = openssl_pkey_get_public(file_get_contents("C:\publickey.pem")); // rsa encrypt openssl_public_encrypt("123", $encrypted, $server_public_key); and the privatekey.pem to check if it works: openssl_private_decrypt($encrypted, $decrypted, openssl_get_privatekey(file_get_contents("C:\privatekey.pem"))); Coming to the conclusion, that encryption/decryption works fine on the php side with these openssl root certificate files. C# side In same manner I read the keys into a .net C# console program: X509Certificate2 myCert2 = new X509Certificate2(); RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); try { myCert2 = new X509Certificate2(@"C:\mycertprivatekey.pfx"); rsa = (RSACryptoServiceProvider)myCert2.PrivateKey; } catch (Exception e) { } string t = Convert.ToString(rsa.Decrypt(rsa.Encrypt(test, false), false)); coming to the point, that encryption/decryption works fine on the c# side with these openssl root certificate files. key generation on unix 1) openssl req -x509 -nodes -days 3650 -newkey rsa:1024 -keyout privatekey.pem -out mycert.pem 2) openssl rsa -in privatekey.pem -pubout -out publickey.pem 3) openssl pkcs12 -export -out mycertprivatekey.pfx -in mycert.pem -inkey privatekey.pem -name "my certificate"

    Read the article

  • Decrypting a string in C# which was encrypted with openssl in php 5.3.2

    - by panny
    maybe someone can clear me up. I have been surfing on this a while now. I used openssl from console to create a root certificate for me (privatekey.pem, publickey.pem, mycert.pem, mycertprivatekey.pfx). See the end of this text on how. The problem is still to get a string encrypted on the PHP side to be decrypted on the C# side with RSACryptoServiceProvider. Any ideas? PHP side I used the publickey.pem to read it into php: $server_public_key = openssl_pkey_get_public(file_get_contents("C:\publickey.pem")); // rsa encrypt openssl_public_encrypt("123", $encrypted, $server_public_key); and the privatekey.pem to check if it works: openssl_private_decrypt($encrypted, $decrypted, openssl_get_privatekey(file_get_contents("C:\privatekey.pem"))); Coming to the conclusion, that encryption/decryption works fine on the php side with these openssl root certificate files. C# side In same manner I read the keys into a .net C# console program: X509Certificate2 myCert2 = new X509Certificate2(); RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); try { myCert2 = new X509Certificate2(@"C:\mycertprivatekey.pfx"); rsa = (RSACryptoServiceProvider)myCert2.PrivateKey; } catch (Exception e) { } string t = Convert.ToString(rsa.Decrypt(rsa.Encrypt(test, false), false)); coming to the point, that encryption/decryption works fine on the c# side with these openssl root certificate files. key generation on unix 1) openssl req -x509 -nodes -days 3650 -newkey rsa:1024 -keyout privatekey.pem -out mycert.pem 2) openssl rsa -in privatekey.pem -pubout -out publickey.pem 3) openssl pkcs12 -export -out mycertprivatekey.pfx -in mycert.pem -inkey privatekey.pem -name "my certificate"

    Read the article

  • How to Verify Signature, Loading PUBLIC KEY From PEM file?

    - by bbirtle
    I'm posting this in the hope it saves somebody else the hours I lost on this really stupid problem involving converting formats of public keys. If anybody sees a simpler solution or a problem, please let me know! The eCommerce system I'm using sends me some data along with a signature. They also give me their public key in .pem format. The .pem file looks like this: -----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDe+hkicNP7ROHUssGNtHwiT2Ew HFrSk/qwrcq8v5metRtTTFPE/nmzSkRnTs3GMpi57rBdxBBJW5W9cpNyGUh0jNXc VrOSClpD5Ri2hER/GcNrxVRP7RlWOqB1C03q4QYmwjHZ+zlM4OUhCCAtSWflB4wC Ka1g88CjFwRw/PB9kwIDAQAB -----END PUBLIC KEY----- Here's the magic code to turn the above into an "RSACryptoServiceProvider" which is capable of verifying the signature. Uses the BouncyCastle library, since .NET apparently (and appallingly cannot do it without some major headaches involving certificate files): RSACryptoServiceProvider thingee; using (var reader = File.OpenText(@"c:\pemfile.pem")) { var x = new PemReader(reader); var y = (RsaKeyParameters)x.ReadObject(); thingee = (RSACryptoServiceProvider)RSACryptoServiceProvider.Create(); var pa = new RSAParameters(); pa.Modulus = y.Modulus.ToByteArray(); pa.Exponent = y.Exponent.ToByteArray(); thingee.ImportParameters(pa); } And then the code to actually verify the signature: var signature = ... //reads from the packet sent by the eCommerce system var data = ... //reads from the packet sent by the eCommerce system var sha = new SHA1CryptoServiceProvider(); byte[] hash = sha.ComputeHash(Encoding.ASCII.GetBytes(data)); byte[] bSignature = Convert.FromBase64String(signature); ///Verify signature, FINALLY: var hasValidSig = thingee.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), bSignature);

    Read the article

  • Decrypting a string in C# 3.5 which was encrypted with openssl in php 5.3.2

    - by panny
    Hi everyone, maybe someone can clear me up. I have been surfing on this a while now. I used openssl from console to create a root certificate for me (privatekey.pem, publickey.pem, mycert.pem, mycertprivatekey.pfx). See the end of this text on how. The problem is still to get a string encrypted on the PHP side to be decrypted on the C# side with RSACryptoServiceProvider. Any ideas? PHP side I used the publickey.pem to read it into php: $server_public_key = openssl_pkey_get_public(file_get_contents("C:\publickey.pem")); // rsa encrypt openssl_public_encrypt("123", $encrypted, $server_public_key); and the privatekey.pem to check if it works: openssl_private_decrypt($encrypted, $decrypted, openssl_get_privatekey(file_get_contents("C:\privatekey.pem"))); Coming to the conclusion, that encryption/decryption works fine on the php side with these openssl root certificate files. C# side In same manner I read the keys into a .net C# console program: X509Certificate2 myCert2 = new X509Certificate2(); RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); try { myCert2 = new X509Certificate2(@"C:\mycertprivatekey.pfx"); rsa = (RSACryptoServiceProvider)myCert2.PrivateKey; } catch (Exception e) { } string t = Convert.ToString(rsa.Decrypt(rsa.Encrypt(test, false), false)); coming to the point, that encryption/decryption works fine on the c# side with these openssl root certificate files. key generation on unix 1) openssl req -x509 -nodes -days 3650 -newkey rsa:1024 -keyout privatekey.pem -out mycert.pem 2) openssl rsa -in privatekey.pem -pubout -out publickey.pem 3) openssl pkcs12 -export -out mycertprivatekey.pfx -in mycert.pem -inkey privatekey.pem -name "my certificate"

    Read the article

  • Securing a license key with RSA key.

    - by Jesse Knott
    Hello, it's late, I'm tired, and probably being quite dense.... I have written an application that I need to secure so it will only run on machines that I generate a key for. What I am doing for now is getting the BIOS serial number and generating a hash from that, I then am encrypting it using a XML RSA private key. I then sign the XML to ensure that it is not tampered with. I am trying to package the public key to decrypt and verify the signature with, but every time I try to execute the code as a different user than the one that generated the signature I get a failure on the signature. Most of my code is modified from sample code I have found since I am not as familiar with RSA encryption as I would like to be. Below is the code I was using and the code I thought I needed to use to get this working right... Any feedback would be greatly appreciated as I am quite lost at this point the original code I was working with was this, this code works fine as long as the user launching the program is the same one that signed the document originally... CspParameters cspParams = new CspParameters(); cspParams.KeyContainerName = "XML_DSIG_RSA_KEY"; cspParams.Flags = CspProviderFlags.UseMachineKeyStore; // Create a new RSA signing key and save it in the container. RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParams) { PersistKeyInCsp = true, }; This code is what I believe I should be doing but it's failing to verify the signature no matter what I do, regardless if it's the same user or a different one... RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(); //Load the private key from xml file XmlDocument xmlPrivateKey = new XmlDocument(); xmlPrivateKey.Load("KeyPriv.xml"); rsaKey.FromXmlString(xmlPrivateKey.InnerXml); I believe this to have something to do with the key container name (Being a real dumbass here please excuse me) I am quite certain that this is the line that is both causing it to work in the first case and preventing it from working in the second case.... cspParams.KeyContainerName = "XML_DSIG_RSA_KEY"; Is there a way for me to sign/encrypt the XML with a private key when the application license is generated and then drop the public key in the app directory and use that to verify/decrypt the code? I can drop the encryption part if I can get the signature part working right. I was using it as a backup to obfuscate the origin of the license code I am keying from. Does any of this make sense? Am I a total dunce? Thanks for any help anyone can give me in this..

    Read the article

  • C# RSA Cryptographic Algorithm

    - by karthik
    Hi, Is C# 'RSACryptoServiceProvider' cryptographic algorithm is a part of Microsoft- CryptoAPI? Any advantage we have for normal asymmetric encryption by using CryptoAPI over 'RSACryptoServiceProvider' in .Net? I cannot understand the difference between them?And which one is best and safty? Could you please help? Thanks Karthik

    Read the article

  • Is it possible to use pure Encoding and Decoding keys in asymmetric cryptography instead of private

    - by macropas
    Is it possible to use pure Encoding and Decoding keys instead of private and public keys? As I know in .Net asymmetric RSA implementation private key RSAParameters parameters = (new RSACryptoServiceProvider()).ExportParameters(true) is a superset of public key. And using private key we can both encode and decode our data. But I need key only for decoding data. How to do it? I experimented on nulling RSAParameters fields, but RSACryptoServiceProvider object can't import such parameters.

    Read the article

  • Is it possible to use pure Encrypting and Decrypting keys in asymmetric cryptography instead of priv

    - by macropas
    Is it possible to use pure Encrypting and Decrypting keys instead of private and public keys? As I know in .Net asymmetric RSA implementation private key RSAParameters parameters = (new RSACryptoServiceProvider()).ExportParameters(true) is a superset of public key. And using private key we can both encrypt and decrypt our data. But I need key only for decrypting data. How to do it? I experimented on nulling RSAParameters fields, but RSACryptoServiceProvider object can't import such parameters.

    Read the article

  • RSA decrypting data in C# (.NET 3.5) which was encrypted with openssl in php 5.3.2

    - by panny
    Maybe someone can clear me up. I have been surfing on this a while now. Step #1: Create a root certificate Key generation on unix 1) openssl req -x509 -nodes -days 3650 -newkey rsa:1024 -keyout privatekey.pem -out mycert.pem 2) openssl rsa -in privatekey.pem -pubout -out publickey.pem 3) openssl pkcs12 -export -out mycertprivatekey.pfx -in mycert.pem -inkey privatekey.pem -name "my certificate" Step #2: Does root certificate work on php: YES PHP side I used the publickey.pem to read it into php: $publicKey = "file://C:/publickey.pem"; $privateKey = "file://C:/privatekey.pem"; $plaintext = "123"; openssl_public_encrypt($plaintext, $encrypted, $publicKey); $transfer = base64_encode($encrypted); openssl_private_decrypt($encrypted, $decrypted, $privateKey); echo $decrypted; // "123" OR $server_public_key = openssl_pkey_get_public(file_get_contents("C:\publickey.pem")); // rsa encrypt openssl_public_encrypt("123", $encrypted, $server_public_key); and the privatekey.pem to check if it works: openssl_private_decrypt($encrypted, $decrypted, openssl_get_privatekey(file_get_contents("C:\privatekey.pem"))); echo $decrypted; // "123" Coming to the conclusion, that encryption/decryption works fine on the php side with these openssl root certificate files. Step #3: Does root certificate work on .NET: YES C# side In same manner I read the keys into a .net C# console program: X509Certificate2 myCert2 = new X509Certificate2(); RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); try { myCert2 = new X509Certificate2(@"C:\mycertprivatekey.pfx"); rsa = (RSACryptoServiceProvider)myCert2.PrivateKey; } catch (Exception e) { } byte[] test = {Convert.ToByte("123")}; string t = Convert.ToString(rsa.Decrypt(rsa.Encrypt(test, false), false)); Coming to the point, that encryption/decryption works fine on the c# side with these openssl root certificate files. Step #4: Enrypt in php and Decrypt in .NET: !!NO!! PHP side $onett = "123" .... openssl_public_encrypt($onett, $encrypted, $server_public_key); $onettbase64 = base64_encode($encrypted); copy - paste $onettbase64 ("LkU2GOCy4lqwY4vtPI1JcsxgDgS2t05E6kYghuXjrQe7hSsYXETGdlhzEBlp+qhxzTXV3pw+AS5bEg9CPxqHus8fXHOnXYqsd2HL20QSaz+FjZee6Kvva0cGhWkFdWL+ANDSOWRWo/OMhm7JVqU3P/44c3dLA1eu2UsoDI26OMw=") into c# program: C# side byte[] transfered_onettbase64 = Convert.FromBase64String("LkU2GOCy4lqwY4vtPI1JcsxgDgS2t05E6kYghuXjrQe7hSsYXETGdlhzEBlp+qhxzTXV3pw+AS5bEg9CPxqHus8fXHOnXYqsd2HL20QSaz+FjZee6Kvva0cGhWkFdWL+ANDSOWRWo/OMhm7JVqU3P/44c3dLA1eu2UsoDI26OMw="); string k = Convert.ToString(rsa.Decrypt(transfered_onettbase64, false)); // Bad Data exception == Exception while decrypting!!! Any ideas?

    Read the article

  • Issued by DNOA service access token parsing and validating in Java application

    - by Regfor
    I am creating OAuth 2.0 access token using DotNetOpenAuth, like here public AccessTokenResult CreateAccessToken( IAccessTokenRequest accessTokenRequestMessage) { var token = new AuthorizationServerAccessToken(); token.Lifetime = TimeSpan.FromMinutes(10); var signCert = LoadCert(Config.STS_CERT); token.AccessTokenSigningKey = (RSACryptoServiceProvider) signCert.PrivateKey; var encryptCert = LoadCert(Config.SERVICE_CERT); token.ResourceServerEncryptionKey = (RSACryptoServiceProvider) encryptCert.PublicKey.Key; var result = new AccessTokenResult(token); return result; } Token issued by this method looks like: { "access_token": "gAAAAH44atDAyWeu8BFwhLof7rtBRpiZrSlAC0zci8xU81tXHZDVkBX8LXrMLDHDYfimjuSOsdrXQIAY7Xf4JnK1x_fo_JSmvuiA5CvO5JUJNuEmHNSlR4ePO4tBPkOHQnN50DIRJMbHJdQrFZCqqaWz6s0iuvCuTMcTua6J0yaTPQaD9AAAAIAAAADHgef78SHh4-K2aZ87xYRoRFfmQ0lc3ET7Y5vAS7BadLM5btYvmrSkAWsCxhUji92D0LbKgyVkbQuuw5LnRP_zsxe_W_VztTqZ5m9PwJDL6q7McrUfiVQj_XBQqpv2slBeouD0F1k1KjVedR9Pwm7ganz4R7dmeYivnx8f0_isEGBqSZrtnILoit3SOCPyVxmIwizYwLE2bQOtlwVpqtrBMyzc4MVPVyaSiJb2-Lj5tOftEWl0k93Qmr8uzmjDyeCn3TsFX0f_qFgCmxp32_kt4ZTMf4zgmh5yUS1Hy7ERNQxpCIxRTx9yma7JN_K5Pss", "token_type": "bearer", "expires_in": 43200, } I need to know whether Java application will be able to parse and validate token issued in such manner?

    Read the article

  • Why RSA encryption can return different results with C# and Java?

    - by ActioN
    I using: c#: RSACryptoServiceProvider JAVA: KeyFactory.getInstance("RSA")+Cipher I sending public key (exponent + modulus) as byte array from java to c#. It's ok, there is the same bytes. But when i try to encrypt some data with one key in Java and c# - there is different results. Java Key Generation: KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize( Config.CRYPTO_KEY_NUM_BITS ); m_KeyPair = keyGen.genKeyPair(); m_PublicKey = KeyFactory.getInstance("RSA").generatePublic( newX509EncodedKeySpec(m_KeyPair.getPublic().getEncoded())); byte[] exponent = m_PublicKey.getPublicExponent().toByteArray(); byte[] modulus = m_PublicKey.getModulus().toByteArray(); // then sending... C# Key Recieve: // Recieved... m_ExternKey = new RSAParameters(); m_ExternKey.Exponent = exponent; m_ExternKey.Modulus = modulus; m_RsaExtern = new RSACryptoServiceProvider(); m_RsaExtern.ImportParameters(m_ExternKey); byte[] test = m_RsaExtern.Encrypt(bytesToEncrypt, true); and problem is that encrypted bytes is different. Thank you.

    Read the article

1 2  | Next Page >