Created
          February 3, 2020 12:40 
        
      - 
      
- 
        Save HirbodBehnam/a42754a9073e3f3d42cb3679eea888c8 to your computer and use it in GitHub Desktop. 
    Just a small app to parse pem files with bouncy castle
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | // https://stackoverflow.com/questions/7149411/j2me-exception-when-casting-from-pemobject-to-asymmetrickeyparameter-with-bounc | |
| // https://stackoverflow.com/questions/11506891/how-to-load-the-rsa-public-key-from-file-in-c-sharp | |
| // https://stackoverflow.com/questions/11346200/reading-pem-rsa-public-key-only-using-bouncy-castle/11367152#11367152 | |
| using System; | |
| using System.Buffers.Text; | |
| using System.Collections.Generic; | |
| using System.Diagnostics; | |
| using System.Globalization; | |
| using System.IO; | |
| using System.Net; | |
| using System.Net.Http; | |
| using System.Numerics; | |
| using System.Security.Cryptography; | |
| using System.Text; | |
| using System.Threading.Tasks; | |
| using Org.BouncyCastle.Crypto; | |
| using Org.BouncyCastle.Crypto.Digests; | |
| using Org.BouncyCastle.Crypto.Encodings; | |
| using Org.BouncyCastle.Crypto.Engines; | |
| using Org.BouncyCastle.OpenSsl; | |
| using Org.BouncyCastle.Security; | |
| namespace TestConsole | |
| { | |
| class Program | |
| { | |
| static void Main() | |
| { | |
| var keyPair = ReadAsymmetricKeyParameter("public.pem"); | |
| var encryptEngine = new OaepEncoding(new RsaEngine(), new Sha512Digest()); | |
| encryptEngine.Init(true,keyPair); | |
| var toEncrypt = Encoding.ASCII.GetBytes("Hello"); | |
| var encrypt = encryptEngine.ProcessBlock(toEncrypt, 0, toEncrypt.Length); | |
| Console.WriteLine(Convert.ToBase64String(encrypt)); | |
| Console.ReadKey(); | |
| } | |
| public static Org.BouncyCastle.Crypto.AsymmetricKeyParameter ReadAsymmetricKeyParameter(string pemFilename) | |
| { | |
| using (StreamReader reader = File.OpenText(pemFilename)) | |
| { | |
| Org.BouncyCastle.OpenSsl.PemReader pr = | |
| new Org.BouncyCastle.OpenSsl.PemReader(reader); | |
| Org.BouncyCastle.Utilities.IO.Pem.PemObject po = pr.ReadPemObject(); | |
| return PublicKeyFactory.CreateKey(po.Content); | |
| } | |
| } | |
| } | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment