2

因此,在 C# 中,我有以下代码:

public static void Main (string[] args)
{
    publicKeyXml = "<Modulus>mFCubVhPGG+euHuVQbNObqod/Ji0kRe+oh2OCFR7aV09xYiOklqFQ8jgIgAHvyCcM1JowqfFeJ5jV9up0Lh0eIiv3FPRu14aQS35kMdBLMebSW2DNBkfVsOF3l498WWQS9/THIqIaxbqwRDUxba5btBLTN0/A2y6WWiXl05Xu1c=</Modulus><Exponent>AQAB</Exponent>";
    RSACryptoServiceProvider rSACryptoServiceProvider = new RSACryptoServiceProvider ();
    rSACryptoServiceProvider.FromXmlString (publicKeyXml);
    Console.WriteLine(Convert.ToBase64String (rSACryptoServiceProvider.Encrypt (Encoding.ASCII.GetBytes(args[0]), false)));
}

当我用来加密消息时,它在远程服务器上工作得很好(我没有源代码)。但是,当尝试在 Python 中使用 PyCrypto 做类似的事情时,远程服务器无法解密。

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5

KEY = RSA.importKey(open('login.key').read()) # Converted to standard format
KEY_CIPHER = PKCS1_v1_5.new(KEY)

testmsg = KEY_CIPHER.encrypt("test msg").encode('base64').replace('\n', '')
# send testmsg down a socket
# Response: {"info":"java.lang.IllegalArgumentException: Could not decrypt.","msg":"Fail"}

关于为什么会这样的任何想法?

4

2 回答 2

1

好的,就我而言,这很奇怪。服务器端期待我的东西倒退。为了解决,我只是这样做了:

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5

KEY = RSA.importKey(open('login.key').read()) # Converted to standard format
KEY_CIPHER = PKCS1_v1_5.new(KEY)

testmsg = KEY_CIPHER.encrypt("test msg").encode('base64').replace('\n', '')
testmsg = "".join(reversed([testmsg[i:i+2] for i in range(0, len(testmsg), 2)]))
于 2013-08-07T16:58:36.697 回答
0
Modulus = "mFCubVhPGG+euHuVQbNObqod/Ji0kRe+oh2OCFR7aV09xYiOklqFQ8jgIgAHvyCcM1JowqfFeJ5jV9up0Lh0eIiv3FPRu14aQS35kMdBLMebSW2DNBkfVsOF3l498WWQS9/THIqIaxbqwRDUxba5btBLTN0/A2y6WWiXl05Xu1c="
Exponent = "AQAB"

mod_raw = b64decode(Modulus)
exp_raw = b64decode(Exponent)
mod = int(mod_raw.encode('hex'), 16)
exp = int(exp_raw.encode('hex'), 16)
seq = asn1.DerSequence()
seq.append(mod)
seq.append(exp)
der = seq.encode()
keyPub = RSA.importKey(der)
print base64.b64encode(keyPub.encrypt('test msg', 0)[0])
于 2016-12-28T06:34:42.737 回答