Skip to content

libsodium.SKI.SecretStream

Andrew Lambert edited this page Nov 26, 2022 · 23 revisions

libsodium.SKI.SecretStream

Class Declaration

 Protected Class SecretStream
 Implements Readable,Writeable

Remarks

This class uses the XChaCha20 cipher to encrypt or decrypt a stream of data with a secret key, and uses the Poly1305 message authentication scheme to authenticate the stream and (optionally) associated unencrypted data (i.e. AEAD). Encryption, decryption, and authentication use the same key, so it must be kept secret at all times.

Encryption is done in chunks. When calling the Read(Integer, TextEncoding) and Write(String) methods the stream is buffered to allow read/write requests of arbitrary length without any associated unencrypted data. The other Read and Write methods perform authenticated encryption with associated data (AEAD) without buffering, meaning you must read/write exactly one chunk at a time.

The encryption is symmetric and so uses a secret key. This can either be a SecretKey if the data will be decrypted by the same user that encrypted it, or a SharedSecret derived from the sender's private key and the recipient's public key.

Example

This example encrypts a file and saves the decryption header/initialization vector to another file:

  Dim mykey As libsodium.SKI.SecretKey
  mykey = mykey.Generate() ' random key for example
  
  Dim src As FolderItem = GetOpenFolderItem("")
  Dim state As FolderItem = src.Parent.Child(src.Name + ".state")
  Dim dst As FolderItem = src.Parent.Child(src.Name + ".crypt")
  
  Dim bsin As BinaryStream = BinaryStream.Open(src)
  Dim bsout As BinaryStream = BinaryStream.Create(dst)
  Dim stream As libsodium.SKI.SecretStream
  stream = stream.Create(mykey, bsout)
  
  Do Until bsin.EOF
    stream.Write(bsin.Read(1024 * 64))
  Loop
  
  Call stream.ExportDecryptionHeader(state)
  stream.Close()
  bsout.Close()
  bsin.Close()

This example decrypts the file from the previous example:

  ' continuing from above
  bsin = BinaryStream.Open(dst)
  bsout = BinaryStream.Create(src.Parent.Child(src.Name + ".decrypted"))
  stream = stream.Open(mykey, bsin, state)
  
  Do Until stream.EOF Or stream.ReadError
    bsout.Write(stream.Read(1024 * 64))
  Loop
  
  stream.Close()
  bsout.Close()
  bsin.Close()

Methods

Properties

Shared methods

See also

Clone this wiki locally