OCamlnet-4 does not include any implementations of cryptographic ciphers or hashes. It does, however, include a binding to GnuTLS and GNU Nettle, providing cryptography, and it defines a number of helper functions to use cryptography efficiently.
Before OCamlnet-4, some modules used Xavier Leroy's Cryptokit. This dependency is gone now.
Like for TLS (see Tls
), first-class modules are used to modularize
the provider of the crypto functions:
Netsys_crypto_types.SYMMETRIC_CRYPTO
: Defines symmetric ciphersNetsys_crypto_types.DIGESTS
: Defines digests (hashes)Netsys_crypto_types.PUBKEY_CRYPTO
: Defines public-key ciphers
Netsys_crypto.current_symmetric_crypto
Netsys_crypto.current_digests
Netsys_crypto.current_pubkey_crypto
Nettls_gnutls.init()
It is not advised to call any functions of the providers directly: the API is not yet stable, and may change, and there are some inconveniences in the buffer management. Instead, use the following functionality:
Netsys_ciphers
is the main user-oriented API for encrypting or decrypting
a message with symmetric ciphersNetsys_digests
is the main API for digesting messages.Netx509_pubkey
and Netx509_pubkey_crypto
is the API for using
public key cryptography according to X509.
Encrypt a string s
with AES-128 in CBC mode and length-style padding:
let key = "0123456789abcdef"
let iv = "0123456789abcdef"
let cipher = Netsys_ciphers.find ("AES-128", "CBC")
let ctx = cipher # create key `Length
let () = ctx # set_iv iv
let s_enc = ctx # encrypt_string s
Compute the SHA1 digest of a string s
:
let digest = Netsys_digests.find "SHA1-160"
let ctx = digest # create()
let () = ctx # add_substring s 0 (String.length s)
let result = ctx # finish()
If using nettls-gnutls as provider, you can normally expect:
If using a recent version of GnuTLS/Nettls:
If using nettls-gnutls as provider, you can normally expect:
You can normally use for encryption: