【发布时间】:2022-06-16 04:55:14
【问题描述】:
我正在写一个函数,这个函数接收我的公钥作为变量,这个变量的值是实际的公钥。
示例: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 加密/解密带传输
我在上面的例子中遵循的相同逻辑现在对我不起作用。我是这一切的初学者。有没有办法做到这一点?
PS:请注意,我不需要/不想生成我的密钥。
委托人
【问题讨论】:
-
这是一个基本的编码问题,而不是安全问题。您使用安全库的事实并没有改变这一点(尽管它确实让我害怕您正在编写的任何内容......即使对于经验丰富的开发人员来说,接触原始加密原语也是不明智的)
标签: encryption rsa asymmetric