How to Sign a String using RSA Private Key Android Kotlin

1k views Asked by At

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

0

There are 0 answers