BouncyCastle Decryption有效,但不是加密吗?

时间:2021-03-30 18:24:46

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

我从外部服务获取加密字符串,我需要解密,然后使用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".

我设法使解密工作正常,但加密似乎不起作用。当我尝试解密由我的加密方法生成的字符串时,我得到一个带有“未知块类型”消息的InvalidCipherTextException。

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?

我不确定我缺少什么让这项工作。有什么明显的东西我似乎在这里失踪了吗?

1 个解决方案

#1


1  

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

我假设您的签名字符串实际上包含公钥的base64编码?

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.

我不会给你一个关于公钥加密的完整课程,但请记住,你必须使用公钥加密和私钥解密。看起来你正试图用同一把钥匙做两件事。

#1


1  

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

我假设您的签名字符串实际上包含公钥的base64编码?

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.

我不会给你一个关于公钥加密的完整课程,但请记住,你必须使用公钥加密和私钥解密。看起来你正试图用同一把钥匙做两件事。