使用RSA / ECB / PKCS1Padding进行.Net加密和Java解密

时间:2013-09-18 12:03:29

标签: c# java encryption

我们在java中有现有的加密代码并且工作得很好。我正在尝试在.net中创建相同的加密方法,这是一种失败的java解密方法,说错误的填充异常。请参阅以下代码详细信息: 使用Java代码: 加密:

private static byte[] doThis(String message) {
    byte[] messageCrypte = null;
       try {
        // Certificate Input Stream
        // LA SSL Certificate to be passed.
        InputStream inStream = new FileInputStream(certificate);

        // X509Certificate created
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);
        inStream.close();

        // Getting Public key using Certficate
        PublicKey rsaPublicKey = (PublicKey) cert.getPublicKey();

        Cipher encryptCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "SunJCE");
        encryptCipher.init(Cipher.ENCRYPT_MODE, rsaPublicKey);

        byte[] messageACrypter = message.getBytes();
        // Encrypted String
        messageCrypte = encryptCipher.doFinal(messageACrypter);
       } catch (Exception e) {
        // TODO: Exception Handling
        e.printStackTrace();
       }
    return messageCrypte;
}

等价的c#.Net代码我正在尝试使用但是我的填充异常从java解密代码中得到了错误。

    static byte[] doThis(string message)
    {
        X509Certificate cert = new X509Certificate(@"C:\Data\abc-rsa-public-key-certificate.cer");
        byte[] aa = cert.GetPublicKey();

        RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
        RSAParameters RSAKeyInfo = new RSAParameters();
        byte[] Exponent = { 1, 0, 1 };

        RSAKeyInfo = RSA.ExportParameters(false);
        //Set RSAKeyInfo to the public key values. 
        RSAKeyInfo.Modulus = aa;
        //RSAKeyInfo.Exponent = Exponent;
        RSA.ImportParameters(RSAKeyInfo);
        byte[] bb = RSA.Encrypt(GetBytes(message), false);
        return bb;
    }

用于解密的Java代码

private String getDecryptedString(byte[] credentials, PrivateKey secretKey) throws NoSuchAlgorithmException,
            NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException,
            BadPaddingException {
        String decryptedString;
        Cipher decryptCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "SunJCE");
        decryptCipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] messageDecrypte = decryptCipher.doFinal(credentials);
        decryptedString = new String(messageDecrypte);
        return decryptedString;
    }

1 个答案:

答案 0 :(得分:2)

这是.net代码:

public static string EncrypIt(string inputString, X509Certificate2 cert)
{
    RSACryptoServiceProvider rsaservice = (RSACryptoServiceProvider)cert.PublicKey.Key;
    byte[] plaintext = Encoding.UTF8.GetBytes(inputString);
    byte[] ciphertext = rsaservice.Encrypt(plaintext, false);
    string cipherresult = Convert.ToBase64String(ciphertext);
    return cipherresult;                 
}