Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# encryption, got .der and .pem files as input

Tags:

c#

encryption

I am new to c#. I am asked to encrypt a string before I post that information to an external URL. All that I got as input from that external application was a .der file and a .pem file. They asked me to send the encrypted (string) information, so that they can decrypt.

I have read a lot of posts, but couldn't get the exact answer on how can I solve this.

I am using the below code snippet to read the .pem file and create a certificate. But on new X509Certificate2(certBuffer); line throwing me a "cannot find the requested object" error. I am not sure if I'm heading in right direction. If yes, help me figure out the issue. Else show me a way. Thanks in advance!

    var pem = System.IO.File.ReadAllText("C:\\Users\\bvarapr1\\Desktop\\fordsync\\public_qa.pem");
    byte[] certBuffer = GetBytesFromPEM(pem, "PUBLIC KEY");
    var certificate = new X509Certificate2( certBuffer );            
    RSACryptoServiceProvider provider = (RSACryptoServiceProvider)certificate.PrivateKey;
    string testString = "DIGITALMOON";
    string encryptedVIN = RSAEnc(provider, testString);

    byte[] GetBytesFromPEM(string pemString, string section)
    {
        var header = String.Format("-----BEGIN {0}-----", section);
        var footer = String.Format("-----END {0}-----", section);

        var start = pemString.IndexOf(header, StringComparison.Ordinal) + header.Length;
        var end = pemString.IndexOf(footer, start, StringComparison.Ordinal) - start;

        if (start < 0 || end < 0)
        {
            return null;
        }

        return Convert.FromBase64String(pemString.Substring(start, end));
    }
like image 337
user1749959 Avatar asked Oct 16 '12 13:10

user1749959


1 Answers

static void Main(string[] args)
{
    System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider();
    System.Security.Cryptography.RSAParameters rsaParam = rsa.ExportParameters(false);
    rsaParam.Modulus = Convert.FromBase64String(System.IO.File.ReadAllText(@"C:\keys\public_key.pem").Replace("-----BEGIN PUBLIC KEY-----", "").Replace("-----END PUBLIC KEY-----", ""));
    rsa.ImportParameters(rsaParam);

    string msg = "This is a test.";
    byte[] encValue = rsa.Encrypt(Encoding.UTF8.GetBytes(msg), false);

    Console.WriteLine("Message Before Encryption: " + msg);
    Console.WriteLine("Encrypted Message:\r\n" + Convert.ToBase64String(encValue));

    Console.WriteLine("\r\nPress any key to exit.");
    Console.ReadKey();
}
like image 120
Jacob Avatar answered Oct 23 '22 05:10

Jacob