Skip to content

PKI Encryption Examples

Andrew Lambert edited this page Aug 2, 2019 · 8 revisions

Public key encryption

libsodium offers facilities to encrypt and decrypt data using the private key of one user and the public key of the other. Both users can derive the shared key using only their private key and the other user's public key; nothing secret needs to be exchanged.

These examples all perform authenticated encryption. That means that encrypted messages include a Message Authentication Code (MAC) that attests to the authenticity of the encrypted message, much like a digital signature except that only the recipient can verify it.

Generate a new random encryption key

  Dim key As libsodium.PKI.EncryptionKey
  key = key.Generate()

Generate a new encryption key from a seed

Use the same seed to generate the same key

  Dim key As libsodium.PKI.EncryptionKey
  key = key.Generate(key.RandomSeed)

Generate a new encryption key from a password (PBKDF2)

Use the same password, salt, and resource limits to generate the same key

  Dim passwd As libsodium.Password = "seekritpassword"
  Dim key As New libsodium.PKI.EncryptionKey(passwd, passwd.RandomSalt, libsodium.ResourceLimits.Interactive)

Encrypt data

  Dim mykey As libsodium.PKI.EncryptionKey
  mykey = mykey.Generate() ' random key for example
  Dim theirkey As New libsodium.PKI.ForeignKey(mykey.Generate) ' the recipient's public key, random for example
  Dim nonce As MemoryBlock = mykey.RandomNonce ' must be stored/sent with the message

  Dim crypttext As MemoryBlock = libsodium.PKI.EncryptData("Hello, world!", theirkey, mykey, nonce)

Decrypt data

  Dim mykey As libsodium.PKI.EncryptionKey
  mykey = mykey.Generate() ' random key for example
  Dim theirkey As New libsodium.PKI.ForeignKey(mykey.Generate) ' the sender's public key, random for example
  Dim nonce As MemoryBlock = TheNonce ' must be the same nonce used to encrypt
  Dim EncryptedData As MemoryBlock ' the encrypted message, assume valid for example
  Dim cleartext As MemoryBlock = libsodium.PKI.DecryptData(EncryptedData, theirkey, mykey, nonce)

Calculate the shared key

  Dim mykey As libsodium.PKI.EncryptionKey
  mykey = mykey.Generate() ' random key for example
  Dim theirkey As New libsodium.PKI.ForeignKey(mykey.Generate) ' the sender's public key, random for example
  Dim sharedkey As New libsodium.PKI.SharedSecret(theirkey, mykey)
Clone this wiki locally