【发布时间】:2018-01-13 16:59:17
【问题描述】:
如何在 Bouncy Castle 中使用 RSA 私钥解包密钥?我收到使用 RSA 公钥包装的已包装密钥。我有 RSA 密钥对。我只是在 C# Bouncy Castle 中找不到可以用来解包它的 api。
C# 源代码 (https://github.com/bcgit/bc-csharp) 中的这段代码目前已被注释掉。 RSA 的注释行正是我所需要的,但是当我尝试使用它们时,它似乎已被删除或从未实现
Key key = cipher.unwrap(wrappedKey, "RSA", IBufferedCipher.PRIVATE_KEY);
上面的行正是我所需要的。为什么被注释掉了? WrapTest.cs 中的完整功能如下:
public ITestResult Perform()
{
try
{
// IBufferedCipher cipher = CipherUtilities.GetCipher("DES/ECB/PKCS5Padding");
IWrapper cipher = WrapperUtilities.GetWrapper("DES/ECB/PKCS5Padding");
IAsymmetricCipherKeyPairGenerator fact = GeneratorUtilities.GetKeyPairGenerator("RSA");
fact.Init(
new RsaKeyGenerationParameters(
BigInteger.ValueOf(0x10001),
new SecureRandom(),
512,
25));
AsymmetricCipherKeyPair keyPair = fact.GenerateKeyPair();
AsymmetricKeyParameter priKey = keyPair.Private;
AsymmetricKeyParameter pubKey = keyPair.Public;
byte[] priKeyBytes = PrivateKeyInfoFactory.CreatePrivateKeyInfo(priKey).GetDerEncoded();
CipherKeyGenerator keyGen = GeneratorUtilities.GetKeyGenerator("DES");
// Key wrapKey = keyGen.generateKey();
byte[] wrapKeyBytes = keyGen.GenerateKey();
KeyParameter wrapKey = new DesParameters(wrapKeyBytes);
// cipher.Init(IBufferedCipher.WRAP_MODE, wrapKey);
cipher.Init(true, wrapKey);
// byte[] wrappedKey = cipher.Wrap(priKey);
byte[] wrappedKey = cipher.Wrap(priKeyBytes, 0, priKeyBytes.Length);
// cipher.Init(IBufferedCipher.UNWRAP_MODE, wrapKey);
cipher.Init(false, wrapKey);
// Key key = cipher.unwrap(wrappedKey, "RSA", IBufferedCipher.PRIVATE_KEY);
byte[] unwrapped = cipher.Unwrap(wrappedKey, 0, wrappedKey.Length);
//if (!Arrays.AreEqual(priKey.getEncoded(), key.getEncoded()))
if (!Arrays.AreEqual(priKeyBytes, unwrapped))
{
return new SimpleTestResult(false, "Unwrapped key does not match");
}
return new SimpleTestResult(true, Name + ": Okay");
}
catch (Exception e)
{
return new SimpleTestResult(false, Name + ": exception - " + e.ToString());
}
}
【问题讨论】:
-
你说的是Java,对吧?这段代码到底在哪里被注释掉了,你为什么要依赖它?你可以在你的代码中使用它。
-
能否请您提供更多代码?目前我们甚至不知道
cipher变量的类型。 @ArtjomB。嗯,里面有IBufferedCipher,感觉有点C#-ish。 -
@MaartenBodewes 我已经用更好的解释和更多代码更新了这个问题。
-
@ArtjomB。它是 C# 中的 Bouncy Castle 实现
-
unwrap方法以小写形式指定,表示复制代码时出现问题或从 Java 复制。这可能会解释混乱。 我们不知道为什么它被注释掉了(我的水晶球随着索伦的毁灭而坏掉了);当您尝试运行它时它会失败吗? 你被困在哪里了?
标签: c# encryption rsa bouncycastle