2

Now I have a Public Key(.pem) file and password to encrypt.

-----BEGIN PUBLIC KEY-----

..... ... ...

-----END PUBLIC KEY-----

I would like to get byte[] values for encrypted password. It doesn't get any error but return byte[] values is seem to wrong.

Below are coding current my using one, pls help me or advise me if I'm going wrong.

Really appreciate for your help!!

private static UnicodeEncoding _encoder = new UnicodeEncoding();

public byte[] getPem(string pemFile, string password)
        {
            byte[] encryptData;

            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            byte[] Exponent = { 1, 0, 1 };

            RSAParameters rsaParam = rsa.ExportParameters(false);
            rsaParam.Modulus = Convert.FromBase64String(File.ReadAllText(pemFile).Replace("-----BEGIN PUBLIC KEY-----", "").Replace("-----END PUBLIC KEY-----", ""));

            rsaParam.Exponent = Exponent;

            rsa.ImportParameters(rsaParam);
            var dataToEncrypt = _encoder.GetBytes(password);
            encryptData = rsa.Encrypt(dataToEncrypt, false);

            return encryptData;
        }
Nay Thway
  • 21
  • 3
  • You can use bouncycastle for reading the pem file. See http://stackoverflow.com/questions/243646/how-to-read-a-pem-rsa-private-key-from-net – huysentruitw Aug 21 '15 at 05:18
  • thank for your comment! but it's using Private Key & to encrypt that key file. I would like to know is to make encrypt a string by using "Public Key" file (.pem). – Nay Thway Aug 21 '15 at 06:26
  • Yeah, didn't say it's a duplicate of your question. Just think you can borrow ways to read out the .pem file correctly because I don't think it just Base64 :) – huysentruitw Aug 21 '15 at 06:36
  • Try to 'Replace("\r\n",String.Empty);'. Also, try just to read all strings except the first and the last. – Oxoron Aug 21 '15 at 07:42

0 Answers0