Im trying to make serverless discord bot using java 11. Discord documentation doesn't provide any example in terms of validating in java. I have found a java library that might be of help here, but I have little expertise in this field and my code always results in validation failed. Would someone point me what im doing wrong during this validation ?
SecretKey key = Crypto.authKey(fromHex("<MY APPLICATION PUBLIC KEY>"));
String message = x_signature_timestamp + event.get("body");
boolean verified = Crypto.authVerify(key,message.getBytes(),fromHex(x_signature_ed25519));
and
public static byte[] fromHex(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}
im always getting this when adding interactions endopint url
response im sending:
if (!verified){
response = ApiGatewayResponse.builder()
.withHeaders(headers)
.withBody("validation failed")
.withStatusCode(401)
.build();
} else {
response = ApiGatewayResponse.builder()
.withHeaders(headers)
.withBody(event.get("body").toString())
.withStatusCode(200)
.build();
}
return response;
With salty-coffee the required Ed25519 verification can be performed under Java (11)!
With the following test data a successful verification can be performed using tweetnacl and the NodeJS code you linked:
const nacl = require('tweetnacl');
const PUBLIC_KEY = "9c7d775851a98ceb09a80928c1f8ff56706a0f5d91d841c72850fcd92e065b8f"; // 'APPLICATION_PUBLIC_KEY'
const signature = "99c4903df0b00ac32ba158db956ee39586adf05fea6be714055ac79a80bfd9dff59399b7da01ced95d0a252daee6bdb07e5f59cc546322bb779fd749b04f170c"; // req.get('X-Signature-Ed25519')
const timestamp = '202204091535'; // req.get('X-Signature-Timestamp')
const body = 'testmessage'; // req.rawBody
const isVerified = nacl.sign.detached.verify(
Buffer.from(timestamp + body),
Buffer.from(signature, 'hex'),
Buffer.from(PUBLIC_KEY, 'hex')
);
console.log(isVerified); // true
The analog Java code with salty-coffee that allows successful verification is:
import java.nio.charset.StandardCharsets;
import software.pando.crypto.nacl.Crypto;
...
String PUBLIC_KEY = "9c7d775851a98ceb09a80928c1f8ff56706a0f5d91d841c72850fcd92e065b8f";
String signature = "99c4903df0b00ac32ba158db956ee39586adf05fea6be714055ac79a80bfd9dff59399b7da01ced95d0a252daee6bdb07e5f59cc546322bb779fd749b04f170c";
String timestamp = "202204091535";
String body = "testmessage";
boolean isVerified = Crypto.signVerify(
Crypto.signingPublicKey(fromHex(PUBLIC_KEY)),
(timestamp + body).getBytes(StandardCharsets.UTF_8),
fromHex(signature));
System.out.println(isVerified); // true
Note that the verification is to be done with Crypto.signVerify()
and not with Crypto.authVerify()
.