Sample code for 30+ languages & platforms
SQL Server

Diffie-Hellman Key Exchange (DH)

See more Diffie-Hellman Examples

Diffie-Hellman key exchange (DH) is a cryptographic protocol that allows two parties that have no prior knowledge of each other to jointly establish a shared secret key.

This example demonstrates how two parties (Alice and Bob) can compute an N-bit shared secret key without the key ever being transmitted.

Chilkat SQL Server Downloads

SQL Server
-- Important: See this note about string length limitations for strings returned by sp_OAMethod calls.
--
CREATE PROCEDURE ChilkatSample
AS
BEGIN
    DECLARE @hr int
    DECLARE @success int
    SELECT @success = 0

    -- This example requires the Chilkat API to have been previously unlocked.
    -- See Global Unlock Sample for sample code.

    -- Create two separate instances of the DH object.
    DECLARE @dhBob int
    EXEC @hr = sp_OACreate 'Chilkat.Dh', @dhBob OUT
    IF @hr <> 0
    BEGIN
        PRINT 'Failed to create ActiveX component'
        RETURN
    END

    DECLARE @dhAlice int
    EXEC @hr = sp_OACreate 'Chilkat.Dh', @dhAlice OUT

    -- The DH algorithm begins with a large prime, P, and a generator, G.  
    -- These don't have to be secret, and they may be transmitted over an insecure channel.  
    -- The generator is a small integer and typically has the value 2 or 5.

    -- The Chilkat DH component provides the ability to use known
    -- "safe" primes, as well as a method to generate new safe primes.

    -- This example will use a known safe prime.  Generating
    -- new safe primes is a time-consuming CPU intensive task
    -- and is normally done offline.

    -- Bob will choose to use the 2nd of our 8 pre-chosen safe primes.  
    -- It is the Prime for the 2nd Oakley Group (RFC 2409) -- 
    -- 1024-bit MODP Group.  Generator is 2. 
    -- The prime is: 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }
    EXEC sp_OAMethod @dhBob, 'UseKnownPrime', NULL, 2

    -- The computed shared secret will be equal to the size of the prime (in bits).
    -- In this case the prime is 1024 bits, so the shared secret will be 128 bytes (128 * 8 = 1024).
    -- However, the result is returned as an SSH1-encoded bignum in hex string format.
    -- The SSH1-encoding prepends a 2-byte count, so the result is going  to be 2 bytes
    -- longer: 130 bytes.  This results in a hex string that is 260 characters long (two chars
    -- per byte for the hex encoding).

    DECLARE @p nvarchar(4000)

    DECLARE @g int

    -- Bob will now send P and G to Alice.
    EXEC sp_OAGetProperty @dhBob, 'P', @p OUT
    EXEC sp_OAGetProperty @dhBob, 'G', @g OUT

    -- Alice calls SetPG to set P and G.  SetPG checks
    -- the values to make sure it's a safe prime and will
    -- return 0 if not.
    EXEC sp_OAMethod @dhAlice, 'SetPG', @success OUT, @p, @g
    IF @success <> 1
      BEGIN

        PRINT 'P is not a safe prime'
        EXEC @hr = sp_OADestroy @dhBob
        EXEC @hr = sp_OADestroy @dhAlice
        RETURN
      END

    -- Each side begins by generating an "E"
    -- value.  The CreateE method has one argument: numBits.
    -- It should be set to twice the size of the number of bits
    -- in the session key.

    -- Let's say we want to generate a 128-bit session key
    -- for AES encryption.  The shared secret generated by the Diffie-Hellman
    -- algorithm will be longer, so we'll hash the result to arrive at the
    -- desired session key length.  However, the length of the session
    -- key we'll utlimately produce determines the value that should be
    -- passed to the CreateE method.

    -- In this case, we'll be creating a 128-bit session key, so pass 256 to CreateE.
    -- This setting is for security purposes only -- the value
    -- passed to CreateE does not change the length of the shared secret
    -- that is produced by Diffie-Hellman.  
    -- Also, there is no need to pass in a value larger
    -- than 2 times the expected session key length.  It suffices to
    -- pass exactly 2 times the session key length.

    -- Bob generates a random E (which has the mathematical
    -- properties required for DH).
    DECLARE @eBob nvarchar(4000)

    EXEC sp_OAMethod @dhBob, 'CreateE', @eBob OUT, 256

    -- Alice does the same:
    DECLARE @eAlice nvarchar(4000)

    EXEC sp_OAMethod @dhAlice, 'CreateE', @eAlice OUT, 256

    -- The "E" values are sent over the insecure channel.
    -- Bob sends his "E" to Alice, and Alice sends her "E" to Bob.

    -- Each side computes the shared secret by calling FindK.
    -- "K" is the shared-secret.

    DECLARE @kBob nvarchar(4000)

    DECLARE @kAlice nvarchar(4000)

    -- Bob computes the shared secret from Alice's "E":
    EXEC sp_OAMethod @dhBob, 'FindK', @kBob OUT, @eAlice

    -- Alice computes the shared secret from Bob's "E":
    EXEC sp_OAMethod @dhAlice, 'FindK', @kAlice OUT, @eBob

    -- Amazingly, kBob and kAlice are identical and the expected
    -- length (260 characters).  The strings contain the hex encoded bytes of
    -- our shared secret:

    PRINT 'Bob''s shared secret:'

    PRINT @kBob

    PRINT 'Alice''s shared secret (should be equal to Bob''s)'

    PRINT @kAlice

    -- To arrive at a 128-bit session key for AES encryption, Bob and Alice should
    -- both transform the raw shared secret using a hash algorithm that produces
    -- the size of session key desired.   MD5 produces a 16-byte (128-bit) result, so
    -- this is a good choice for 128-bit AES.

    -- To produce the session key:
    DECLARE @crypt int
    EXEC @hr = sp_OACreate 'Chilkat.Crypt2', @crypt OUT

    EXEC sp_OASetProperty @crypt, 'EncodingMode', 'hex'
    EXEC sp_OASetProperty @crypt, 'HashAlgorithm', 'md5'

    DECLARE @sessionKey nvarchar(4000)

    EXEC sp_OAMethod @crypt, 'HashStringENC', @sessionKey OUT, @kBob


    PRINT '128-bit Session Key:'

    PRINT @sessionKey

    -- Encrypt something...
    EXEC sp_OASetProperty @crypt, 'CryptAlgorithm', 'aes'
    EXEC sp_OASetProperty @crypt, 'KeyLength', 128
    EXEC sp_OASetProperty @crypt, 'CipherMode', 'cbc'

    -- Use an IV that is the MD5 hash of the session key...
    DECLARE @iv nvarchar(4000)

    EXEC sp_OAMethod @crypt, 'HashStringENC', @iv OUT, @sessionKey

    -- AES uses a 16-byte IV:

    PRINT 'Initialization Vector:'

    PRINT @iv

    EXEC sp_OAMethod @crypt, 'SetEncodedKey', NULL, @sessionKey, 'hex'
    EXEC sp_OAMethod @crypt, 'SetEncodedIV', NULL, @iv, 'hex'

    -- Encrypt some text:
    DECLARE @cipherText64 nvarchar(4000)

    EXEC sp_OASetProperty @crypt, 'EncodingMode', 'base64'
    EXEC sp_OAMethod @crypt, 'EncryptStringENC', @cipherText64 OUT, 'The quick brown fox jumps over the lazy dog'

    PRINT @cipherText64

    DECLARE @plainText nvarchar(4000)

    EXEC sp_OAMethod @crypt, 'DecryptStringENC', @plainText OUT, @cipherText64


    PRINT @plainText

    EXEC @hr = sp_OADestroy @dhBob
    EXEC @hr = sp_OADestroy @dhAlice
    EXEC @hr = sp_OADestroy @crypt


END
GO