Skip to content

Instantly share code, notes, and snippets.

@galoggob
Created February 16, 2021 05:25
Show Gist options
  • Save galoggob/dfc7d0f7f217e457772019b9a3caad71 to your computer and use it in GitHub Desktop.
Save galoggob/dfc7d0f7f217e457772019b9a3caad71 to your computer and use it in GitHub Desktop.
Converts an AWS secret access key to an Amazon SES SMTP password
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
/**
* @see The following pseudocode shows an algorithm that converts an AWS secret access key to an Amazon SES SMTP password.
* https://docs.aws.amazon.com/ses/latest/DeveloperGuide/smtp-credentials.html#smtp-credentials-console
*/
public class SesSmtpCredentialGenerator {
public String getSmtpPasswordV4(String key){
// The values of the following variables should always stay the same.
final String message = "SendRawEmail";
final String date = "11111111";
final String service = "ses";
final String terminal = "aws4_request";
final String region = "eu-west-1";
final byte VERSION4 = 0x04; // Version number. Do not modify.
try {
byte[] kDate = sign(date, ("AWS4" +key).getBytes());
byte[] kRegion = sign(region, kDate);
byte[] kService = sign(service, kRegion);
byte[] kTerminal = sign(terminal, kService);
byte[] kMessage = sign(message, kTerminal);
// Snippet code-> signatureAndVersion = Concatenate(version, kMessage);
byte[] rawSignatureWithVersion = new byte[kMessage.length + 1];
byte[] versionArray = {VERSION4};
System.arraycopy(versionArray, 0, rawSignatureWithVersion, 0, 1);
System.arraycopy(kMessage, 0, rawSignatureWithVersion, 1, kMessage.length);
// Snippet code-> smtpPassword = Base64(signatureAndVersion);
String smtpPassword = DatatypeConverter.printBase64Binary(rawSignatureWithVersion);
System.out.println(smtpPassword);
return smtpPassword;
} catch (Exception ex) {
System.out.println("Error generating SMTP password: " + ex.getMessage());
}
return null;
}
private static byte[] sign(String msg, final byte[] key) throws NoSuchAlgorithmException, InvalidKeyException {
SecretKeySpec secretKey = new SecretKeySpec(key, "HmacSHA256");
// Get an HMAC-SHA256 Mac instance and initialize it with the AWS secret access key.
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(secretKey);
return mac.doFinal(msg.getBytes());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment