0

We are facing issue on Signing String using Private RSA Key

val key:'-----BEGIN RSA PRIVATE KEY-----ASDSADSAADSDASA-----END RSA PRIVATE KEY-----';
val data:'DATA TO BE SIGNED';
val privateKeyPEM = key
        .replace("-----BEGIN RSA PRIVATE KEY-----", "")
        .replace(System.lineSeparator().toRegex(), "")
        .replace("-----END RSA PRIVATE KEY-----", "")

val encoded: ByteArray = Base64.getDecoder().decode(privateKeyPEM)
val spec = PKCS8EncodedKeySpec(encoded)
val kf = KeyFactory.getInstance("RSA")
val privateKey: RSAPrivateKey = kf.generatePrivate(spec) as RSAPrivateKey

val signature: Signature = Signature.getInstance("SHA256withRSA")
signature.initSign(privateKey)
signature.update(data)
val signedString: signature.sign()

So this above code of Kotlin is not generating the correct sign as the sample given by payment integrator company as given below in Javascript

'calculateSignature': function (data, timestamp, nonce) {
     //console.log('data', data);
     //console.log('timestamp =', timestamp);
     //console.log('nonce =', nonce);
    
    var dataToSign = data + timestamp + nonce;
    console.log('dataToSign', dataToSign);
    var clientPrivateKey = pm.environment.get('clientPrivateKey');
        hashAlgorithm = pm.environment.get('hashAlgorithm');

     console.log('clientPrivateKey =', clientPrivateKey);
    console.log('hashAlgorithm =', hashAlgorithm);
    var rsa = new RSAKey();
    rsa.readPrivateKeyFromPEMString(clientPrivateKey);
    var signature = rsa.sign(dataToSign, hashAlgorithm);
    console.log('signature =', signature);
    
    return signature;
},

Can anyone please suggest me where we are doing wrong step. any help or suggestion would be appreciated

Kashyap Patel
  • 1,139
  • 1
  • 13
  • 29
  • `BEGIN RSA PRIVATE KEY` is used for a private key format that is not compatible with PKCS8EncodedKeySpec. It should throw an exception. – President James K. Polk Mar 30 '22 at 00:07
  • @PresidentJamesK.Polk it doesnt throw an exception. it generates the signature but it doesnt match with the example given by integrator company – Kashyap Patel Mar 30 '22 at 04:51
  • @KashyapPatel Do you able to find a solution for this? I also need something similar. – Kunu Aug 26 '22 at 04:48
  • @Kunu I made a Tweak in the process here. instead of doing it using Kotlin. i have developed a Node app to do this and used it using API – Kashyap Patel Sep 01 '22 at 16:14

0 Answers0