简体   繁体   中英

java cipher to c# equivalent

I am very grateful with any help. I am trying to convert a rsa cryptor java implementation to c#. I need to encrypt credit card data. The platform i use provides cryptography SDK for javascript and android, but I need a C# implementation.

    try {
      cipher = Cipher.getInstance("RSA/None/PKCS1Padding", "SC");
    } catch (SecurityException se) {
      //workaround for tests
      Log.i("Moip SDK", "No SC provider, running test profile");
      cipher = Cipher.getInstance("RSA");
    }

    BufferedReader pemReader = null;
    pemReader = new BufferedReader(new InputStreamReader(
      new ByteArrayInputStream(publicKey.getBytes("UTF-8"))));

    StringBuffer content = new StringBuffer();
    String line = null;
    while ((line = pemReader.readLine()) != null) {
      if (line.indexOf("-----BEGIN PUBLIC KEY-----") != -1) {
        while ((line = pemReader.readLine()) != null) {
          if (line.indexOf("-----END PUBLIC KEY") != -1) {
            break;
          }
          content.append(line.trim());
        }
        break;
      }
    }
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, keyFactory.generatePublic(new X509EncodedKeySpec(Base64.decode(content.toString(), Base64.DEFAULT))));
    byte[] cipherText = cipher.doFinal(toHash().getBytes());

    return Base64.encodeToString(cipherText, Base64.DEFAULT);

The code I created looking at the implementation in java, it works but fails to be decrypted on the platform, I must be forgetting something. My implementation:

  private string Payload(string number, string expirationMonth, string expirationYear, string cvc) {
    return String.Join(
      "&",
      new List<string> {
        $"number={number}",
        $"cvc={cvc}",
        $"expirationMonth={expirationMonth}",
        $"expirationYear={expirationYear}",
      }
    );
  }

  private string Encrypt(string key, string payload) {
    var publicKey = $"<RSAKeyValue><Modulus>{key}</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
    var rsa = new RSACryptoServiceProvider(2048);
    rsa.FromXmlString(publicKey);
    var encryptedData = rsa.Encrypt(Encoding.UTF8.GetBytes(payload), RSAEncryptionPadding.Pkcs1);
    rsa.Dispose();

    return Convert.ToBase64String(encryptedData);
  }


var payload = Payload(number, expirationMonth, expirationYear, cvc);
hash = Encrypt(ClientManager.Environment.publicKeyCreditCard, payload);

Welcome to Stackoverflow. I run your codes and I could encrypt and decrypt on both platforms (Java & C#) successfully.

So in my eyes the only reason why decryption fails when doing encryption on C# is that you didn't convert the public key correctly.

I recommend to use (as it is the pub key) an online converter like https://superdry.apphb.com/tools/online-rsa-key-converter .

Just copy the public key in the lower input text area "PEM to XML" like this one (it's an unsecure 512 bit RSA-key so it will be shorter than your one):

-----BEGIN PUBLIC KEY-----" +
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJn4LYaoLyuT+pD9NKI8wOvPrRjMIxGn
HbqIxUrpGsyj162fEOV4836oCZg0N8HFnt4Vivdjt8/7ZgLjeOygNGUCAwEAAQ==
-----END PUBLIC KEY-----

and press "Convert" - below you get the public key in xml-format:

<RSAKeyValue><Modulus>mfgthqgvK5P6kP00ojzA68+tGMwjEacduojFSukazKPXrZ8Q5XjzfqgJmDQ3wcWe3hWK92O3z/tmAuN47KA0ZQ==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>

The partial key that you have to present to your C# method is after Modulus:

mfgthqgvK5P6kP00ojzA68+tGMwjEacduojFSukazKPXrZ8Q5XjzfqgJmDQ3wcWe3hWK92O3z/tmAuN47KA0ZQ==

You should have an eye on the value - in most times it is "AQAB" but in case you receive another value you have to adjust your source code in C#.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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