Reputation: 53
I use AWS SDK for Java 2.x, dependency software.amazon.awssdk:sns
I receive message from sns topic via http. I'm wondering if there're any official or non-official but well-supported libraries that can do verification of signature.
I've implemented verification using code snippets from https://docs.aws.amazon.com/sns/latest/dg/sns-example-code-endpoint-java-servlet.html, but perhaps better solution is existing
public void verifySignature(SnsMessage message) {
String signatureVersion = message.getSignatureVersion();
if (signatureVersion.equals("1")) {
// Check the signature and throw an exception if the signature verification fails.
if (isMessageSignatureVersion1Valid(message)) {
log.info("Signature verification succeeded");
} else {
log.info("Signature verification failed");
throw new SecurityException("Signature verification failed.");
}
} else {
log.info("Unexpected signature version. Unable to verify signature.");
throw new SecurityException("Unexpected signature version. Unable to verify signature.");
}
}
Upvotes: 5
Views: 1418
Reputation: 41
For latest version of SNS SDK at the moment 1.12.286 - signature verification is done automatically during message deserialization to SnsMessage object.
You can use SnsMessageManager#parseMessage to deserialize incoming message to SnsMessage object.
From SNS SDK javadoc:
Unmarshalls a message into a subclass of SnsMessage. This will automatically validate the authenticity of the mesage to ensure it was sent by SNS. If the validity of the message cannot be verified an exception will be thrown. Params: messageBody – Input stream containing message JSON. Returns: Unmarshalled message object.
It's clear from SNS SDK source code as well:
SnsMessageManager#parseMessage -> SignatureVerifier#verifySignature
So something like this will work:
InputStream messageInputStream = "<message received from SNS>"
SnsMessage snsMessage = new SnsMessageManager().parseMessage(messageInputStream)
See this part of SNS documentation is useful for signature verification details.
Upvotes: 4
Reputation: 8354
At the time of writing (August 2021) AWS SDK for Java 2.x doesn't yet support all the features of AWS SDK for Java 1.x. But fortunately, you can use them side-by-side. Quote from the official documentation:
You can use both versions of the AWS SDK for Java in your projects.
And in 1.x you have SnsMessageManager that apparently does the job:
public class SnsMessageManager
extends Object
Unmarshalls an SNS message and validates it using the SNS public certificate.
Upvotes: 4