1

I have a the following code in Node.js

    let publicKeyString = '-----BEGIN PUBLIC KEY-----RANDOMPUBLICKEYOMITTED-----END PUBLIC KEY-----\n';

    let publicKey = {
      key: publicKeyString,
      padding: 1
    }
    function _encrypt(input, key) {
        let buf = new Buffer(input, 'utf8');
        console.log('******');
        console.log(buf.length);
        console.log(buf);
        console.log('******');
        let encryptedBuffer = crypto.publicEncrypt(key, buf);
        return encryptedBuffer.toString('base64');
    }
    let card =  {
       "card_type": "ABCD",
       "card_number": "1111222233334444",
       "expiration_month": 01,
       "expiration_year": 2222,
       "security_code": "321"
    };

   let encryptedPayload = _encrypt(JSON.stringify(card), publicKey);

   console.log(encryptedPayload);

I also have test cases to determine if code has been encrypted properly (I can not share these though) I would like to have the equivalent encryption code in Java. I have referenced some other stackoverflow questions such as Encryption of Strings works, encryption of byte[] array type does not work where keys are generated. This does not work for me because I need to be able to set the public key's string. Porting Node 'crypto' code to Java does not work for me because I do not believe I need a cipher and the node js code does not contain a cipher, Encrypt with Node.js Crypto module and decrypt with Java (in Android app) does not work for me because I can not set the public key's encryption string, and java Encrypt method equivalent in node js crypto does not work because my node js code does not contain a cipher. I have also referenced this snippet of code in java :

    public static PublicKey getKey(String key){
    try{
        byte[] byteKey = Base64.getDecoder().decode(key.getBytes("UTF-8"));
        System.out.println(byteKey.length);
        X509EncodedKeySpec X509publicKey = new X509EncodedKeySpec(byteKey);
        KeyFactory kf = KeyFactory.getInstance("RSA");

        return kf.generatePublic(X509publicKey);
    }
    catch(Exception e){
        e.printStackTrace();
    }

    return null;
}

However I am not getting the correct encryption when I simple plug in the public key string. I am also unsure how padding is implemented in Node js and what the default encryption algorithm for crypto.publicencrypt is.

Any help would be appreciated.

swilliz
  • 13
  • 4

0 Answers0