我正在编写一个函数,其中该函数接收我的公钥作为变量,并且该变量的值是实际的公钥。我需要 Azure 中的两个不同的功能应用程序来加密和解密。密钥必须匹配,但问题是,每次我调用 API 时,公钥都不同,我可以毫无问题地加密。但是当我必须解密时它就不起作用了。我无法对这些功能使用相同的密钥对。这就是为什么我尝试使用之前生成的密钥作为变量。
Example:
string publicKey = "MMMFisIDUDHfhHSANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAi7ZOKtc55v9NJuhQFR583BcFkcjflXNVMqC5/3b7t7v..."
这是我用来加密的方法:
cipher.Init(true, publicKey);
我的密钥是使用 Bouncy Castle 生成的。
RsaKeyPairGenerator g = new RsaKeyPairGenerator();
g.Init(new KeyGenerationParameters(new SecureRandom(), 2048));
AsymmetricCipherKeyPair keyPair = g.GenerateKeyPair();
使用下面的代码可以正常工作:
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();`
我需要上面生成的键作为变量在控制台应用程序内的函数中使用。
但是当我尝试将密钥作为变量传递时,我收到以下错误:
https://i.stack.imgur.com/vLSOL.png
我可以使用 C# 中的核心类执行相同的过程,它与下面的代码类似:
C# RSA加密/解密与传输
我在上面的例子中遵循的相同逻辑现在对我不起作用。我是这一切的初学者。有没有办法做到这一点?
这是我用来获取屏幕截图上的错误的代码。密钥是使用我在原始帖子上发布的代码生成的。
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.