1

I'm writing a function where this function is receiving my public key as variable, and the value for this variable is the actually public key. I need two different functions apps in Azure, to encrypt and decrypt. The keys must match, but the problem is, every time I call the API the public key is different, I can encrypt without problems. But when I have to decrypt it doesn't work. I am not able to use the same key pairs for these functions. Thats why Im trying to use the keys I generated before as variables.

Example: string publicKey = "MMMFisIDUDHfhHSANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAi7ZOKtc55v9NJuhQFR583BcFkcjflXNVMqC5/3b7t7v..."

This is the method I'm using to encrypt:

cipher.Init(true, publicKey);

My keys are being generated using Bouncy Castle.

RsaKeyPairGenerator g = new RsaKeyPairGenerator(); g.Init(new KeyGenerationParameters(new SecureRandom(), 2048)); AsymmetricCipherKeyPair keyPair = g.GenerateKeyPair();

It worked normally with the code below:

        string plainText = "test data here";
        byte[] plainTextToByte = Encoding.UTF8.GetBytes(plainText);

        //Generating Key Pair
        RsaKeyPairGenerator g = new RsaKeyPairGenerator();
        g.Init(new KeyGenerationParameters(new SecureRandom(), 2048));
        AsymmetricCipherKeyPair keyPair = g.GenerateKeyPair();

        //Extracting the private key from pair
        RsaKeyParameters privateKey = (RsaKeyParameters)keyPair.Private;
        RsaKeyParameters publicKey = (RsaKeyParameters)keyPair.Public;

        //Encryption proccess
        IAsymmetricBlockCipher cipher = new OaepEncoding(new RsaEngine());
        cipher.Init(true, publicKey);
        byte[] cipherText = cipher.ProcessBlock(plainTextToByte, 0, plainTextToByte.Length);
        string encryptedText = Encoding.UTF8.GetString(cipherText);
        Console.WriteLine(encryptedText);

        //Decryption Process
        cipher.Init(false, privateKey);
        byte[] decryptedText = cipher.ProcessBlock(cipherText, 0 , cipherText.Length);
        string decryptedTextToString = Encoding.UTF8.GetString(decryptedText);

        Console.WriteLine(decryptedTextToString);
        Console.ReadLine();`

I need the keys generated above as a variable to use in a function inside a console app.

But when I try pass the key as variable, I'm getting the error below:

https://i.stack.imgur.com/vLSOL.png

I could do same procedure using core classes from C#, it was similar with the code below:

C# RSA encryption/decryption with transmission

The same logic I follow for the example above is not working for me now. I am beginner into all this. Is there a way to do that?

This is the piece code I'm using to get the error on the screenshot. The keys were generated with the code I posted on the original post.

    string plainText = "test here";
    byte[] plainTextToByte = Encoding.UTF8.GetBytes(plainText);

    string publicKey = "MIIBIjANBgk...DAQAB";

    IAsymmetricBlockCipher cipher = new OaepEncoding(new RsaEngine());
    cipher.Init(true, publicKey);
    byte[] cipherText = cipher.ProcessBlock(plainTextToByte, 0, plainTextToByte.Length);
    string encryptedText = Encoding.UTF8.GetString(cipherText);
    Console.WriteLine(encryptedText);

    return new OkObjectResult(encryptedText);`

Att.

pppery
  • 3,731
  • 22
  • 33
  • 46
miguelito
  • 111
  • 1
  • 10
  • Use PEM keys or Base64 encoded DER keys. These are strings. BC and C# (the latter not in all versions) support import/export. – Topaco Jun 14 '22 at 10:58
  • It didn't work either. I might be doing something wrong. I tried a different approach where I created two different functions: one for encrypt and for decrypt. But its still not working since I got different keys every time I request it from the API. – miguelito Jun 15 '22 at 01:38
  • Don't you want to export the public key generated with `g.GenerateKeyPair()` as a string and import this key again later and use it in `cipher.Init(true, publicKey)`? A Base64 encoded DER key does not change during import/export. Maybe I misunderstand the question. See also [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). – Topaco Jun 15 '22 at 06:18
  • I might be overthinking whole this process but I don't see how I can do that. Whenever I try with strings, I got the error: https://i.stack.imgur.com/vLSOL.png – miguelito Jun 15 '22 at 07:00
  • Screenshots are not very helpful. You should post how you generate the Base64 encoded DER key from `g.GenerateKeyPair()` (or whatever encoding you use) and how you later turn it into an `RsaKeyParameters` object that can be passed to `cipher.Init(true, publicKey)`. – Topaco Jun 15 '22 at 07:42
  • Once again: Where does `MIIBIjANBgk...DAQAB` come from? I don't see anywhere in the code how you get this string! – Topaco Jun 15 '22 at 17:37
  • My Public Key Generator: `RsaKeyPairGenerator g = new RsaKeyPairGenerator(); g.Init(new KeyGenerationParameters(new SecureRandom(), 2048)); AsymmetricCipherKeyPair keyPair = g.GenerateKeyPair(); RsaKeyParameters publicKey = (RsaKeyParameters)keyPair.Public; TextWriter tw = new StringWriter(); PemWriter pw = new PemWriter(tw); pw.WriteObject(publicKey); pw.Writer.Flush(); string printPublicKey = tw.ToString(); Console.WriteLine(printPublicKey);` – miguelito Jun 16 '22 at 01:10
  • I need two different functions apps in Azure, to encrypt and decrypt. The keys must match, but the problem is, every time I call the API the public key is different, I can encrypt without problems. But when I have to decrypt it doesn't work. I am not able to use the same key pairs for these functions. Thats why Im trying to use the keys I generated before as variables. :) – miguelito Jun 16 '22 at 02:24

1 Answers1

0

I'm not quite clear what the problem is. But based on the last snippet posted in the question, you are trying to import a public key. And according to your penultimate comment, it is a PEM encoded public key in X.509/SPKI format exported with a PemWriter:

-----BEGIN PUBLIC KEY-----
MIIB...
...AQAB
-----END PUBLIC KEY-----

Such a key can be imported and used in Cipher#Init() as follows (let publicKeyPem be the exported PEM key):

using Org.BouncyCastle.OpenSsl;
...
PemReader pemReader = new PemReader(new StringReader(publicKeyPem));
RsaKeyParameters publicKeyReloaded = (RsaKeyParameters)pemReader.ReadObject();
...
cipher.Init(true, publicKeyReloaded); 
Topaco
  • 40,594
  • 4
  • 35
  • 62
  • Thanks for the assistance @Topaco, now I'm able to encrypt the data I want to. I will now follow the same logic for decrypting the data. I'll use the output of this function to encrypt and set into a variable and see what happens. Cheers! :) – miguelito Jun 17 '22 at 02:48