How to put timestamp in android generated crypto signature

Viewed 67

What I have is private key without header, footer and spaces (it's test one)

MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg0m4yLz+sdzZtBG9Q3HQ9++wcfq1O4hOWgSBMb/A6eijyhRANCAAQeB0fBl2D7HZOKVBjpPiU2jabzNxQU4ZYrJ+MSA3LpzZxmRk2JaFHNujjkJghQT19HHjg3Fnkb8Y9oIhB9neXBI

And this code in android which generates signature in required format.

val signatureSHA256 = Signature.getInstance("SHA256withECDSA")

val encoded = Base64.decode(privateKeyHere, Base64.DEFAULT)
val privateKey: PrivateKey = KeyFactory.getInstance("EC").generatePrivate(PKCS8EncodedKeySpec(encoded))

signatureSHA256.initSign(privateKey)

val finalSignature = signatureSHA256.sign().toHexString()



//Somewhere
fun ByteArray.toHexString() = joinToString("") { "%02x".format(it) }

And function which return timestamp:

fun getXTimestamp(): Long {
    return (System.currentTimeMillis() / 1000L)
}

From android Im getting finalSignature and getXTimestamp() And I need to verify my signature in php script:

$timestamp = '1625730735';
$public_key = "
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEHgdHwZdg+x2TilQY6T4lNo2m8zcU
FGWKyfjEgNy6c2cZkZNiWhRzbo45CYIUE9fRx44NxZ5G/GPaCIQfZ3lwSA==
-----END PUBLIC KEY-----
";
//hex2bin("finalSignature")
$sign = hex2bin("3045022048011d511094a5270c528ca5064b07084e36ccfd2ee3f5e1e20278fb5d83cdba022100d71a0096ef2c6288554a51017a89374b18c7e84ba7031a43d67f53d7ce89152c");

$result = openssl_verify($timestamp, $sign, $public_key, OPENSSL_ALGO_SHA256);
print $result;

Now php script launched from console returns 0 but should return 1. I think I should somehow update or put timestamp in signature. I tried to put it in update() as bytes, but still got 0 Who can help pls?)

1 Answers

On PHP side ("verification") you use your 'timestamp' as text string as input for your openssl_verify function.

On Kotlin-side you need to do the same - get the timestamp as string and use it as input for a sign.update call with [Pseudo-code] timestamp-string.getBytes(StandardCharset.UTF8) as input.

As I'm not familiar with Kotlin I'm using the code in the comment of @Andrej Kijonok as it solves the problem :-)

val signatureTimestamp = getXTimestamp().toString().toByteArray(Charsets.UTF_8)
signatureSHA256.initSign(privateKey)
signatureSHA256.update(signatureTimestamp)
Related