Skip to content

SKI Encryption Examples

Andrew Lambert edited this page Dec 18, 2022 · 15 revisions

Secret key encryption

libsodium offers facilities to encrypt and decrypt data using a pre-shared secret key. Both users must already posses the secret key, or it must be negotiated somehow.

These examples demonstrate how to encrypt and decrypt short messages that can fit into memory. Refer to the SecretStream example for a demonstration of encryption and decryption of large streams or files. To generate a message authentication code for a large stream or file, use the GenericHashDigest class with a SecretKey.

Generate a new random key

  Dim key As libsodium.SKI.SecretKey
  key = key.Generate()

Generate a new 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.SKI.SecretKey(passwd, passwd.RandomSalt, libsodium.ResourceLimits.Interactive)

Encrypt data

  Dim key As libsodium.SKI.SecretKey
  key = key.Generate() ' random key for example
  Dim nonce As MemoryBlock = key.RandomNonce ' must be stored/sent with the message
  Dim ciphertext As MemoryBlock = libsodium.SKI.EncryptData("Hello, world!", key, nonce)

Decrypt data

  Dim key As libsodium.SKI.SecretKey
  key = key.Generate() ' random key for example
  Dim ciphertext As MemoryBlock ' the encrypted message, assume valid for example
  Dim nonce As MemoryBlock = TheNonce ' must be the same nonce used to encrypt
  Dim cleartext As MemoryBlock = libsodium.SKI.DecryptData(ciphertext, key, nonce)

Generate and validate a message authentication code

  Dim key As libsodium.SKI.SecretKey
  key = key.Generate() ' random key for example
  Dim msg As MemoryBlock = "Hello, world!"
  Dim mac As MemoryBlock = libsodium.SKI.GenerateMAC(msg, key)
  
  If libsodium.SKI.VerifyMAC(mac, msg, key) Then
    MsgBox("MAC verified")
  Else
    MsgBox("MAC not verified")
  End If
Clone this wiki locally