Skip to content

Instantly share code, notes, and snippets.

@byt3bl33d3r
Last active October 16, 2018 23:02
Show Gist options
  • Save byt3bl33d3r/6d2dbf2c7fc68031e859e8352269d8d3 to your computer and use it in GitHub Desktop.
Save byt3bl33d3r/6d2dbf2c7fc68031e859e8352269d8d3 to your computer and use it in GitHub Desktop.
ECDH Encrypted Key Exchange (IronPython 2.7.8)
from System.IO import MemoryStream
from System.Text import Encoding
from System.Security.Cryptography import Aes, AsymmetricAlgorithm, CryptoStream, CryptoStreamMode
class DiffieHellman:
def __init__(self):
self.aes = Aes.Create()
self.diffieHellman = AsymmetricAlgorithm.Create("ECDiffieHellmanCng")
self.PublicKey = self.diffieHellman.PublicKey.ToByteArray()
self.IV = self.aes.IV
def Encrypt(self, publicKey, secretMessage):
CngKey = self.diffieHellman.PublicKey.Import()
key = CngKey.Import(publicKey, self.diffieHellman.PublicKey.BlobFormat)
derivedKey = self.diffieHellman.DeriveKeyMaterial(key)
#print "Derived Key: {}".format(derivedKey)
self.aes.Key = derivedKey
with MemoryStream() as cipherText:
with self.aes.CreateEncryptor() as encryptor:
with CryptoStream(cipherText, encryptor, CryptoStreamMode.Write) as cryptoStream:
ciphertextMessage = Encoding.UTF8.GetBytes(secretMessage)
cryptoStream.Write(ciphertextMessage, 0, ciphertextMessage.Length)
return cipherText.ToArray()
def Decrypt(self, publicKey, encryptedMessage, iv):
CngKey = self.diffieHellman.PublicKey.Import()
key = CngKey.Import(publicKey, self.diffieHellman.PublicKey.BlobFormat)
derivedKey = self.diffieHellman.DeriveKeyMaterial(key)
#print "Derived Key: {}".format(derivedKey)
self.aes.Key = derivedKey
self.aes.IV = iv
with MemoryStream() as plainText:
with self.aes.CreateDecryptor() as decryptor:
with CryptoStream(plainText, decryptor, CryptoStreamMode.Write) as cryptoStream:
cryptoStream.Write(encryptedMessage, 0, encryptedMessage.Length)
return Encoding.UTF8.GetString(plainText.ToArray())
text = "Hello World!"
bob = DiffieHellman()
alice = DiffieHellman()
secretMessage = bob.Encrypt(alice.PublicKey, text)
#print secretMessage
decryptedMessage = alice.Decrypt(bob.PublicKey, secretMessage, bob.IV)
print decryptedMessage
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment