[英]Public and Private Key as variables C#
我正在編寫一個函數,該函數將我的公鑰作為變量接收,該變量的值是實際的公鑰。 我需要 Azure 中的兩個不同功能的應用程序來加密和解密。 密鑰必須匹配,但問題是,每次調用 API 時公鑰都不一樣,我可以毫無問題地加密。 但是當我必須解密時它不起作用。 我無法為這些功能使用相同的密鑰對。 這就是為什么我試圖使用我之前生成的密鑰作為變量。
示例: 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# 中的核心類執行相同的過程,它與下面的代碼類似:
我為上面的示例遵循的相同邏輯現在對我不起作用。 我是這一切的初學者。 有沒有辦法做到這一點?
這是我用來獲取屏幕截圖錯誤的代碼。 密鑰是使用我在原始帖子中發布的代碼生成的。
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);`
附件。
我不太清楚問題是什么。 但是根據問題中發布的最后一個片段,您正在嘗試導入公鑰。 根據您的倒數第二條評論,它是使用PemWriter
導出的 X.509/SPKI 格式的 PEM 編碼公鑰:
-----BEGIN PUBLIC KEY-----
MIIB...
...AQAB
-----END PUBLIC KEY-----
這樣的密鑰可以按如下方式在Cipher#Init()
中導入和使用(設publicKeyPem
為導出的 PEM 密鑰):
using Org.BouncyCastle.OpenSsl;
...
PemReader pemReader = new PemReader(new StringReader(publicKeyPem));
RsaKeyParameters publicKeyReloaded = (RsaKeyParameters)pemReader.ReadObject();
...
cipher.Init(true, publicKeyReloaded);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.