Skip to content

Instantly share code, notes, and snippets.

@plugnburn
Last active November 17, 2023 21:10
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save plugnburn/fb4246164690632e7632 to your computer and use it in GitHub Desktop.
Save plugnburn/fb4246164690632e7632 to your computer and use it in GitHub Desktop.
Sample Diffie-Hellman key exchange helper implementation in Bash (depends on dc for bigint and od for secret generation)
#!/bin/bash
# RFC 3526 prime and base (id 14, 2048-bit)
PRIME='FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F4
4C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED52907709
6966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFF
FFFFFFFFFFFF'
BASE=2
# large hex number sanitizer
cleannum() {
echo "$@"|tr -d ' \n\\'|tr a-f A-F
}
# actual modular exponentiation via dc
# modexp $base $exp $mod
modexp() {
cleannum $(echo "16dio$(cleannum $1) $(cleannum $2) $(cleannum $3)|p"|dc)
}
#main action
case $1 in
secret)
echo $(cleannum $(head -c 16 /dev/urandom|od -A n -v -t x1))
;;
public)
echo $(modexp "$BASE" "$2" "$PRIME")
;;
session)
echo $(modexp "$3" "$2" "$PRIME")
;;
*)
echo -e "Usage: $0 (secret|public your_secret|session your_secret other_party_public)"
;;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment