开发者

BouncyCastle Decryption works, but not Encryption?

I'm getting an encrypted string from an external service that I need to decrypt, and then re-encrypt using the BouncyCastle API.

I've managed to get decryption working fine, but encryption doesn't seem to work. When I try to decrypt a string generated by my encryption method I get an InvalidCipherTextException with the message "unknown block type".

This is my decryption code, which successfully decrypts text from the service I'm interfacing with:

string Decrypt(string value) 
{
    string Signature = "My_Signature";
    RsaKeyParameters keyParams = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(Signature));
    IBufferedCipher cipher = CipherUtilities.GetCipher("RSA/NONE/PKCS1Padding");
    cipher.Init(false, keyParams);

    byte[] secretBytes = Convert.FromBase64String(value);
    byte[] decrypted = cipher.DoFinal(secretBytes);

    return Encoding.Default.GetString(decrypted);
}

This is my encryption method, which doesn't seem to generate an encrypted string that my decrypt method can handle:

string Encrypt(string value)
{
    string Signature = "My_Signature";
    RsaKeyParameters keyParams = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(Signature));
    IBufferedCipher cipher = CipherUtilities.GetCipher("RSA/NONE/PKCS1Padding");
    cipher.Init(true, keyParams);

    byte[] secretBytes = Encoding.Default.GetBytes(value);
    byte[] encrypted = cipher.DoFinal(secretBytes);

    return Convert.ToBase64String(encrypted);
}

I'm not really sure what I'm missing to make this work. Is there anything obvious 开发者_如何学编程I seem to be missing here?


I assume your Signature-string actually contains a base64-encoding of a public key?

I won't give you a full course on Public-key cryptography, but remember that you have to use the public key to encrypt and the private key to decrypt. It looks like you are trying to do both with the same key.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜