C#Bouncy Castle解码私钥

时间:2017-09-07 19:40:29

标签: c# rsa bouncycastle

我使用输入到C#类的私钥密码解码私钥时遇到错误。我认为问题是因为关键是:

  1. 从具有换行符的文本文件中读取。
  2. 私钥不是使用此库创建的,所以也许我没有正确解码它。
  3. 我不知道生成此密钥的系统是什么填充(具体来说,它是从Ruby Security lib生成的)。
  4. 抛出的异常是

      

    Org.BouncyCastle.Crypto.InvalidCipherTextException

    带有消息

      

    pad block corrupted

    发生在object privateKeyObject = pemReader.ReadObject();

    以下是提供给我的示例私钥:

    -----BEGIN RSA PRIVATE KEY-----
    Proc-Type: 4,ENCRYPTED
    DEK-Info: DES-EDE3-CBC,C7E12029C6ED8D89
    
    edy+pZIAuG1GpOLjg2i1Ed0ya3gUzYvpxUpkXN0B4JLLVMEonhThODm76WPg/UD1
    X1uua41vl+uzRyHRsT1JKS6//TBP2J1yUhEUb+Sckkpx2ZJ1ZWz+enoIGz9dJ8eR
    pfp6sKk4detX1l479PgdvcS0w9VUaSdGpsP5/ZnS7ZPST9SdZ2t8CtDlE/cleUw6
    JHhgjZfu7nd01xHoqA71xw/tl9G2b2CBI2KRFkHucdQ048dL9FPb/sRyUiWayVLr
    WzUhgX+3z9QUMh0n3UptbErR+tnPFfp2lC1P8HQfVwePTn7Ajc/GCQYHpKAJ6zVO
    DfPZA1thcJzv7DAk5w58mDSszpxVLb9Raf02Hk8XrSc/DxejH/VBQrZoqH8MJiOE
    gUg2iAZVW2FfPOvHqfsvEw7oSxZvSfSdSm/6ko66+akMmomViWCm30fWkcXO7aeY
    4FadpPZIQiL30fgJo5KZCoh/sP1jAsWr8H1XpnCM+tL2AOGJz/HvqTTlUCEL5O6E
    zIbX/SZxwcxhbHwUM+guH4HgPPtXF9RK3XGmVVed7MSBMpIzk/XS0vh4/UaMub77
    KppMF0G6S12StTS7IDlWHNBf4yXeyfwnPvWkV2PHwb6Oz4UUeI2oGXZooPiUCp9F
    f/ZW/ERvytM1xYxmpcTIYXgEkmW4COwpKF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9Ijvx1ZH2VIggm+aGCoBRwyhtgzs25jBXFGDkEZJwRq7w5PEvFgAlswTN
    7gKYazVU4bxm0snFNkIpVKAn9eDOU1xxEHNIp2bGx/9GpJ0n84jrg7VXzyZZN/yb
    PKxwr021LUizB2WOqKXeFid+7PUX4SHg1aJfnCYabC+Ms60a8+MvO+wb3HTj2HhV
    yGBjVcJQ7AhQXia1T3gKM9aCBAmuBxGUWoclchWVUYnbDkhiiNFJTRxGTwj+uEtr
    VxnLNnQIpLq8x5gHEMyM59+6IreVO/ppPcPNiudp706u1YU6+i/4wiACpbYHaycw
    qSgB+qxvnopjXKAiMzVslp/rWNNrEpFrH6nAg/Mh7AxQo/NXsF6k3QRViznwpQns
    -----END RSA PRIVATE KEY-----
    

    以下是私钥密码:

    SPH?!(C7ryh~juR>
    

    以下是代码:

    private readonly string _pubKey;
    private readonly string _privateKey;
    private readonly string _privateKeyPass;
    
    public RSAKeyEncryption(string pubKey, string privateKey, string privateKeyPass)
    {
        _pubKey = pubKey;
        _privateKey = privateKey;
        _privateKeyPass = privateKeyPass;
    }
    
    private AsymmetricCipherKeyPair DecodePrivateKey()
    {
        TextReader textReader = new StringReader(_privateKey);
        PemReader pemReader = new PemReader(textReader, new PasswordFinder(_privateKeyPass));
        object privateKeyObject = pemReader.ReadObject();
        AsymmetricCipherKeyPair keyPair = (AsymmetricCipherKeyPair)privateKeyObject;
        return keyPair;
    }
    

1 个答案:

答案 0 :(得分:1)

以下代码对我有用:

//  https://stackoverflow.com/a/6038944/1911064
StreamReader sr = new StreamReader(@"E:\AK\temp\key.pem");
string privateKeyPass = "SPH?!(C7ryh~juR>";
var pf = new PasswordFinder(privateKeyPass);
PemReader pr = new PemReader(sr, pf);
AsymmetricCipherKeyPair KeyPair = (AsymmetricCipherKeyPair)pr.ReadObject();
RSAParameters rsa =
        DotNetUtilities.ToRSAParameters((RsaPrivateCrtKeyParameters)KeyPair.Private);