我正在尝试使用接收方公钥加密我的字符串文件,但我无法做到这一点。我正在使用充气城堡方法来生成密钥。我导出了公钥并将其设为全局。现在我想用这个公钥加密消息,但我做不到。请帮帮我。请查看我的代码。
string PubKey; // global variable
string inputMessage = 12345; // message to be encrypted
private void KeyGeneration() // function for generating the keys.
{
RsaKeyPairGenerator generator = new RsaKeyPairGenerator();
generator.Init(new KeyGenerationParameters(new SecureRandom(), 1024));
AsymmetricCipherKeyPair keyPair = generator.GenerateKeyPair();
RsaKeyParameters publicKey = (RsaKeyParameters)keyPair.Public;
// Save to export format
SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public);
byte[] ret = info.GetEncoded();
PubKey = Convert.ToBase64String(ret);
PrivateKeyInfo pKinfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private);
byte[] privRet = pKinfo.GetEncoded();
PrivKey = Convert.ToBase64String(privRet);
}
private void Create_PC_Req_Click(object sender, EventArgs e) // this is my button event I want to encrypt my message here
{
UTF8Encoding utf8enc = new UTF8Encoding();
byte[] inputBytes = utf8enc.GetBytes(inputMessage);
RsaKeyPairGenerator rsaKeyPairGnr = new RsaKeyPairGenerator();
rsaKeyPairGnr.Init(new KeyGenerationParameters(new SecureRandom(), 512));
AsymmetricCipherKeyPair keyPair = rsaKeyPairGnr.GenerateKeyPair();
RsaKeyParameters publicKey = (RsaKeyParameters)keyPair.Public;
IAsymmetricBlockCipher cipher = new RsaEngine();
// this is the way of encryption when you are generating a keys here and extracting a public key here but I want to encrypt my message with the public key which I made global.
cipher.Init(true, publicKey);
//Encrypting the input bytes
byte[] cipheredBytes = cipher.ProcessBlock(inputBytes, 0, inputMessage.Length);
string p = utf8enc.GetString(cipheredBytes);
textBox4.Text = p;
}