Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save DevoKun/5315ba14e5da246aa3b734a510924cf9 to your computer and use it in GitHub Desktop.
Save DevoKun/5315ba14e5da246aa3b734a510924cf9 to your computer and use it in GitHub Desktop.
Convert AWS IAM credentials to AWS SMTP credentials

Convert AWS IAM credentials to AWS SMTP credentials

If you do, or want to, use AWS to deploy your apps, you will end up using AWS SES via SMTP when you're launching an app that sends out emails of any kind (user registrations, email notifications, etc). For example, I have used this configuration on various Ruby on Rails apps, however, it is just basic SMTP configurations and crosses over to any framework that supports SMTP sendmail.

There are two ways to go about this:

Luckily, you found this MD file and the NOT SO EASY WAY is suddenly copy-pasta... sudo yum....

Assuming you've already set up your SES Policy on your IAM User:

    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect":"Allow",
          "Action":["ses:SendEmail", "ses:SendRawEmail"],
          "Resource":"*"
        }
      ]
    }

Go ahead and drop this into an bash session, or somewhere in your app, and pass in your IAM user's secret key to generate your SMTP password :)

Ruby

Thanks @talreg and @cristim

require 'openssl'
require 'base64'

def aws_iam_smtp_password_generator(key_secret)
    message = "SendRawEmail"
    versionInBytes = "\x02"
    signatureInBytes = OpenSSL::HMAC.digest('sha256', key_secret, message)
    signatureAndVer = versionInBytes + signatureInBytes
    smtpPassword = Base64.encode64(signatureAndVer)
    return smtpPassword.to_s.strip
end

# print aws_iam_smtp_password_generator ENV['AWS_SECRET_ACCESS_KEY']

PHP

    <?php

      function aws_iam_smtp_password_generator($secret) {
        $message = "SendRawEmail";
        $versionInBytes = chr(2);
        $signatureInBytes = hash_hmac('sha256', $message, $secret, true);
        $signatureAndVer = $versionInBytes.$signatureInBytes;
        $smtpPassword = base64_encode($signatureAndVer);

        return $smtpPassword;
      }

    ?>

Python

Thanks to @avdhoot and @techsolx

# v2
import base64
import hmac
import hashlib
import sys

def hash_smtp_pass_from_secret_key(key):
    message = "SendRawEmail"
    version = '\x02'
    h = hmac.new(key, message, digestmod=hashlib.sha256)
    return base64.b64encode("{0}{1}".format(version, h.digest()))

if __name__ == "__main__":
    print hash_smtp_pass_from_secret_key(sys.argv[1])


#####################


# v3
import argparse
import base64
import hashlib
import hmac


def hash_iam_secret(sakey, version):
    key_bytes = str.encode(sakey)
    message_bytes = str.encode('SendRawEmail')
    version_bytes = str.encode(version)
    dig = hmac.new(key_bytes, message_bytes, digestmod=hashlib.sha256)
    return base64.b64encode(version_bytes+dig.digest()).decode()


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('iam_secret_access_key',
                        type=str,
                        help='The AWS IAM secret access key')
    parser.add_argument('version',
                        type=str,
                        nargs='?',
                        default='\0x2',
                        help='Optional version number, default is 2')
    args = parser.parse_args()

    if len(args.iam_secret_access_key) != 40:
        print('AWS secret access keys should be 40 characters.')
    else:
        dig = hash_iam_secret(args.iam_secret_access_key,
                              args.version)

    print(dig)


if __name__ == '__main__':
    main()

Go

Thanks @talreg

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
)

const (
	awsMessageKey          = "SendRawEmail"
	awsMessageVersion byte = 0x02
)

// GenerateSMTPPasswordFromSecret - generate smtp password from a given aws secret
func GenerateSMTPPasswordFromSecret(secret string) (string, error) {
	mac := hmac.New(sha256.New, []byte(secret))
	mac.Write([]byte(awsMessageKey))
	value1 := mac.Sum(nil)
	infoWithSignature := append([]byte{}, awsMessageVersion)
	infoWithSignature = append(infoWithSignature, value1...)

	return base64.StdEncoding.EncodeToString(infoWithSignature), nil
}

PowerShell

https://gist.github.com/jacqueskang/96c444ee01e6a4b37300aa49e8097513

$key = "${SecretAccessKey}";
$region = "${AWS::Region}";

$date = "11111111";
$service = "ses";
$terminal = "aws4_request";
$message = "SendRawEmail";
$versionInBytes = 0x04;

function HmacSha256($text, $key2) {
    $hmacsha = New-Object System.Security.Cryptography.HMACSHA256
    $hmacsha.key = $key2;
    $hmacsha.ComputeHash([Text.Encoding]::UTF8.GetBytes($text));
}

$signature = [Text.Encoding]::UTF8.GetBytes("AWS4" + $key)
$signature = HmacSha256 "$date" $signature;
$signature = HmacSha256 "$region" $signature;
$signature = HmacSha256 "$service" $signature;
$signature = HmacSha256 "$terminal" $signature;
$signature = HmacSha256 "$message" $signature;
$signatureAndVersion = [System.Byte[]]::CreateInstance([System.Byte], $signature.Length + 1);
$signatureAndVersion[0] = $versionInBytes;
$signature.CopyTo($signatureAndVersion, 1);
$smtpPassword = [Convert]::ToBase64String($signatureAndVersion);

Write-Host $smtpPassword;

Java

I'm not a Java programmer, yet, but AWS's documentation [http://docs.aws.amazon.com/ses/latest/DeveloperGuide/smtp-credentials.html#smtp-credentials-convert] has a snippet you can use

I spent way too much time figuring this stuff out. I hope this helps!!!

HAPPY SES-ing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment