简体   繁体   English

Python和C#密码学:我做错了什么?

[英]Python and C# Cryptography: What i'm doing wrong?

I need to encrypt text in python and decrypt in C #. 我需要在python中加密文本并在C#中解密。 In python, I have this code: 在python中,我有以下代码:

I have this code in Python: 我在Python中有以下代码:

def genKey():
    rsa = RSA.gen_key(2048, 65537)
    rsa.save_key('c:/temp/priv-key.pem', callback=passwordCallback)
    rsa.save_pub_key('c:/temp/pub-key.pem')

def encrypt():
    varkey = readkey('c:/temp/pub-key.pem')
    bio = BIO.MemoryBuffer(varkey)
    rsa = RSA.load_pub_key_bio(bio)

    encrypted = rsa.public_encrypt('My Text Here.', RSA.pkcs1_oaep_padding)

    f = open("c:/temp/cript.txt", "w")
    f.write(encrypted)
    f.close()

This code uses M2Crypto. 此代码使用M2Crypto。

Like I said, I want to decrypt the result generated up in C #. 就像我说的,我想解密在C#中生成的结果。 Below is my code: 下面是我的代码:

static void Main(string[] args)
{
    string text = GetText();
    System.Text.ASCIIEncoding  encoding=new System.Text.ASCIIEncoding();
    Byte[] payload = encoding.GetBytes(text);

    byte[] b = System.IO.File.ReadAllBytes(@"C:\temp\priv-key.pem");
    System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();

    OpenSSL.Core.BIO bio = new OpenSSL.Core.BIO(b);
    OpenSSL.Crypto.CryptoKey key = OpenSSL.Crypto.CryptoKey.FromPrivateKey(bio, "mypassword");
    RSA rsa = key.GetRSA();
    byte[] result = rsa.PrivateDecrypt(payload, RSA.Padding.OAEP);
}

The problem is this line: 问题是这一行:

byte[] result = rsa.PrivateDecrypt(payload, RSA.Padding.OAEP);

When it is executed, this error occurs: 执行该错误时,将发生以下错误:

error:0407A079:rsa routines:RSA_padding_check_PKCS1_OAEP:oaep decoding error
error:04065072:rsa routines:RSA_EAY_PRIVATE_DECRYPT:padding check failed

The gurus of Cryptography and C# can help me? 密码学和C#专家可以帮助我吗?

You are writing the encryption ciphertext as text. 您正在将encryption密文写为文本。 Instead you should open your file in binary mode in python. 相反,您应该在python中以二进制模式打开文件。 Then in C# you do the same thing, but the other way around. 然后,在C#中您执行相同的操作,但反之亦然。 Here you should return bytes instead of a string as ciphertext. 在这里,您应该返回字节而不是字符串作为密文。

If you want to use text mode instead of binary mode then you could use base 64 encoding/decoding. 如果要使用文本模式而不是二进制模式,则可以使用base 64编码/解码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM