text:
LuaJIT FFI bindings for [Nettle](http://www.lysator.liu.se/~nisse/nettle/nettle.html) (a low-level cryptographic library)

## Status

All the bindings that do not depend on [GMP](https://gmplib.org/) are ready to use. The [GMP](https://gmplib.org/) depended functionality is the [public-key algorithms](http://www.lysator.liu.se/~nisse/nettle/nettle.html#Public_002dkey-algorithms) (i.e. RSA, DSA, and ECDSA), and ONLY the RSA functions have some support right now, although the APIs might change. Much of the documentation here is copied from [Nettle's documentation](http://www.lysator.liu.se/~nisse/nettle/nettle.html), but I have included Lua examples to it. I will be adding more documentation shortly.

## Synopsis

```lua
local function hex(str, spacer)
    return (string.gsub(str, "(.)", function (c)
        return string.format("%02X%s", string.byte(c), spacer or "")
    end))
end

do
    local md2 = require "resty.nettle.md2"
    print("md2      ", #md2(""), hex(md2("")))
    local hash = md2.new()
    hash:update("")
    print("md2     ", #hash:digest(), hex(hash:digest()))
end

do
    local md4 = require "resty.nettle.md4"
    print("md4      ", #md4(""), hex(md4("")))
    local hash = md4.new()
    hash:update("")
    print("md4      ", #hash:digest(), hex(hash:digest()))
end

do
    local md5 = require "resty.nettle.md5"
    print("md5      ", #md5(""), hex(md5("")))
    local hash = md5.new()
    hash:update("")
    print("md5      ", #hash:digest(), hex(hash:digest()))
end

do
    local ripemd160 = require "resty.nettle.ripemd160"
    local hash = ripemd160.new()
    hash:update("")
    print("ripemd160", #hash:digest(), hex(hash:digest()))
end

do
    local gosthash94 = require "resty.nettle.gosthash94"
    local hash = gosthash94.new()
    hash:update("")
    print("gosthash94", #hash:digest(), hex(hash:digest()))
end

do
    local sha1 = require "resty.nettle.sha1"
    print("sha1      ", #sha1(""), hex(sha1("")))
    local hash = sha1.new()
    hash:update("")
    print("sha1     ", #hash:digest(), hex(hash:digest()))
end

do
    local sha1 = require "resty.nettle.sha1"
    print("sha1      ", #sha1(""), hex(sha1("")))
    local hash = sha1.new()
    hash:update("")
    print("sha1     ", #hash:digest(), hex(hash:digest()))
end

do
    local sha2 = require "resty.nettle.sha2"

    local hash = sha2.sha224.new()
    hash:update("")
    print("sha224      ", #hash:digest(), hex(hash:digest()))
    print("sha224      ", #sha2.sha224(""), hex(sha2.sha224("")))

    local hash = sha2.sha256.new()
    hash:update("")
    print("sha256      ", #hash:digest(), hex(hash:digest()))
    print("sha256      ", #sha2.sha256(""), hex(sha2.sha256("")))

    local hash = sha2.sha384.new()
    hash:update("")
    print("sha384      ", #hash:digest(), hex(hash:digest()))
    print("sha384      ", #sha2.sha384(""), hex(sha2.sha384("")))

    local hash = sha2.sha512.new()
    hash:update("")
    print("sha512      ", #hash:digest(), hex(hash:digest()))
    print("sha512      ", #sha2.sha512(""), hex(sha2.sha512("")))

    local hash = sha2.sha512_224.new()
    hash:update("")
    print("sha512_224", #hash:digest(), hex(hash:digest()))
    print("sha512_224", #sha2.sha512_224(""), hex(sha2.sha512_224("")))

    local hash = sha2.sha512_256.new()
    hash:update("")
    print("sha512_256", #hash:digest(), hex(hash:digest()))
    print("sha512_256", #sha2.sha512_256(""), hex(sha2.sha512_256("")))
end

do
    local sha3 = require "resty.nettle.sha3"

    local hash = sha3.sha224.new()
    hash:update("")
    print("sha3 224", #hash:digest(), hex(hash:digest()))

    local hash = sha3.sha256.new()
    hash:update("")
    print("sha3 256", #hash:digest(), hex(hash:digest()))

    local hash = sha3.sha384.new()
    hash:update("")
    print("sha3 384", #hash:digest(), hex(hash:digest()))

    local hash = sha3.sha512.new()
    hash:update("")
    print("sha3 512", #hash:digest(), hex(hash:digest()))
end

do
    local hmac = require "resty.nettle.hmac"
    print("hmac md5", #hmac("md5", "a", "a"), hex(hmac("md5", "a", "a")))
    print("hmac md5", #hmac.md5("a", "a"), hex(hmac.md5("a", "a")))
    local hash = hmac.md5.new("a")
    hash:update("a")
    local dgst = hash:digest()
    print("hmac md5", #dgst, hex(dgst))

    local hash = hmac.ripemd160.new("a")
    hash:update("a")
    local dgst = hash:digest()
    print("hmac ripemd160", #dgst, hex(dgst))

    local hash = hmac.sha1.new("a")
    hash:update("a")
    local dgst = hash:digest()
    print("hmac sha1", #dgst, hex(dgst))

    local hash = hmac.sha224.new("a")
    hash:update("a")
    local dgst = hash:digest()
    print("hmac sha224", #dgst, hex(dgst))

    local hash = hmac.sha256.new("a")
    hash:update("a")
    local dgst = hash:digest()
    print("hmac sha256", #dgst, hex(dgst))

    local hash = hmac.sha384.new("a")
    hash:update("a")
    local dgst = hash:digest()
    print("hmac sha384", #dgst, hex(dgst))

    local hash = hmac.sha512.new("a")
    hash:update("a")
    local dgst = hash:digest()
    print("hmac sha512", #dgst, hex(dgst))
end

do
    local umac = require "resty.nettle.umac"
    local hash = umac.umac32.new("umac32")
    hash:update("")
    local dgst = hash:digest()
    print("umac32     ", #dgst, hex(dgst))

    local hash = umac.umac64.new("umac64")
    hash:update("")
    local dgst = hash:digest()
    print("umac64     ", #dgst, hex(dgst))

    local hash = umac.umac96.new("umac96")
    hash:update("")
    local dgst = hash:digest()
    print("umac96     ", #dgst, hex(dgst))

    local hash = umac.umac128.new("umac128")
    hash:update("")
    local dgst = hash:digest()
    print("umac128     ", #dgst, hex(dgst))
end

do
    local poly = require "resty.nettle.poly1305"
    local hash = poly.new("poly")
    hash:update("")
    local dgst = hash:digest()
    print("poly1305    ", #dgst, hex(dgst))
end

do
    local pbkdf2 = require "resty.nettle.pbkdf2"
    local hmac = pbkdf2.hmac_sha1("password", 1, "salt", 20)
    print("pbkdf2 sha1", #hmac, hex(hmac))
    local hmac = pbkdf2.hmac_sha256("pass\0word", 4096, "sa\0lt", 32)
    print("pbkdf2 sha256", #hmac, hex(hmac))
end

print()

do
    local aes = require "resty.nettle.aes"
    local aes128 = aes.new("testtesttesttest")
    local ciphertext = aes128:encrypt("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
    print("aes128 encrypt", #ciphertext, hex(ciphertext))
    local aes128 = aes.new("testtesttesttest")
    local plaintext = aes128:decrypt(ciphertext)
    print("aes128 decrypt", #plaintext, plaintext)

    print()

    local aes128 = aes.new("testtesttesttest", "cbc", "testtesttesttest")
    local ciphertext = aes128:encrypt("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
    print("aes128 cbc enc", #ciphertext, hex(ciphertext))
    local aes128 = aes.new("testtesttesttest", "cbc", "testtesttesttest")
    local plaintext = aes128:decrypt(ciphertext)
    print("aes128 cbc dec", #plaintext, plaintext)

    print()

    local aes128 = aes.new("testtesttesttest", "ctr", "testtesttesttest")
    local ciphertext = aes128:encrypt("a")
    print("aes128 ctr enc", #ciphertext, hex(ciphertext))
    local aes128 = aes.new("testtesttesttest", "ctr", "testtesttesttest")
    local plaintext = aes128:decrypt(ciphertext)
    print("aes128 ctr dec", #plaintext, plaintext)

    print()

    local aes128 = aes.new("testtesttesttest", "eax", "testtesttest")
    local ciphertext, digest = aes128:encrypt("a")
    print("aes128 eax enc", #ciphertext, hex(ciphertext))
    print("aes128 eax dgst", #digest, hex(digest))
    local aes128 = aes.new("testtesttesttest", "eax", "testtesttest")
    local plaintext, digest = aes128:decrypt(ciphertext)
    print("aes128 eax dec", #plaintext, plaintext)
    print("aes128 eax dgst", #digest, hex(digest))

    print()

    local aes128 = aes.new("testtesttesttest", "gcm", "testtesttest")
    local ciphertext, digest = aes128:encrypt("a")
    print("aes128 gcm enc", #ciphertext, hex(ciphertext))
    print("aes128 gcm dgst", #digest, hex(digest))
    local aes128 = aes.new("testtesttesttest", "gcm", "testtesttest")
    local plaintext, digest = aes128:decrypt(ciphertext)
    print("aes128 gcm dec", #plaintext, plaintext)
    print("aes128 gcm dgst", #digest, hex(digest))

    print()

    local aes128 = aes.new("testtesttesttest", "ccm", "testtesttest")
    local ciphertext, digest = aes128:encrypt("a")
    print("aes128 ccm enc", #ciphertext, hex(ciphertext))
    print("aes128 ccm dgst", #digest, hex(digest))
    local aes128 = aes.new("testtesttesttest", "ccm", "testtesttest")
    local plaintext, digest = aes128:decrypt(ciphertext)
    print("aes128 ccm dec", #plaintext, plaintext)
    print("aes128 ccm dgst", #digest, hex(digest))

    print()

    local aes192 = aes.new("testtesttesttesttesttest")
    local ciphertext = aes192:encrypt("a")
    print("aes192 encrypt", #ciphertext, hex(ciphertext))
    local aes192 = aes.new("testtesttesttesttesttest")
    local plaintext = aes192:decrypt(ciphertext)
    print("aes192 decrypt", #plaintext, plaintext)

    print()

    local aes192 = aes.new("testtesttesttesttesttest", "cbc", "testtesttesttest")
    local ciphertext = aes192:encrypt("a")
    print("aes192 cbc enc", #ciphertext, hex(ciphertext))
    local aes192 = aes.new("testtesttesttesttesttest", "cbc", "testtesttesttest")
    local plaintext = aes192:decrypt(ciphertext)
    print("aes192 cbc dec", #plaintext, plaintext)

    print()

    local aes192 = aes.new("testtesttesttesttesttest", "ctr", "testtesttesttest")
    local ciphertext = aes192:encrypt("a")
    print("aes192 ctr enc", #ciphertext, hex(ciphertext))
    local aes192 = aes.new("testtesttesttesttesttest", "ctr", "testtesttesttest")
    local plaintext = aes192:decrypt(ciphertext)
    print("aes192 ctr dec", #plaintext, plaintext)

    print()

    local aes192 = aes.new("testtesttesttesttesttest", "gcm", "testtesttest")
    local ciphertext, digest = aes192:encrypt("a")
    print("aes192 gcm enc", #ciphertext, hex(ciphertext))
    print("aes192 gcm dgst", #digest, hex(digest))
    local aes192 = aes.new("testtesttesttesttesttest", "gcm", "testtesttest")
    local plaintext, digest = aes192:decrypt(ciphertext)
    print("aes192 gcm dec", #plaintext, plaintext)
    print("aes192 gcm dgst", #digest, hex(digest))

    print()

    local aes192 = aes.new("testtesttesttesttesttest", "ccm", "testtesttest")
    local ciphertext, digest = aes192:encrypt("a")
    print("aes192 ccm enc", #ciphertext, hex(ciphertext))
    print("aes192 ccm dgst", #digest, hex(digest))
    local aes192 = aes.new("testtesttesttesttesttest", "ccm", "testtesttest")
    local plaintext, digest = aes192:decrypt(ciphertext)
    print("aes192 ccm dec", #plaintext, plaintext)
    print("aes192 ccm dgst", #digest, hex(digest))

    print()

    local aes256 = aes.new("testtesttesttesttesttesttesttest")
    local ciphertext = aes256:encrypt("a")
    print("aes256 encrypt", #ciphertext, hex(ciphertext))
    local aes256 = aes.new("testtesttesttesttesttesttesttest")
    local plaintext = aes256:decrypt(ciphertext)
    print("aes256 decrypt", #plaintext, plaintext)

    print()

    local aes256 = aes.new("testtesttesttesttesttesttesttest", "cbc", "testtesttesttest")
    local ciphertext = aes256:encrypt("a")
    print("aes256 cbc enc", #ciphertext, hex(ciphertext))
    local aes256 = aes.new("testtesttesttesttesttesttesttest", "cbc", "testtesttesttest")
    local plaintext = aes256:decrypt(ciphertext)
    print("aes256 cbc dec", #plaintext, plaintext)

    print()

    local aes256 = aes.new("testtesttesttesttesttesttesttest", "ctr", "testtesttesttest")
    local ciphertext = aes256:encrypt("a")
    print("aes256 ctr enc", #ciphertext, hex(ciphertext))
    local aes256 = aes.new("testtesttesttesttesttesttesttest", "ctr", "testtesttesttest")
    local plaintext = aes256:decrypt(ciphertext)
    print("aes256 ctr dec", #plaintext, plaintext)

    print()

    local aes256 = aes.new("testtesttesttesttesttesttesttest", "gcm", "testtesttest", "testtesttesttest1asdasdasdasdasdasdasdasdasdasdasdasdasdasdasd")
    local ciphertext, digest = aes256:encrypt("a")
    print("aes256 gcm enc", #ciphertext, hex(ciphertext))
    print("aes256 gcm dgst", #digest, hex(digest))
    local aes256 = aes.new("testtesttesttesttesttesttesttest", "gcm", "testtesttest", "testtesttesttest1asdasdasdasdasdasdasdasdasdasdasdasdasdasdasd")
    local plaintext, digest = aes256:decrypt(ciphertext)
    print("aes256 gcm dec", #plaintext, plaintext)
    print("aes256 gcm dgst", #digest, hex(digest))

    print()

    local aes256 = aes.new("testtesttesttesttesttesttesttest", "ccm", "testtesttest", "testtesttesttest1asdasdasdasdasdasdasdasdasdasdasdasdasdasdasd")
    local ciphertext, digest = aes256:encrypt("a")
    print("aes256 ccm enc", #ciphertext, hex(ciphertext))
    print("aes256 ccm dgst", #digest, hex(digest))
    local aes256 = aes.new("testtesttesttesttesttesttesttest", "ccm", "testtesttest", "testtesttesttest1asdasdasdasdasdasdasdasdasdasdasdasdasdasdasd")
    local plaintext, digest = aes256:decrypt(ciphertext)
    print("aes256 ccm dec", #plaintext, plaintext)
    print("aes256 ccm dgst", #digest, hex(digest))
end

print()

do
    local camellia = require "resty.nettle.camellia"
    local camellia128 = camellia.new("testtesttesttest")
    local ciphertext = camellia128:encrypt("a")
    print("cam128 encrypt", #ciphertext, hex(ciphertext))
    local camellia128 = camellia.new("testtesttesttest")
    local plaintext = camellia128:decrypt(ciphertext)
    print("cam128 decrypt", #plaintext, plaintext)

    print()

    local camellia128 = camellia.new("testtesttesttest", "gcm", "testtesttest")
    local ciphertext, digest = camellia128:encrypt("a")
    print("cam128 gcm enc", #ciphertext, hex(ciphertext))
    print("cam128 gcm dgst", #digest, hex(digest))
    local camellia128 = camellia.new("testtesttesttest", "gcm", "testtesttest")
    local plaintext, digest = camellia128:decrypt(ciphertext)
    print("cam128 gcm dec", #plaintext, plaintext)
    print("cam128 gcm dgst", #digest, hex(digest))

    print()

    local camellia192 = camellia.new("testtesttesttesttesttest")
    local ciphertext = camellia192:encrypt("a")
    print("cam192 encrypt", #ciphertext, hex(ciphertext))
    local camellia192 = camellia.new("testtesttesttesttesttest")
    local plaintext = camellia192:decrypt(ciphertext)
    print("cam192 decrypt", #plaintext, plaintext)

    print()

    local camellia256 = camellia.new("testtesttesttesttesttesttesttest")
    local ciphertext = camellia256:encrypt("a")
    print("cam256 encrypt", #ciphertext, hex(ciphertext))
    local camellia256 = camellia.new("testtesttesttesttesttesttesttest")
    local plaintext = camellia256:decrypt(ciphertext)
    print("cam256 decrypt", #plaintext, plaintext)

    print()

    local camellia256 = camellia.new("testtesttesttesttesttesttesttest", "gcm", "testtesttest", "testtesttesttest1asdasdasdasdasdasdasdasdasdasdasdasdasdasdasd")
    local ciphertext, digest = camellia256:encrypt("a")
    print("cam256 gcm enc", #ciphertext, hex(ciphertext))
    print("cam256 gcm dgst", #digest, hex(digest))
    local camellia256 = camellia.new("testtesttesttesttesttesttesttest", "gcm", "testtesttest", "testtesttesttest1asdasdasdasdasdasdasdasdasdasdasdasdasdasdasd")
    local plaintext, digest = camellia256:decrypt(ciphertext)
    print("cam256 gcm dec", #plaintext, plaintext)
    print("cam256 gcm dgst", #digest, hex(digest))
end

print()

do
    local arcfour = require "resty.nettle.arcfour"
    local af = arcfour.new("testtesttesttest")
    local ciphertext = af:encrypt("a")
    print("ARCFOUR encrypt", #ciphertext, hex(ciphertext))
    local af = arcfour.new("testtesttesttest")
    local plaintext = af:decrypt(ciphertext)
    print("ARCFOUR decrypt", #plaintext, plaintext)
end

print()

do
    local blowfish = require "resty.nettle.blowfish"
    local bf = blowfish.new("testtesttesttest")
    local ciphertext = bf:encrypt("a")
    print("BLOWFISH enc", #ciphertext, hex(ciphertext))
    local bf = blowfish.new("testtesttesttest")
    local plaintext = bf:decrypt(ciphertext)
    print("BLOWFISH dec", #plaintext, plaintext)
end

print()

do
    local twofish = require "resty.nettle.twofish"
    local tf = twofish.new("testtesttesttest")
    local ciphertext = tf:encrypt("a")
    print("TWOFISH enc", #ciphertext, hex(ciphertext))
    local tf = twofish.new("testtesttesttest")
    local plaintext = tf:decrypt(ciphertext)
    print("TWOFISH dec", #plaintext, plaintext)
end

print()

do
    local serpent = require "resty.nettle.serpent"
    local sp = serpent.new("testtesttesttest")
    local ciphertext = sp:encrypt("a")
    print("SERPENT enc", #ciphertext, hex(ciphertext))
    local sp = serpent.new("testtesttesttest")
    local plaintext = sp:decrypt(ciphertext)
    print("SERPENT dec", #plaintext, plaintext)
end

print()

do
    local cast128 = require "resty.nettle.cast128"
    local ct = cast128.new("testtesttesttest")
    local ciphertext = ct:encrypt("a")
    print("CAST128 enc", #ciphertext, hex(ciphertext))
    local ct = cast128.new("testtesttesttest")
    local plaintext = ct:decrypt(ciphertext)
    print("CAST128 dec", #plaintext, plaintext)
end

print()

do
    local chacha = require "resty.nettle.chacha"
    local cc = chacha.new("testtesttesttesttesttesttesttest", "testtest")
    local ciphertext = cc:encrypt("a")
    print("ChaCha enc", #ciphertext, hex(ciphertext))
    local cc = chacha.new("testtesttesttesttesttesttesttest", "testtest")
    local plaintext = cc:decrypt(ciphertext)
    print("ChaCha dec", #plaintext, plaintext)
end

print()

do
    local salsa20 = require "resty.nettle.salsa20"
    local ss = salsa20.new("testtesttesttest", "testtest")
    local ciphertext = ss:encrypt("a")
    print("Salsa20 128 enc", #ciphertext, hex(ciphertext))
    local ss = salsa20.new("testtesttesttest", "testtest")
    local plaintext = ss:decrypt(ciphertext)
    print("Salsa20 128 dec", #plaintext, plaintext)
end

print()

do
    local salsa20 = require "resty.nettle.salsa20"
    local ss = salsa20.new("testtesttesttesttesttesttesttest", "testtest")
    local ciphertext = ss:encrypt("a")
    print("Salsa20 256 enc", #ciphertext, hex(ciphertext))
    local ss = salsa20.new("testtesttesttesttesttesttesttest", "testtest")
    local plaintext = ss:decrypt(ciphertext)
    print("Salsa20 256 dec", #plaintext, plaintext)
end

print()

do
    local salsa20 = require "resty.nettle.salsa20"
    local ss = salsa20.new("testtesttesttest", "testtest", 12)
    local ciphertext = ss:encrypt("a")
    print("Sal20r12 128 e", #ciphertext, hex(ciphertext))
    local ss = salsa20.new("testtesttesttest", "testtest", 12)
    local plaintext = ss:decrypt(ciphertext)
    print("Sal20r12 128 d", #plaintext, plaintext)
end

print()

do
    local salsa20 = require "resty.nettle.salsa20"
    local ss = salsa20.new("testtesttesttesttesttesttesttest", "testtest", 12)
    local ciphertext = ss:encrypt("a")
    print("Sal20r12 256 e", #ciphertext, hex(ciphertext))
    local ss = salsa20.new("testtesttesttesttesttesttesttest", "testtest", 12)
    local plaintext = ss:decrypt(ciphertext)
    print("Sal20r12 256 d", #plaintext, plaintext)
end

print()

do
    local chacha_poly1305 = require "resty.nettle.chacha-poly1305"
    local cp = chacha_poly1305.new("testtesttesttesttesttesttesttest", "testtesttesttest", "testtest")
    local ciphertext, digest = cp:encrypt("a")
    print("cc-p1305 enc", #ciphertext, hex(ciphertext))
    print("cc-p1305 dgst", #digest, hex(digest))
    local cp = chacha_poly1305.new("testtesttesttesttesttesttesttest", "testtesttesttest", "testtest")
    local plaintext, digest = cp:decrypt(ciphertext)
    print("cc-p1305 dec", #plaintext, plaintext)
    print("cc-p1305 dgst", #digest, hex(digest))
end

print()

do
    local des = require "resty.nettle.des"
    print("DES check   ", "testtest", des.check_parity("testtest"))
    print("DES fix     ", "testtest", des.fix_parity("testtest"))
    print("DES check   ", des.fix_parity("testtest"), des.check_parity(des.fix_parity("testtest")))
end

print()

do
    local des = require "resty.nettle.des"
    local ds, wk = des.new("testtest")
    local ciphertext = ds:encrypt("a")
    print("DES enc     ", wk, #ciphertext, hex(ciphertext))
    local ds, wk = des.new("testtest")
    local plaintext = ds:decrypt(ciphertext)
    print("DES dec     ", wk, #plaintext, plaintext)
end

print()

do
    local des = require "resty.nettle.des"
    local ds, wk = des.new("testtest", "cbc", "kalakala")
    local ciphertext = ds:encrypt("testtestkalakala")
    print("DES cbc enc ", wk, #ciphertext, hex(ciphertext))
    local ds, wk = des.new("testtest", "cbc", "kalakala")
    local plaintext = ds:decrypt(ciphertext)
    print("DES cbc dec ", wk, #plaintext, plaintext)
end

print()

do
    local des = require "resty.nettle.des"
    local ds, wk = des.new("testtest", "ctr", "kalakala")
    local ciphertext = ds:encrypt("testtestkalakala")
    print("DES ctr enc ", wk, #ciphertext, hex(ciphertext))
    local ds, wk = des.new("testtest", "ctr", "kalakala")
    local plaintext = ds:decrypt(ciphertext)
    print("DES ctr dec ", wk, #plaintext, plaintext)
end

print()

do
    local des = require "resty.nettle.des"
    print("DES3 check   ", "testtestkalakalatesttest", des.check_parity("testtestkalakalatesttest"))
    print("DES3 fix     ", "testtestkalakalatesttest", des.fix_parity("testtestkalakalatesttest"))
    print("DES3 check   ", des.fix_parity("testtestkalakalatesttest"), des.check_parity(des.fix_parity("testtestkalakalatesttest")))
end

print()

do
    local des = require "resty.nettle.des"
    local ds, wk = des.new("testtestkalakalatesttest")
    local ciphertext = ds:encrypt("a")
    print("DES3 enc     ", wk, #ciphertext, hex(ciphertext))
    local ds, wk = des.new("testtestkalakalatesttest")
    local plaintext = ds:decrypt(ciphertext)
    print("DES3 dec     ", wk, #plaintext, plaintext)
end

print()

do
    local des = require "resty.nettle.des"
    local ds, wk = des.new("testtestkalakalatesttest", "cbc", "kalakala")
    local ciphertext = ds:encrypt("testtestkalakala")
    print("DES3 cbc enc", wk, #ciphertext, hex(ciphertext))
    local ds, wk = des.new("testtestkalakalatesttest", "cbc", "kalakala")
    local plaintext = ds:decrypt(ciphertext)
    print("DES3 cbc dec", wk, #plaintext, plaintext)
end

print()

do
    local des = require "resty.nettle.des"
    local ds, wk = des.new("testtestkalakalatesttest", "ctr", "kalakala")
    local ciphertext = ds:encrypt("testtestkalakala")
    print("DES3 ctr enc", wk, #ciphertext, hex(ciphertext))
    local ds, wk = des.new("testtestkalakalatesttest", "ctr", "kalakala")
    local plaintext = ds:decrypt(ciphertext)
    print("DES3 ctr dec", wk, #plaintext, plaintext)
end

print()

do
    local base64 = require "resty.nettle.base64"
    local encoded = base64.encode("testtesttesttest")
    print("BASE64 enc", #encoded, encoded)
    local decoded = base64.decode(encoded)
    print("BASE64 dec", #decoded, decoded)

    print()

    local encoded = base64.encode("testtesttesttest+&", true)
    print("BASE64 enc-url", #encoded, encoded)
    local decoded = base64.decode(encoded, true)
    print("BASE64 dec-url", #decoded, decoded)

    print()

    local base64enc = base64.encoder.new()
    print(base64enc:single("t"))
    print(base64enc:single("e"))
    print(base64enc:single("s"))
    print(base64enc:single("t"))
    print(base64enc:update("test"))
    print(base64enc:single("t"))
    print(base64enc:single("e"))
    print(base64enc:single("s"))
    print(base64enc:single("t"))
    print(base64enc:update("test"))
    print(base64enc:final())

    print()

    local base64dec = base64.decoder.new()
    print(base64dec:single("d"))
    print(base64dec:single("G"))
    print(base64dec:single("V"))
    print(base64dec:single("z"))
    print(base64dec:single("d"))
    print(base64dec:update("HRlc3"))
    print(base64dec:single("R"))
    print(base64dec:single("0"))
    print(base64dec:single("Z"))
    print(base64dec:single("X"))
    print(base64dec:single("N"))
    print(base64dec:single("0"))
    print(base64dec:update("dGVzdA=="))
    print(base64dec:final())
end

print()

do
    local base16 = require "resty.nettle.base16"
    local encoded = base16.encode("testtesttesttest")
    print("BASE16 enc", #encoded, encoded)
    local decoded = base16.decode(encoded)
    print("BASE16 dec", #decoded, decoded)

    print()

    local base16enc = base16.encoder.new()
    print(base16enc:single("t"))
    print(base16enc:single("e"))
    print(base16enc:single("s"))
    print(base16enc:single("t"))
    print(base16enc:update("test"))
    print(base16enc:single("t"))
    print(base16enc:single("e"))
    print(base16enc:single("s"))
    print(base16enc:single("t"))
    print(base16enc:update("test"))

    print()

    local base16dec = base16.decoder.new()
    print(base16dec:single("7"))
    print(base16dec:single("4"))
    print(base16dec:single("6"))
    print(base16dec:single("5"))
    print(base16dec:single("7"))
    print(base16dec:single("3"))
    print(base16dec:single("7"))
    print(base16dec:single("4"))
    print(base16dec:update("74657374"))
    print(base16dec:single("7"))
    print(base16dec:single("4"))
    print(base16dec:single("6"))
    print(base16dec:single("5"))
    print(base16dec:single("7"))
    print(base16dec:single("3"))
    print(base16dec:single("7"))
    print(base16dec:single("4"))
    print(base16dec:update("74657374"))
    print(base16dec:final())
end

print()

do
    local yarrow = require "resty.nettle.yarrow"
    local y = yarrow.new()
    print(y.sources)
    print(y.seeded)
    y:seed("testtesttesttesttesttesttesttest")
    print(y.seeded)

    print(hex(y:random(30)))
    print(hex(y:random(30)))

    y:fast_reseed()

    print(hex(y:random(30)))

    y:slow_reseed()
    print(hex(y:random(30)))
end

print()

do
    local knuth = require "resty.nettle.knuth-lfib"
    local k = knuth.new()
    print(k:number())
    print(k:number())
    print(hex(k:random(10)))
    local t = k:array(10)
    print(t)
    print(table.concat(t, '|'))
end

print()

do
    local hash = require "resty.nettle.hash"
    local hashes = hash.hashes
    for _, h in ipairs(hashes) do
        print(h.name, h.context_size, h.block_size, h.init, h.update, h.digest)
    end
end

print()

do
    local cipher = require "resty.nettle.cipher"
    local ciphers = cipher.ciphers
    for _, c in ipairs(ciphers) do
        print(c.name, c.context_size, c.block_size, c.key_size, c.set_encrypt_key, c.set_decrypt_key, c.encrypt, c.decrypt)
    end
end

print()

do
    local aead = require "resty.nettle.aead"
    local aeads = aead.aeads
    for _, a in ipairs(aeads) do
        print(a.name, a.context_size, a.block_size, a.key_size, a.nonce_size, a.set_encrypt_key, a.set_decrypt_key, a.set_nonce, a.update, a.encrypt, a.decrypt, a.digest)
    end
end
```

The above should output this:

```text
md2      	    16	8350E5A3E24C153DF2275C9F80692773
md2     	    16	8350E5A3E24C153DF2275C9F80692773
md4      	    16	31D6CFE0D16AE931B73C59D7E0C089C0
md4      	    16	31D6CFE0D16AE931B73C59D7E0C089C0
md5      	    16	D41D8CD98F00B204E9800998ECF8427E
md5      	    16	D41D8CD98F00B204E9800998ECF8427E
ripemd160	    20	9C1185A5C5E9FC54612808977EE8F548B2258D31
gosthash94	    32	CE85B99CC46752FFFEE35CAB9A7B0278ABB4C2D2055CFF685AF4912C49490F8D
sha1      	    20	DA39A3EE5E6B4B0D3255BFEF95601890AFD80709
sha1        	20	DA39A3EE5E6B4B0D3255BFEF95601890AFD80709
sha224      	28	D14A028C2A3A2BC9476102BB288234C415A2B01F828EA62AC5B3E42F
sha224      	28	D14A028C2A3A2BC9476102BB288234C415A2B01F828EA62AC5B3E42F
sha256      	32	E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855
sha256      	32	E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855
sha384      	48	38B060A751AC96384CD9327EB1B1E36A21FDB71114BE07434C0CC7BF63F6E1DA274EDEBFE76F65FBD51AD2F14898B95B
sha384      	48	38B060A751AC96384CD9327EB1B1E36A21FDB71114BE07434C0CC7BF63F6E1DA274EDEBFE76F65FBD51AD2F14898B95B
sha512      	64	CF83E1357EEFB8BDF1542850D66D8007D620E4050B5715DC83F4A921D36CE9CE47D0D13C5D85F2B0FF8318D2877EEC2F63B931BD47417A81A538327AF927DA3E
sha512      	64	CF83E1357EEFB8BDF1542850D66D8007D620E4050B5715DC83F4A921D36CE9CE47D0D13C5D85F2B0FF8318D2877EEC2F63B931BD47417A81A538327AF927DA3E
sha512_224	    28	6ED0DD02806FA89E25DE060C19D3AC86CABB87D6A0DDD05C333B84F4
sha512_224	    28	6ED0DD02806FA89E25DE060C19D3AC86CABB87D6A0DDD05C333B84F4
sha512_256  	32	C672B8D1EF56ED28AB87C3622C5114069BDD3AD7B8F9737498D0C01ECEF0967A
sha512_256	    32	C672B8D1EF56ED28AB87C3622C5114069BDD3AD7B8F9737498D0C01ECEF0967A
sha3 224    	28	F71837502BA8E10837BDD8D365ADB85591895602FC552B48B7390ABD
sha3 256	    32	C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470
sha3 384    	48	2C23146A63A29ACF99E73B88F8C24EAA7DC60AA771780CCC006AFBFA8FE2479B2DD2B21362337441AC12B515911957FF
sha3 512	    64	0EAB42DE4C3CEB9235FC91ACFFE746B29C29A8C366B7C60E4E67C466F36A4304C00FA9CAF9D87976BA469BCBE06713B435F091EF2769FB160CDAB33D3670680E
hmac md5    	16	06F30DC9049F859EA0CCB39FDC8FD5C2
hmac md5    	16	06F30DC9049F859EA0CCB39FDC8FD5C2
hmac md5    	16	06F30DC9049F859EA0CCB39FDC8FD5C2
hmac ripemd160	20	ECB2E5CA0EEFFD84F5566B5DE1D037EF1F9689EF
hmac sha1   	20	3902ED847FF28930B5F141ABFA8B471681253673
hmac sha224 	28	7A5027C4F3A358A76D943D6D83A8242675FE96E2D30A526FE9E19629
hmac sha256 	32	3ECF5388E220DA9E0F919485DEB676D8BEE3AEC046A779353B463418511EE622
hmac sha384 	48	724C212553F366248BC76017E812C8ACC85B94FEC2F396C2A925BCC2571F7AB29FEDEE6B3B3013BBF9DE7B89549D5A69
hmac sha512 	64	FC8C80E6B943CD07ECCECF01BC6038BAE68EBB6FA2E1E62B44753D7C177AF7A46B089DF349A19F7622A22312C76906CA9C984E1446D3AB86A98FDFA1425341C5
umac32      	4	D262065C
umac64      	8	C11564AD8F2D885E
umac96      	12	70C9A3F2BB7E0D993B808AE1
umac128     	16	18693CE486CF228E6B1B62EF304BFBC4
poly1305    	16	879E865A98C8CDE7C899D9A3A243EDB9
pbkdf2 sha1 	20	0C60C80F961F0E71F3A9B524AF6012062FE037A6
pbkdf2 sha256	32	89B69D0516F829893C696226650A86878C029AC13EE276509D5AE58B6466A724

aes128 encrypt	32	2EBEA9810D3056A2159BBE45A72429692EBEA9810D3056A2159BBE45A7242969
aes128 decrypt	32	aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

aes128 cbc enc	32	D3D069910C09DFC1675562A0EC9D8B204DD27DB3413D24D994F7300DD331135A
aes128 cbc dec	32	aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

aes128 ctr enc	1	64
aes128 ctr dec	1	a

aes128 eax enc	1	73
aes128 eax dgst	16	B4D34C46BFCA2E729FECC7638F9A6199
aes128 eax dec	1	a
aes128 eax dgst	16	B4D34C46BFCA2E729FECC7638F9A6199

aes128 gcm enc	1	BB
aes128 gcm dgst	16	18D5F5CCECB218322F21005BCBFF16E0
aes128 gcm dec	1	a
aes128 gcm dgst	16	18D5F5CCECB218322F21005BCBFF16E0

aes128 ccm enc	1	6E
aes128 ccm dgst	16	415B65935A4B546B9E81C988B9C68E53
aes128 ccm dec	1	a
aes128 ccm dgst	16	415B65935A4B546B9E81C988B9C68E53

aes192 encrypt	16	942EA398ADD92EBD9DB5574B9E2EA2FC
aes192 decrypt	1	a

aes192 cbc enc	16	9D08DD73316880D2ADA9629BC1906F46
aes192 cbc dec	1	a

aes192 ctr enc	1	98
aes192 ctr dec	1	a

aes192 gcm enc	1	1B
aes192 gcm dgst	16	8F616E7FF9A858FBDC2C1C4C302C4747
aes192 gcm dec	1	a
aes192 gcm dgst	16	8F616E7FF9A858FBDC2C1C4C302C4747

aes192 ccm enc	1	CD
aes192 ccm dgst	16	0D19B5B3D3B637D240B48BDE79395B94
aes192 ccm dec	1	a
aes192 ccm dgst	16	0D19B5B3D3B637D240B48BDE79395B94

aes256 encrypt	16	CF2B7DF795FCEEEEAA39CEBBA3D692BC
aes256 decrypt	1	a

aes256 cbc enc	16	CA906181C0F3457CDAAAAF9D94109337
aes256 cbc dec	1	a

aes256 ctr enc	1	70
aes256 ctr dec	1	a

aes256 gcm enc	1	3B
aes256 gcm dgst	16	EFB12AF268F64A602779EAE2F8C2FA03
aes256 gcm dec	1	a
aes256 gcm dgst	16	EFB12AF268F64A602779EAE2F8C2FA03

aes256 ccm enc	1	A1
aes256 ccm dgst	16	B743659EF6F2FB95C77870FE3F9BD297
aes256 ccm dec	1	a
aes256 ccm dgst	16	B743659EF6F2FB95C77870FE3F9BD297

cam128 encrypt	16	9928767CA4A4D7C7EA11A14B0E0EC626
cam128 decrypt	1	a

cam128 gcm enc	1	E0
cam128 gcm dgst	16	AF2E1CC47D3D31CCC3EA63F417DF35DD
cam128 gcm dec	1	a
cam128 gcm dgst	16	AF2E1CC47D3D31CCC3EA63F417DF35DD

cam192 encrypt	16	A29A12EE9785F75C2A3C62D1EB981604
cam192 decrypt	1	a

cam256 encrypt	16	6EB7D0ACB7AA626F8F6F54C705512D79
cam256 decrypt	1	a

cam256 gcm enc	1	A0
cam256 gcm dgst	16	6B1891EE8E1F20FA49788E75A8F9447F
cam256 gcm dec	1	a
cam256 gcm dgst	16	6B1891EE8E1F20FA49788E75A8F9447F

ARCFOUR encrypt	1	CF
ARCFOUR decrypt	1	a

BLOWFISH enc	8	821C2FA4533A2FD2
BLOWFISH dec	1	a

TWOFISH enc	    16	835DD521513944F098F0399BAD0F7379
TWOFISH dec	    1	a

SERPENT enc 	16	37694A1E1136E4A7E9C1583CBA2525A0
SERPENT dec 	1	a

CAST128 enc	    8	FA80BC104398019E
CAST128 dec	    1	a

ChaCha enc	    1	E2
ChaCha dec  	1	a

Salsa20 128 enc	1	27
Salsa20 128 dec	1	a

Salsa20 256 enc	1	2B
Salsa20 256 dec	1	a

Sal20r12 128 e	1	C1
Sal20r12 128 d	1	a

Sal20r12 256 e	1	E8
Sal20r12 256 d	1	a

cc-p1305 enc	1	35
cc-p1305 dgst	16	94BECC3FD052F18D657B4F18521C0409
cc-p1305 dec	1	a
cc-p1305 dgst	16	94BECC3FD052F18D657B4F18521C0409

DES check   	testtest	false
DES fix     	testtest	udsuudsu
DES check   	udsuudsu	true

DES enc     	false	8	236BF47A8D784246
DES dec     	false	1	a

DES cbc enc 	false	16	3840F08DBAD6CD6DE2AF46AF2656BE48
DES cbc dec 	false	16	testtestkalakala

DES ctr enc 	false	16	AEC72E5671C9D82D343F9F721F668701
DES ctr dec 	false	16	testtestkalakala

DES3 check   	testtestkalakalatesttest	false
DES3 fix     	testtestkalakalatesttest	udsuudsukamakamaudsuudsu
DES3 check   	udsuudsukamakamaudsuudsu	true

DES3 enc     	false	8	95D3D64AEA12A4B5
DES3 dec     	false	1	a

DES3 cbc enc	false	16	C668BD2F4C1154F638A5995EC10EF184
DES3 cbc dec	false	16	testtestkalakala

DES3 ctr enc	false	16	BDD1394B141DE724ADB714DEC4D8E30F
DES3 ctr dec	false	16	testtestkalakala

BASE64 enc	    24	dGVzdHRlc3R0ZXN0dGVzdA==
BASE64 dec	    16	testtesttesttest

BASE64 enc-url	24	dGVzdHRlc3R0ZXN0dGVzdCsm
BASE64 dec-url	18	testtesttesttest+&

... rest is truncated
```

## Hash Functions

### Recommended Hash Functions

The following hash functions have no known weaknesses, and are suitable for new applications. The SHA2 family of hash functions were specified by NIST, intended as a replacement for SHA1.

#### SHA-256

SHA256 is a member of the SHA2 family. It outputs hash values of 256 bits, or 32 octets.

```lua
local hash = require "resty.nettle.sha2"
local dgst = hash('sha256', 'test')
-- or
local dgst = hash.sha256('test')
-- or
local s256 = hash.sha256.new()
s256:update('te')
s256:update('st')
local dgst = s256:digest()
```

#### SHA-224

SHA224 is a variant of SHA256, with a different initial state, and with the output truncated to 224 bits, or 28 octets.

```lua
local hash = require "resty.nettle.sha2"
local dgst = hash('sha224', 'test')
-- or
local dgst = hash.sha224('test')
-- or
local s224 = hash.sha224..new()
s224:update('te')
s224:update('st')
local dgst = s224:digest()
```

#### SHA-512

SHA512 is a larger sibling to SHA256, with a very similar structure but with both the output and the internal variables of twice the size. The internal variables are 64 bits rather than 32, making it significantly slower on 32-bit computers. It outputs hash values of 512 bits, or 64 octets.

```lua
local hash = require "resty.nettle.sha2"
local dgst = hash('sha512', 'test')
-- or
local dgst = hash.sha512('test')
-- or
local s512 = hash.sha512.new()
s512:update('te')
s512:update('st')
local dgst = s512:digest()
```

#### SHA-384, SHA-512/224,  and SHA-512/256

Several variants of SHA512 have been defined, with a different initial state, and with the output truncated to shorter length than 512 bits. Naming is a bit confused, these algorithms are call SHA-512/224, SHA-512/256 and SHA384, for output sizes of 224, 256 and 384 bits, respectively.

#### SHA-384

```lua
local hash = require "resty.nettle.sha2"
local dgst = hash('sha384', 'test')
-- or
local dgst = hash.sha384('test')
-- or
local s384 = hash.sha384.new()
s512:update('te')
s512:update('st')
local dgst = s384:digest()
```

#### SHA-512/224

```lua
local hash = require "resty.nettle.sha2"
local dgst = hash('sha512_224', 'test')
-- or
local dgst = hash.sha512_224('test')
-- or
local s512_224 = hash.sha512_224.new()
s512_224:update('te')
s512_224:update('st')
local dgst = s512_224:digest()
```

#### SHA-512/256

```lua
local hash = require "resty.nettle.sha2"
local dgst = hash('sha512_256', 'test')
-- or
local dgst = hash.sha512_256('test')
-- or
local s512_256 = hash.sha512_256.new()
s512_256:update('te')
s512_256:update('st')
local dgst = s512_256:digest()
```

#### SHA3-224

The SHA3 hash functions were specified by NIST in response to weaknesses in SHA1, and doubts about SHA2 hash functions which structurally are very similar to SHA1. SHA3 is a result of a competition, where the winner, also known as Keccak, was designed by Guido Bertoni, Joan Daemen, Michaël Peeters and Gilles Van Assche. It is structurally very different from all widely used earlier hash functions. Like SHA2, there are several variants, with output sizes of 224, 256, 384 and 512 bits (28, 32, 48 and 64 octets, respectively).

Nettle's implementation of SHA3 should be considered experimental. It is based on the design from the competition. Unfortunately, it is likely that when the standard is finalized, there will be small changes making Nettle's current implementation incompatible with the standard. Nettle's implementation may need incompatible changes to track standardization. Latest standard draft, at the time of writing, is at http://csrc.nist.gov/publications/drafts/fips-202/fips_202_draft.pdf.

```lua
local hash = require "resty.nettle.sha3"
local dgst = hash(224, 'test')
-- or
local dgst = hash.sha224('test')
-- or
local s224 = hash.sha224.new()
s224:update('te')
s224:update('st')
local dgst = s224:digest()
```

#### SHA3-256

This is SHA3 with 256-bit output size, and possibly the most useful of the SHA3 hash functions.

```lua
local hash = require "resty.nettle.sha3"
local dgst = hash(256, 'test')
-- or
local dgst = hash.sha256('test')
-- or
local s256 = hash.sha256.new()
s256:update('te')
s256:update('st')
local dgst = s256:digest()
```

#### SHA3-384

This is SHA3 with 384-bit output size.

```lua
local hash = require "resty.nettle.sha3"
local dgst = hash(384, 'test')
-- or
local dgst = hash.sha384('test')
-- or
local s384 = hash.sha384.new()
s384:update('te')
s384:update('st')
local dgst = s384:digest()
```

#### SHA3-512

This is SHA3 with 512-bit output size.

```lua
local hash = require "resty.nettle.sha3"
local dgst = hash(512, 'test')
-- or
local dgst = hash.sha512('test')
-- or
local s512 = hash.sha512.new()
s512:update('te')
s512:update('st')
local dgst = s512:digest()
```

### Legacy Hash Functions

The hash functions in this section all have some known weaknesses, and should be avoided for new applications. These hash functions are mainly useful for compatibility with old applications and protocols. Some are still considered safe as building blocks for particular constructions, e.g., there seems to be no known attacks against HMAC-SHA1 or even HMAC-MD5. In some important cases, use of a "legacy" hash function does not in itself make the application insecure; if a known weakness is relevant depends on how the hash function is used, and on the threat model.

#### MD5

MD5 is a message digest function constructed by Ronald Rivest, and described in RFC 1321. It outputs message digests of 128 bits, or 16 octets.

#### MD2

MD2 is another hash function of Ronald Rivest's, described in RFC 1319. It outputs message digests of 128 bits, or 16 octets.

#### MD4

MD4 is a predecessor of MD5, described in RFC 1320. Like MD5, it is constructed by Ronald Rivest. It outputs message digests of 128 bits, or 16 octets. Use of MD4 is not recommended, but it is sometimes needed for compatibility with existing applications and protocols.

#### RIPEMD160

RIPEMD160 is a hash function designed by Hans Dobbertin, Antoon Bosselaers, and Bart Preneel, as a strengthened version of RIPEMD (which, like MD4 and MD5, fails the collision-resistance requirement). It produces message digests of 160 bits, or 20 octets.

#### SHA-1

SHA1 is a hash function specified by NIST (The U.S. National Institute for Standards and Technology). It outputs hash values of 160 bits, or 20 octets.

#### GOSTHASH94

The GOST94 or GOST R 34.11-94 hash algorithm is a Soviet-era algorithm used in Russian government standards (see RFC 4357). It outputs message digests of 256 bits, or 32 octets.

## Cipher Functions

A cipher is a function that takes a message or plaintext and a secret key and transforms it to a ciphertext. Given only the ciphertext, but not the key, it should be hard to find the plaintext. Given matching pairs of plaintext and ciphertext, it should be hard to find the key.

#### AES

AES is a block cipher, specified by NIST as a replacement for the older DES standard. The standard is the result of a competition between cipher designers. The winning design, also known as RIJNDAEL, was constructed by Joan Daemen and Vincent Rijnmen.

Like all the AES candidates, the winning design uses a block size of 128 bits, or 16 octets, and three possible key-size, 128, 192 and 256 bits (16, 24 and 32 octets) being the allowed key sizes. It does not have any weak keys.

#### ARCFOUR

ARCFOUR is a stream cipher, also known under the trade marked name RC4, and it is one of the fastest ciphers around. A problem is that the key setup of ARCFOUR is quite weak, you should never use keys with structure, keys that are ordinary passwords, or sequences of keys like "secret:1", "secret:2"... If you have keys that don't look like random bit strings, and you want to use ARCFOUR, always hash the key before feeding it to ARCFOUR. Furthermore, the initial bytes of the generated key stream leak information about the key; for this reason, it is recommended to discard the first 512 bytes of the key stream.

#### ARCTWO

ARCTWO (also known as the trade marked name RC2) is a block cipher specified in RFC 2268. Nettle also include a variation of the ARCTWO set key operation that lack one step, to be compatible with the reverse engineered RC2 cipher description, as described in a Usenet post to sci.crypt by Peter Gutmann.

ARCTWO uses a block size of 64 bits, and variable key-size ranging from 1 to 128 octets. Besides the key, ARCTWO also has a second parameter to key setup, the number of effective key bits, ekb. This parameter can be used to artificially reduce the key size. In practice, ekb is usually set equal to the input key size.

We do not recommend the use of ARCTWO; the Nettle implementation is provided primarily for interoperability with existing applications and standards.

#### BLOWFISH

BLOWFISH is a block cipher designed by Bruce Schneier. It uses a block size of 64 bits (8 octets), and a variable key size, up to 448 bits. It has some weak keys.

#### Camellia

Camellia is a block cipher developed by Mitsubishi and Nippon Telegraph and Telephone Corporation, described in RFC3713. It is recommended by some Japanese and European authorities as an alternative to AES, and it is one of the selected algorithms in the New European Schemes for Signatures, Integrity and Encryption (NESSIE) project. The algorithm is patented. The implementation in Nettle is derived from the implementation released by NTT under the GNU LGPL (v2.1 or later), and relies on the implicit patent license of the LGPL. There is also a statement of royalty-free licensing for Camellia at http://www.ntt.co.jp/news/news01e/0104/010417.html, but this statement has some limitations which seem problematic for free software.

Camellia uses a the same block size and key sizes as AES: The block size is 128 bits (16 octets), and the supported key sizes are 128, 192, and 256 bits. The variants with 192 and 256 bit keys are identical, except for the key setup.

#### CAST128

CAST-128 is a block cipher, specified in RFC 2144. It uses a 64 bit (8 octets) block size, and a variable key size of up to 128 bits.

#### ChaCha

ChaCha is a variant of the stream cipher Salsa20, also designed by D. J. Bernstein. For more information on Salsa20, see below.

#### DES

DES is the old Data Encryption Standard, specified by NIST. It uses a block size of 64 bits (8 octets), and a key size of 56 bits. However, the key bits are distributed over 8 octets, where the least significant bit of each octet may be used for parity. A common way to use DES is to generate 8 random octets in some way, then set the least significant bit of each octet to get odd parity, and initialize DES with the resulting key.

The key size of DES is so small that keys can be found by brute force, using specialized hardware or lots of ordinary work stations in parallel. One shouldn't be using plain DES at all today, if one uses DES at all one should be using "triple DES", see DES3 below.

#### DES3

The inadequate key size of DES has already been mentioned. One way to increase the key size is to pipe together several DES boxes with independent keys. It turns out that using two DES ciphers is not as secure as one might think, even if the key size of the combination is a respectable 112 bits.

The standard way to increase DES's key size is to use three DES boxes. The mode of operation is a little peculiar: the middle DES box is wired in the reverse direction. To encrypt a block with DES3, you encrypt it using the first 56 bits of the key, then decrypt it using the middle 56 bits of the key, and finally encrypt it again using the last 56 bits of the key. This is known as "ede" triple-DES, for "encrypt-decrypt-encrypt".

The "ede" construction provides some backward compatibility, as you get plain single DES simply by feeding the same key to all three boxes. That should help keeping down the gate count, and the price, of hardware circuits implementing both plain DES and DES3.

DES3 has a key size of 168 bits, but just like plain DES, useless parity bits are inserted, so that keys are represented as 24 octets (192 bits). As a 112 bit key is large enough to make brute force attacks impractical, some applications uses a "two-key" variant of triple-DES. In this mode, the same key bits are used for the first and the last DES box in the pipe, while the middle box is keyed independently. The two-key variant is believed to be secure, i.e. there are no known attacks significantly better than brute force.

Naturally, it's simple to implement triple-DES on top of Nettle's DES functions.

#### Salsa20

Salsa20 is a fairly recent stream cipher designed by D. J. Bernstein. It is built on the observation that a cryptographic hash function can be used for encryption: Form the hash input from the secret key and a counter, xor the hash output and the first block of the plaintext, then increment the counter to process the next block (similar to CTR mode, see see CTR). Bernstein defined an encryption algorithm, Snuffle, in this way to ridicule United States export restrictions which treated hash functions as nice and harmless, but ciphers as dangerous munitions.

Salsa20 uses the same idea, but with a new specialized hash function to mix key, block counter, and a couple of constants. It's also designed for speed; on x86_64, it is currently the fastest cipher offered by nettle. It uses a block size of 512 bits (64 octets) and there are two specified key sizes, 128 and 256 bits (16 and 32 octets).

Caution: The hash function used in Salsa20 is not directly applicable for use as a general hash function. It's not collision resistant if arbitrary inputs are allowed, and furthermore, the input and output is of fixed size.

When using Salsa20 to process a message, one specifies both a key and a nonce, the latter playing a similar role to the initialization vector (IV) used with CBC or CTR mode. One can use the same key for several messages, provided one uses a unique random iv for each message. The iv is 64 bits (8 octets). The block counter is initialized to zero for each message, and is also 64 bits (8 octets).

#### SERPENT

SERPENT is one of the AES finalists, designed by Ross Anderson, Eli Biham and Lars Knudsen. Thus, the interface and properties are similar to AES'. One peculiarity is that it is quite pointless to use it with anything but the maximum key size, smaller keys are just padded to larger ones.

#### TWOFISH

Another AES finalist, this one designed by Bruce Schneier and others.

## Cipher Modes

#### Cipher Block Chaining (CBC)
#### Counter Mode (CTR)

## Authenticated Encryption with Associated Data

#### EAX
#### Galois Counter Mode (GCM)
#### Counter with CBC-MAC Mode (CCM)
#### ChaCha-Poly1305

## Keyed Hash Functions

#### HMAC

##### HMAC-MD5
##### HMAC-RIPEMD160
##### HMAC-SHA1
##### HMAC-SHA256
##### HMAC-SHA512

#### UMAC
#### Poly1305

## Key Derivation Functions

#### PBKDF2

##### PBKDF2-HMAC-SHA1
##### PBKDF2-HMAC-SHA256

## Asymmentric Encryption (aka Public Key Encryption)

#### RSA (only preliminary support for now)
#### DSA (not implemented yet)

## Randomness

#### Yarrow
#### Knuth LFIB (a "lagged fibonacci" pseudorandomness generator)

## ASCII Encoding

#### Base64
#### Base16

## License

`lua-resty-nettle` uses two clause BSD license.

```
Copyright (c) 2014 – 2015, Aapo Talvensaari
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice, this
  list of conditions and the following disclaimer in the documentation and/or
  other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
```


text:
package com.mycompany.petclinic.security;

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {

}

redpajama_set_name: RedPajamaGithub


text:
{% extends "base.html" %}

{% load i18n humanize %}
{% load crispy_forms_tags django_bootstrap_breadcrumbs %}

{% block head_title %}{{project.group}} / {{project}}{% endblock %}

{% block breadcrumbs %}
    {{block.super}}
    {% breadcrumb project.group "groups:group-detail" slug=project.group.slug %}
    {% breadcrumb project "projects:project-detail" slug=project.slug %}
    {% breadcrumb "Uploads" "projects:project-uploads" slug=project.slug %}
{% endblock breadcrumbs %}

{% block container %}

    {% include "projects/includes/project_detail_header.html" %}

            {% blocktrans %}You can upload the build result of your documentation using the form below.{% endblocktrans %}

{% trans "Upload docs" %}

                        <form class="project-uploads mb-4" method="post" action="{% url 'projects:imported-archive-create' project.slug %}" enctype="multipart/form-data" novalidate data-ajax-submit>
                            {% crispy form %}
                            <button class="btn btn-success btn-block" type="submit">{% trans "Upload" %}</button>
                        </form>

                            {% trans 'Before upload your docs, make sure the archive:' %}

{% blocktrans %}contain a index.html file and all other docs files as root elements;{% endblocktrans %}

                                    {% blocktrans %}has the correct mimetype. Supported:{% endblocktrans %}

                                        {% for mimetype in allowed_mimetypes %}

{{mimetype}}

                                        {% endfor %}

        {% if imported_archives %}

{% trans "History" %}

                                {% trans "Uploaded at" %}
                                {% trans "Uploaded by" %}
                                {% trans "Uploaded from" %}
                                {% trans "Archive" %}
                                {% trans "Size" %}

                            {% for imported_archive in imported_archives %}

                                    {{imported_archive.created|timesince}}
                                    {{imported_archive.uploaded_by}}
                                    {{imported_archive.get_uploaded_from_display}}
                                    {{imported_archive.archive.url}}
                                    {{imported_archive.archive.size|filesizeformat}}

                            {% endfor %}

        {% endif %}

{% endblock %}


text:
let story = require('storyboard').mainStory;
let URL = require('url');
let request = require('request');
let S = require('string');
let validator = require('validator');

let plugged = require('../client');
let redis = require('../db/redis_db');
const config = require('../load_config');
let utils = require('../utils');
const langfile = require('../../langfile');
let db = require('../db/sql_db');

module.exports = {
    names: ['unblacklist', 'rmbl', 'unbl'],
    enabled: true,
    handler: (data) => {
        //noinspection JSUnresolvedFunction
        redis.hget('user:roles', data.id).then(perm => {
            perm = parseInt(perm, 10);
            if (config.options.bouncerPlus ? (perm > 1) : (perm > 2)) {
                let split = data.message.trim().split(' ');
                if (split.length === 2) {
                    if (validator.isURL(split[1], {
                            protocols: ['https'],
                            host_whitelist: ['youtube.com', 'youtu.be', 'soundcloud.com', 'www.youtube.com'] //eslint-disable-line camelcase
                        })) {
                        let url = URL.parse(split[1], true);
                        if (url.hostname === 'youtu.be') {
                            //noinspection JSUnresolvedFunction
                            let cid = S(url.pathname).replaceAll('/', '').s;
                            db.blacklist.remove(1, cid).then(song => {
                                if (song) {
                                    db.blacklist.remove(song.format, song.cid);
                                    plugged.sendChat(utils.replace(langfile.blacklist.unbl.default, {
                                        username: data.username,
                                        song: utils.songtitle(song.author, song.title)
                                    }), 30);
                                    story.info('unbl', `${utils.userLogString(data.username, data.id)} removed ${utils.songtitle(song.author, song.title)}[${song.format}:${song.cid}] from the blacklist.`);
                                } else plugged.sendChat(utils.replace(langfile.error.argument, {
                                    username: data.username,
                                    cmd: 'UnBl'
                                }), 20);
                            });
                        } else { //noinspection JSUnresolvedletiable
                            if (url.hostname === 'www.youtube.com' && url.query.v) {
                                //noinspection JSUnresolvedletiable
                                db.models.Song.find({where: {format: 1, cid: url.query.v}}).then(song => {
                                    if (song) {
                                        db.blacklist.remove(song.format, song.cid);
                                        plugged.sendChat(utils.replace(langfile.blacklist.unbl.default, {
                                            username: data.username,
                                            song: utils.songtitle(song.author, song.title)
                                        }), 30);
                                        story.info('unbl', `${utils.userLogString(data.username, data.id)} removed ${utils.songtitle(song.author, song.title)}[${song.format}:${song.cid}] from the blacklist.`);
                                    } else plugged.sendChat(utils.replace(langfile.error.argument, {
                                        username: data.username,
                                        cmd: 'UnBl'
                                    }), 20);
                                });
                            } else if (url.hostname === 'soundcloud.com') {
                                request.get(`http://api.soundcloud.com/resolve?url=${split[1]}&client_id=${config.apiKeys.soundcloud}`, (err, resp, body) => {
                                    if (!err && resp.statusCode === 200) {
                                        body = JSON.parse(body);
                                        db.models.Song.find({where: {format: 2, cid: body.id}}).then(song => {
                                            if (song) {
                                                db.blacklist.remove(song.format, song.cid);
                                                plugged.sendChat(utils.replace(langfile.blacklist.unbl.default, {
                                                    username: data.username,
                                                    song: utils.songtitle(song.author, song.title)
                                                }), 30);
                                                story.info('unbl', `${utils.userLogString(data.username, data.id)} removed ${utils.songtitle(song.author, song.title)}[${song.format}:${song.cid}] from the blacklist.`);
                                            } else plugged.sendChat(utils.replace(langfile.error.argument, {
                                                username: data.username,
                                                cmd: 'UnBl'
                                            }), 20);
                                        });
                                    }
                                });
                            } else plugged.sendChat(utils.replace(langfile.error.argument, {
                                username: data.username,
                                cmd: 'UnBl'
                            }), 20);
                        }
                    } else {
                        let args = split[1].split(':');
                        if (args.length === 2 && ['1', '2'].includes(args[0])) {
                            db.models.Song.find({
                                where: {
                                    isBanned: true,
                                    format: args[0],
                                    cid: args[1]
                                }
                            }).then(song => {
                                if (song) {
                                    db.blacklist.remove(args[0], args[1]);
                                    plugged.sendChat(utils.replace(langfile.blacklist.unbl.default, {
                                        username: data.username,
                                        song: utils.songtitle(song.author, song.title)
                                    }), 30);
                                    story.info('unbl', `${utils.userLogString(data.username, data.id)} removed ${utils.songtitle(song.author, song.title)}[${song.format}:${song.cid}] from the blacklist.`);
                                } else plugged.sendChat(utils.replace(langfile.error.argument, {
                                    username: data.username,
                                    cmd: 'UnBl'
                                }), 20);
                            });
                        } else plugged.sendChat(utils.replace(langfile.error.argument, {
                            username: data.username,
                            cmd: 'UnBl'
                        }), 20);
                    }
                } else plugged.sendChat(utils.replace(langfile.error.argument, {
                    username: data.username,
                    cmd: 'UnBl'
                }), 20);
            }
        });
        plugged.removeChatMessage(data.cid);
    }
};


text:
class UpdateAnonymousToFalse < ActiveRecord::Migration
  def self.up
    execute("UPDATE backers SET anonymous = false")
  end

  def self.down
  end
end


text:
/**
 * FILE: Bonus.js
 * PERCORSO /Codice/sgad/clienttier/model/generaldata/Bonus.js
 * DATA CREAZIONE: 12 Febbraio 2014
 * AUTORE: ProTech
 * EMAIL: protech.unipd@gmail.com
 *
 * Questo file è proprietà del gruppo ProTech, viene rilasciato sotto licenza Apache v2.
 *
 * DIARIO DELLE MODIFICHE:
 * 2014-02-13 - Implementazione dei metodi getBonusName(), getBonusQuantity(), getBonusType() e valueOf() - Gatto Francesco
 * 2014-02-12 - Creazione della classe - Gatto Francesco
 */

 /**
 * Classe per la gestione dei bonus eventualmente disponibili per certi edifici.
 * @constructor
 * @param {string} bonusName Rappresenta il nome del bonus.
 * @param {number} quantity Rappresenta la potenza del bonus.
 * @param {int} type Codice identificativo che rappresenta il tipo di bonus e di conseguenza i parametri che influenza con potenza pari al parametro quantity.
 **/
function Bonus(bonusName, quantity, type) {
	/**
	 * Rappresenta il nome del bonus.
	 * @type {string}
	 * @private
	 */
	this.bonusName = bonusName;
	/**
	 * Rappresenta la potenza del bonus.
	 * @type {number}
	 * @private
	 */
	this.quantity = quantity;
	/**
	 * Codice identificativo che rappresenta il tipo di bonus,
	 * e di conseguenza i parametri che influenzano con potenza pari al parametro quantity.
	 * @type {int}
	 * @private
	 */
	this.type = type;
}
/**
 * Controlla l'accesso al nome del bonus.
 * @return {string} Nome del bonus.
 */
Bonus.prototype.getBonusName = function() {
	return this.bonusName;
};
/**
 * Controlla l'accesso alla quantità del bonus.
 * @return {number} Potenza del bonus.
 */
Bonus.prototype.getBonusQuantity = function() {
	return this.quantity;
};
/**
 * Controlla l'accesso al tipo del bonus.
 * @return {int} Tipo del bonus.
 */
Bonus.prototype.getBonusType = function() {
	return this.type;
};
/**
 * Ridefinizione del metodo valueOf di Bonus
 * @override
 * @return {string} Stringa di confronto.
 */
Bonus.prototype.valueOf = function() {
    return JSON.stringify({bonusName : this.getBonusName(), quantity : this.getBonusQuantity(), type : this.getBonusType()});
};


text:
import IFormElement = require('./IFormElement');
interface ICheckableElement extends IFormElement {
	checked: boolean;
	defaultChecked: boolean;
	update (): void;
}

export = ICheckableElement;


text:
/*
 * Pre-upgrade:
 * - display:block element
 * - size-defined element
 */
bento-brightcove {
  display: block;
  overflow: hidden;
  position: relative;
}

/* Pre-upgrade: size-defining element - hide children. */
bento-brightcove:not(.i-amphtml-built)
  > :not([placeholder]):not([slot='i-amphtml-svc']) {
  display: none;
  content-visibility: hidden;
}


text:
The Entity Component System for C# and Unity
============================================

Entitas is a super fast Entity Component System (ECS) specifically made for C# and Unity. Internal caching and blazing fast component access makes it second to none. Several design decisions have been made to work optimal in a garbage collected environment and to go easy on the garbage collector. Entitas comes with an optional code generator which radically reduces the amount of code you have to write and [makes your code read like well written prose.][clean-coders]

---

### **[» Wiki, Overview, Roadmap and example projects][wiki]**
### **[» Community: Games and Examples #madeWithEntitas][wiki-games-and-examples]**

Watch the talk from Unite Europe 2015
=====================================
» Open the slides on SlideShare

[![UniteEurope 2015][unite-europe-2015-video-thumbnail]][unite-europe-2015-video]

First glimpse
=============

The optional [code generator][wiki-code-generator] lets you write code that is super fast, safe and literally screams its intent.

```csharp
public static Entity CreateRedGem(this Pool pool, int x, int y) {
    return pool.CreateEntity()
               .IsGameBoardElement(true)
               .IsMovable(true)
               .AddPosition(x, y)
               .AddResource(Res.redGem)
               .IsInteractive(true);
}
```

```csharp
var entities = pool.GetEntities(Matcher.AllOf(Matcher.Move, Matcher.Position));
foreach (var entity in entities) {
    var move = entity.move;
    var pos = entity.position;
    entity.ReplacePosition(pos.x, pos.y + move.speed);
}
```

Overview
========

Entitas is fast, light and gets rid of unnecessary complexity. There are less than a handful classes you have to know to rocket start your game or application:

- Entity
- Pool
- Group
- Group Observer

[Read more...][wiki-overview]

Code Generator
==============

The Code Generator generates classes and methods for you, so you can focus on getting the job done. It radically reduces the amount of code you have to write and improves readability by a huge magnitude. It makes your code less error-prone while ensuring best performance. I strongly recommend using it!

[Read more...][wiki-code-generator]

Unity integration
=================

The optional Unity module integrates Entitas nicely into Unity and provides powerful editor extensions to inspect and debug pools, groups, entities, components and systems.

[Read more...][wiki-unity-integration]

Entitas deep dive
=================

[Read the wiki][wiki] or checkout the awesome [example projects][wiki-example-projects] to see Entitas in action. These example projects illustrate how systems, groups, observers and entities all play together seamlessly.

Download Entitas
================

Each release is published with zip files attached containing all source files you need.

[**Entitas-CSharp.zip**][entitas-csharp-zip]
- Entitas
- Entitas.CodeGenerator

[**Entitas-Unity.zip**][entitas-unity-zip]
- Entitas
- Entitas.CodeGenerator
- Entitas.Unity
- Entitas.Unity.CodeGenerator
- Entitas.Unity.VisualDebugging

[Show releases][releases]

Contributing to Entitas
=======================

The project is hosted on [GitHub][github-entitas] where you can [report issues][issues], fork the project and [submit pull requests][pulls].

Entitas.sln contains all projects and tests in one solution. All Unity projects are not committed to the repository and can be generated with Unity. Open Entitas.Unity, Entitas.Unity.CodeGenerator and Entitas.Unity.VisualDebugging in Unity and generate all projects by clicking Assets -> Sync MonoDevelop Project.

To run the tests, navigate to the project root folder and execute runTests.sh.

- Check the [issues][issues] to make sure nobody hasn't already requested it and/or contributed it
- Fork the project
- Checkout the latest develop
- Start a feature/yourFeatureOrBugfix branch based on the latest develop
- Make sure to add/update tests. This is important so nobody will break it in a future version. Please write tests first, followed by the implementation.
- Commit and push until you are happy with your contribution
- Create a [pull request][pulls]

Thanks to
=========

Big shout out to [@mzaks][github-mzaks], [@cloudjubei][github-cloudjubei] and [@devboy][github-devboy] for endless hours of discussion and helping making Entitas awesome!

Maintainer(s)
=============

- [@sschmid][github-sschmid] | Twitter: [@s_schmid][twitter-sschmid]

Different language?
===================

Entitas is also available in
- [Swift](https://github.com/mzaks/Entitas)
- [Objective-C](https://github.com/wooga/entitas)
- [Go](https://github.com/wooga/go-entitas)
- [Clojure](https://github.com/mhaemmerle/entitas-clj)
- [Haskell](https://github.com/mhaemmerle/entitas-haskell)
- [Erlang](https://github.com/mhaemmerle/entitas_erl)

[clean-coders]: https://cleancoders.com "Clean Coders"
[entitas-csharp-zip]: https://github.com/sschmid/Entitas-CSharp/blob/master/bin/Entitas-CSharp.zip?raw=true "Download Entitas-CSharp.zip"
[entitas-unity-zip]: https://github.com/sschmid/Entitas-CSharp/blob/master/bin/Entitas-Unity.zip?raw=true "Download Entitas-Unity.zip"

[wiki]: https://github.com/sschmid/Entitas-CSharp/wiki "Entitas Wiki"
[wiki-code-generator]: https://github.com/sschmid/Entitas-CSharp/wiki/Code-Generator "Wiki - Code Generator"
[wiki-overview]: https://github.com/sschmid/Entitas-CSharp/wiki/Overview "Wiki - Overview"
[wiki-unity-integration]: https://github.com/sschmid/Entitas-CSharp/wiki/Unity-integration "Wiki - Unity Integration"
[wiki-example-projects]: https://github.com/sschmid/Entitas-CSharp/wiki/Example-projects "Wiki - Example Projects"
[wiki-games-and-examples]: https://github.com/sschmid/Entitas-CSharp/wiki/Games-and-Examples "Wiki - Games and Examples #madeWithEntitas"

[unite-europe-2015-video-thumbnail]: https://raw.githubusercontent.com/sschmid/Entitas-CSharp/develop/Readme/Images/UniteEurope2015-Video.png "Video: Watch the Entitas Talk at Unite Europe 2015"
[unite-europe-2015-video]: http://buff.ly/1KtKlm6 "Video: Watch the Entitas Talk at Unite Europe 2015"

[github-entitas]: https://github.com/sschmid/Entitas-CSharp "sschmid/Entitas-CSharp"
[releases]: https://github.com/sschmid/Entitas-CSharp/releases "Releases"
[issues]: https://github.com/sschmid/Entitas-CSharp/issues "Issues"
[pulls]: https://github.com/sschmid/Entitas-CSharp/pulls "Pull Requests"

[twitter-sschmid]: https://twitter.com/s_schmid "s_schmid on Twitter"

[github-sschmid]: https://github.com/sschmid "@sschmid"
[github-mzaks]: https://github.com/mzaks "@mzaks"
[github-cloudjubei]: https://github.com/cloudjubei "@cloudjubei"
[github-devboy]: https://github.com/devboy "@devboy"


text:
extern "C" {
#endif

#ifdef __cplusplus
}
#endif

#ifdef __cplusplus

#include <std_msgs/Float32.h>
#include "bsp/bsp_can.h"

class Motor {
public:

  Motor(uint32_t id, CAN* bus);

  void UpdateSensorData(CanRxMsgTypeDef *message);

  int current = 0;
  int speedRPM = 0;
  int angle = 0;
  int lastAngle = 0;
  int targetCurrent = 0;
  long round = 0;
  long totalAngle = 0;
  int offsetAngle = 0;
private:
  uint32_t canID;
  CAN* bus;
};

#endif

#endif //CHASSIS_MOTOR_H


text:
package main

import (
	"fmt"
	"reflect"
)

type TagType struct {
	field1 bool   "An important answer"
	field2 string "The name of the thing"
	field3 int    `how much there are`
}

func main() {
	tt := TagType{true, "Barak Obama", 1}
	var reflectType reflect.Type = reflect.TypeOf(tt)
	var ixField reflect.StructField
	for i := 0; i < 3; i++ {
		ixField = reflectType.Field(i)
		fmt.Printf("%s\n", ixField.Tag)
	}
}


text:
module Dynflow
  class ThrottleLimiter

    attr_reader :core

    def initialize(world)
      @world = world
      spawn
    end

    def initialize_plan(plan_id, semaphores_hash)
      core.tell([:initialize_plan, plan_id, semaphores_hash])
    end

    def finish(plan_id)
      core.tell([:finish, plan_id])
    end

    def handle_plans!(*args)
      core.ask!([:handle_plans, *args])
    end

    def cancel!(plan_id)
      core.tell([:cancel, plan_id])
    end

    def terminate
      core.ask(:terminate!)
    end

    def observe(parent_id = nil)
      core.ask!([:observe, parent_id])
    end

    def core_class
      Core
    end

    private

    def spawn
      Concurrent::Promises.resolvable_future.tap do |initialized|
        @core = core_class.spawn(:name => 'throttle-limiter',
                                 :args => [@world],
                                 :initialized => initialized)
      end
    end

    class Core < Actor
      def initialize(world)
        @world = world
        @semaphores = {}
      end

      def initialize_plan(plan_id, semaphores_hash)
        @semaphores[plan_id] = create_semaphores(semaphores_hash)
        set_up_clock_for(plan_id, true)
      end

      def handle_plans(parent_id, planned_ids, failed_ids)
        failed = failed_ids.map do |plan_id|
          ::Dynflow::World::Triggered[plan_id, Concurrent::Promises.resolvable_future].tap do |triggered|
            execute_triggered(triggered)
          end
        end

        planned_ids.map do |child_id|
          ::Dynflow::World::Triggered[child_id, Concurrent::Promises.resolvable_future].tap do |triggered|
            triggered.future.on_resolution! { self << [:release, parent_id] }
            execute_triggered(triggered) if @semaphores[parent_id].wait(triggered)
          end
        end + failed
      end

      def observe(parent_id = nil)
        if parent_id.nil?
          @semaphores.reduce([]) do |acc, cur|
            acc << { cur.first => cur.last.waiting }
          end
        elsif @semaphores.key? parent_id
          @semaphores[parent_id].waiting
        else
          []
        end
      end

      def release(plan_id, key = :level)
        return unless @semaphores.key? plan_id
        set_up_clock_for(plan_id) if key == :time
        semaphore = @semaphores[plan_id]
        semaphore.release(1, key) if semaphore.children.key?(key)
        if semaphore.has_waiting? && semaphore.get == 1
          execute_triggered(semaphore.get_waiting)
        end
      end

      def cancel(parent_id, reason = nil)
        if @semaphores.key?(parent_id)
          reason ||= 'The task was cancelled.'
          @semaphores[parent_id].waiting.each do |triggered|
            cancel_plan_id(triggered.execution_plan_id, reason)
            triggered.future.reject(reason)
          end
          finish(parent_id)
        end
      end

      def finish(parent_id)
        @semaphores.delete(parent_id)
      end

      private

      def cancel_plan_id(plan_id, reason)
        plan = @world.persistence.load_execution_plan(plan_id)
        steps = plan.run_steps
        steps.each do |step|
          step.state = :error
          step.error = ::Dynflow::ExecutionPlan::Steps::Error.new(reason)
          step.save
        end
        plan.update_state(:stopped)
        plan.save
      end

      def execute_triggered(triggered)
        @world.execute(triggered.execution_plan_id, triggered.finished)
      end

      def set_up_clock_for(plan_id, initial = false)
        if @semaphores[plan_id].children.key? :time
          timeout_message = 'The task could not be started within the maintenance window.'
          interval = @semaphores[plan_id].children[:time].meta[:interval]
          timeout = @semaphores[plan_id].children[:time].meta[:time_span]
          @world.clock.ping(self, interval, [:release, plan_id, :time])
          @world.clock.ping(self, timeout, [:cancel, plan_id, timeout_message]) if initial
        end
      end

      def create_semaphores(hash)
        semaphores = hash.keys.reduce(Utils.indifferent_hash({})) do |acc, key|
          acc.merge(key => ::Dynflow::Semaphores::Stateful.new_from_hash(hash[key]))
        end
        ::Dynflow::Semaphores::Aggregating.new(semaphores)
      end
    end
  end
end


text:
package org.t246osslab.easybuggy.exceptions;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.undo.UndoManager;

import org.t246osslab.easybuggy.core.servlets.AbstractServlet;

@SuppressWarnings("serial")
@WebServlet(urlPatterns = { "/cue" })
public class CannotUndoExceptionServlet extends AbstractServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        new UndoManager().undo();
    }
}


text:
[Secure Secret Storage and
Sharing](https://github.com/matrix-org/matrix-doc/pull/1946) (SSSS) was
designed to allow the user to create multiple keys that would be able to
decrypt different subsets of the secrets.  However, the vast majority of users
do not need this feature.

This proposal defines how clients should behave if they only wish to support a
single key, by defining which key clients should use if multiple keys are
present.  It also makes the `name` field in the `m.secret_storage.key.*` events
optional, as this field was mainly added to allow a user to select between
different keys.

## Proposal

If a client wants to present a simplified interface to users by not supporting
multiple SSSS keys, then the client should use the default key (the key listed
in the `m.secret_storage.default_key` account data event.)  If there is no
default key the client may behave as if there is no SSSS key at all.  When such
a client creates an SSSS key, it must mark that key as being the default key.

The `name` field in the `m.secret_storage.key.*` account data events is
optional, rather than required.  If a client wishes to display multiple keys to
a user and a given key does not have a `name` field, the client may use a
default name as the key's name, such as "Unnamed key", or "Default key" if the
key is marked as default.

For example, when a client creates a key with ID `abcdefg`, it will create an
`m.secret_storage.key.abcdefg` account data event to store information about
the key.  It will then mark it as the default key by setting the
`m.secret_storage.default_key` account data to `{"key": "abcdefg"}`.  When
another client logs in after this, it will see that the default key has been
set, and will know to use that key as the SSSS key.

## Potential issues

If secrets are encrypted using a key that is not marked as default, a client
might not decrypt the secrets, even if it would otherwise be able to.

## Alternatives

Rather than solely relying on the key marked as default, a client could guess
at what key to use.  For example, it could look at the secrets that it needs,
see what keys they are encrypted with, and if there is only one common key,
then it could use that.  (This is what Element currently does.)  Or if there
are multiple keys, it could use some sort of heuristic to pick a key.  However,
this approach can be error-prone, and it is better to rely on an explicit
marking.

## Security considerations

None

## Unstable prefix

An unstable prefix is not needed for a behaviour change in choosing the key to
use as there are no event/endpoint changes.

Some clients already omit the `name` field (notably, matrix-js-sdk
unintentionally does this -- mea culpa), and this does not seem to be causing
issues, so an unstable prefix seems unnecessary for this.


text:
/**
 * Module dependencies.
 */

var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , map = require('./routes/map')
  , localize = require('./routes/localize')
  , http = require('http')
  , path = require('path')
  ;

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// added for accept localization web app
app.use(function(req, res, next) {
	res.header('Access-Control-Allow-Origin', '*');
});

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

app.get('/', routes.index);
app.get('/user/list', user.list);
app.get('/user/history', user.history);
app.post('/user/history', user.addHistory);
app.get('/map/structure', map.structure);
app.get('/map/camera', map.camera);
app.get('/map/dense', map.dense);
app.get('/localize', localize.estimateGet);
app.post('/localize', localize.estimatePost);

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});


text:
// This file is automatically generated.

package adila.db;

/*
 * Verizon Wireless QTAQZ3KID
 *
 * DEVICE: QTAQZ3KID
 * MODEL: QTAQZ3KID
 */
final class qtaqz3kid_qtaqz3kid {
    public static final String DATA = "Verizon Wireless|QTAQZ3KID|";
}


text:
declare module "windowed" {
	function windowed<T>(size: number, xs: T[]): T[][];

	export default windowed;
}


text:
1. Increment the version in `./lib/pact_broker/version.rb`
2. Update the `CHANGELOG.md` using:

      $ git log --pretty=format:'  * %h - %s (%an, %ad)' vX.Y.Z..HEAD

3. Add files to git

      $ git add CHANGELOG.md lib/pact_broker/version.rb

3. Release:

      $ bundle exec rake release


text:
/* global QUnit */

sap.ui.define(["jquery.sap.encoder"], function (jQuery) {
	"use strict";
	// Output encodings should follow the guide
	// <SAPWIKI>/wiki/download/attachments/867713114/XSS_Char_Table.pdf

	QUnit.module("HTML context");
	QUnit.test("encode HTML", function (assert) {
		assert.equal(jQuery.sap.encodeHTML("+"), "+", "Plus");
		assert.equal(jQuery.sap.encodeHTML("<>&\""), "<>&"", "<>&\"");
		assert.equal(jQuery.sap.encodeHTML("\x00\x01\x02"), "���", "0x00 0x01 0x02");
		assert.equal(jQuery.sap.encodeHTML(">&<\"\'\\/"), ">&<"'\/", ">&<\"\'\\/");
	});

	QUnit.test("should not encode", function (assert) {
		assert.equal(jQuery.sap.encodeHTML("nothingtoencode123,.-_"), "nothingtoencode123,.-_", "nothingtoencode123,.-_");
	});

	// http://unicode.org/review/pr-121.html
	QUnit.test("should replaced with 0xfffd", function (assert) {
		assert.equal(jQuery.sap.encodeHTML(String.fromCharCode(8)), "�", "Backspace");
		assert.equal(jQuery.sap.encodeHTML(String.fromCharCode(9)), "	", "Tab");
		assert.equal(jQuery.sap.encodeHTML(String.fromCharCode(10)), "
", "Line feed");
		assert.equal(jQuery.sap.encodeHTML(String.fromCharCode(11)), "�", "Vertical tab");
		assert.equal(jQuery.sap.encodeHTML(String.fromCharCode(12)), "�", "Form feed");
		assert.equal(jQuery.sap.encodeHTML(String.fromCharCode(13)), "
", "Carriage return");
		assert.equal(jQuery.sap.encodeHTML(String.fromCharCode(14)), "�", "Shift out");
		assert.equal(jQuery.sap.encodeHTML(String.fromCharCode(15)), "�", "Shift in");
		assert.equal(jQuery.sap.encodeHTML(String.fromCharCode(16)), "�", "Data link escape");

	});

	QUnit.test("characters above (>) 255 (0xff) should not be encoded, except for 0x2028 and 0x2029", function (assert) {
		assert.equal(jQuery.sap.encodeHTML(String.fromCharCode(256)), "Ā", "Ā (0x100)");
		assert.equal(jQuery.sap.encodeHTML(String.fromCharCode(257)), "ā", "ā (0x101)");
		assert.equal(jQuery.sap.encodeHTML(String.fromCharCode(0x2028)), "
", "(0x2028)");
		assert.equal(jQuery.sap.encodeHTML(String.fromCharCode(0x2029)), "
", "(0x2029)");
	});

	QUnit.module("JS context");
	QUnit.test("encode JS", function (assert) {
		assert.equal(jQuery.sap.encodeJS("\""), "\\x22", "Quote");
		assert.equal(jQuery.sap.encodeJS("\'"), "\\x27", "Apostrophe");
		assert.equal(jQuery.sap.encodeJS("\x00\x01\x02"), "\\x00\\x01\\x02", "0x00 0x01 0x02");
		assert.equal(jQuery.sap.encodeJS(">&<\"\'\\/"), "\\x3e\\x26\\x3c\\x22\\x27\\x5c\\x2f", ">&<\"\'\\/");
	});

	QUnit.test("should not encode", function (assert) {
		assert.equal(jQuery.sap.encodeJS("nothingtoencode123,._"), "nothingtoencode123,._", "nothingtoencode123,._");
	});

	QUnit.test("characters above (>) 255 (0xff) should not be encoded, except for 0x2028 and 0x2029", function (assert) {
		assert.equal(jQuery.sap.encodeJS(String.fromCharCode(256)), "Ā", "Ā (0x100)");
		assert.equal(jQuery.sap.encodeJS(String.fromCharCode(257)), "ā", "ā (0x101)");
		assert.equal(jQuery.sap.encodeJS(String.fromCharCode(0x2028)), "\\u2028", "(0x2028)");
		assert.equal(jQuery.sap.encodeJS(String.fromCharCode(0x2029)), "\\u2029", "(0x2029)");
	});

	QUnit.module("URL context");
	QUnit.test("encode URL", function (assert) {
		assert.equal(jQuery.sap.encodeURL("*"), "%2a", "Asterisk");
		assert.equal(jQuery.sap.encodeURL("+"), "%2b", "Plus");
		assert.equal(jQuery.sap.encodeURL("ä"), "%c3%a4", "Umlaut");
		assert.equal(jQuery.sap.encodeURL("\x00\x01\x02"), "%00%01%02", "0x00 0x01 0x02");
		assert.equal(jQuery.sap.encodeURL(">&<\"\'\\/"), "%3e%26%3c%22%27%5c%2f", ">&<\"\'\\/");
	});
	QUnit.test("encode URL parameters", function (assert) {
		assert.equal(jQuery.sap.encodeURLParameters({
			"?": "=",
			"&": "?",
			">&<\"\'\\/": String.fromCharCode(256)
		}), "%3f=%3d&%26=%3f&%3e%26%3c%22%27%5c%2f=%c4%80", "parameter map");
		assert.equal(jQuery.sap.encodeURLParameters({}), "", "empty parameter map");
		assert.equal(jQuery.sap.encodeURLParameters(), "", "no parameter map");
	});
	QUnit.test("should not encode", function (assert) {
		assert.equal(jQuery.sap.encodeURL("nothingtoencode123-._"), "nothingtoencode123-._", "nothingtoencode123-._");
	});

	QUnit.test("characters above (>) 255 (0xff) should be encoded always", function (assert) {
		assert.equal(jQuery.sap.encodeURL(String.fromCharCode(256)), "%c4%80", "Ā (0x100)");
		assert.equal(jQuery.sap.encodeURL(String.fromCharCode(257)), "%c4%81", "ā (0x101)");
	});

	QUnit.module("CSS context");
	QUnit.test("encode CSS", function (assert) {
		assert.equal(jQuery.sap.encodeCSS("+"), "\\2b", "Plus");
		assert.equal(jQuery.sap.encodeCSS("~7"), "\\7e 7", "~7");
		assert.equal(jQuery.sap.encodeCSS("+apple"), "\\2b apple", "+apple");
		assert.equal(jQuery.sap.encodeCSS("/BUG"), "\\2f BUG", "/BUG");
		assert.equal(jQuery.sap.encodeCSS("~test"), "\\7etest", "~test");
		assert.equal(jQuery.sap.encodeCSS("\x00\x01\x02"), "\\0\\1\\2", "0x00 0x01 0x02");
		assert.equal(jQuery.sap.encodeCSS(">&<\"\'\\/"), "\\3e\\26\\3c\\22\\27\\5c\\2f", ">&<\"\'\\/");
	});

	QUnit.test("should not encode", function (assert) {
		assert.equal(jQuery.sap.encodeCSS("nothingtoencode123"), "nothingtoencode123", "nothingtoencode123");

	});

	QUnit.test("characters above (>) 255 (0xff) should not be encoded, except for 0x2028 and 0x2029", function (assert) {
		assert.equal(jQuery.sap.encodeCSS(String.fromCharCode(256)), "Ā", "Ā (0x100)");
		assert.equal(jQuery.sap.encodeCSS(String.fromCharCode(257)), "ā", "ā (0x101)");
		assert.equal(jQuery.sap.encodeCSS(String.fromCharCode(0x2028)), "\\2028", "(0x2028)");
		assert.equal(jQuery.sap.encodeCSS(String.fromCharCode(0x2029)), "\\2029", "(0x2029)");
	});

	QUnit.module("URL validation");
	QUnit.test("HTTP urls", function (assert) {
		assert.equal(jQuery.sap.validateUrl("http://host"), true, "http://host");
		assert.equal(jQuery.sap.validateUrl("http://host/path"), true, "http://host/path");
		assert.equal(jQuery.sap.validateUrl("http://www.host.com"), true, "http://www.host.com");
		assert.equal(jQuery.sap.validateUrl("http://www.host.com?name=value"), true, "http://www.host.com?name=value");
		assert.equal(jQuery.sap.validateUrl("http://www.host.com#somehash"), true, "http://www.host.com#somehash");
		assert.equal(jQuery.sap.validateUrl("http://www.host.com?name=value#somehash"), true, "http://www.host.com?name=value#somehash");
		assert.equal(jQuery.sap.validateUrl("http://www.host.com/path%7e+13?_name@=!value+#somehash?/"), true, "http://www.host.com/path%7e+13?_name@=!value+#somehash?/");

		assert.equal(jQuery.sap.validateUrl("http://www.host.com/invalid\\path"), false, "Invalid character in path");
		assert.equal(jQuery.sap.validateUrl("http://www.host.com/path?name=invalid>value"), false, "Invalid character in query");
		assert.equal(jQuery.sap.validateUrl("http://www.host.com/path?invalid>value"), false, "Invalid character in query without equal sign");
		assert.equal(jQuery.sap.validateUrl("http://www.host.com/path#invalid#hash"), false, "Invalid character in hash");
		assert.equal(jQuery.sap.validateUrl("http://www.host.com/invalid%path"), false, "Invalid percent encoding");

	});

	QUnit.test("mailto urls", function (assert) {
		jQuery.sap.addUrlWhitelist("mailto");
		assert.equal(jQuery.sap.validateUrl("mailto:name@domain.com"), true, "mailto:name@domain.com");
		assert.equal(jQuery.sap.validateUrl("mailto:NAME@domain.com"), true, "mailto:NAME@domain.com");
		assert.equal(jQuery.sap.validateUrl("mailto:name@some-domain.com"), true, "mailto:name@some-domain.com");
		assert.equal(jQuery.sap.validateUrl("mailto:someone@example.com?subject=This%20is%20the%20subject&cc=someone_else@example.com&body=This%20is%20the%20body"), true, "should accept mailto URL with parameters");
		assert.equal(jQuery.sap.validateUrl("mailto:someone@example.com,someoneelse@example.com"), true, "should accept mailto URL with multiple addresses");
		assert.equal(jQuery.sap.validateUrl("mailto:?to=&subject=mailto"), true, "should accept mailto URL without addresses");
		assert.equal(jQuery.sap.validateUrl("mailto:name-with$lot_of!strange%23characters@domain.com"), true, "mailto:name-with$lot_of!strange#characters@domain.com");
		jQuery.sap.clearUrlWhitelist();
	});

	QUnit.test("Syntax check", function (assert) {

		var sUrl = "http://www.sap.com";
		assert.ok(jQuery.sap.validateUrl(sUrl), sUrl + " valid");

		sUrl = "http:\\www.sap.com";
		assert.ok(jQuery.sap.validateUrl(sUrl), sUrl + " valid");

		sUrl = "https://www.sap.com";
		assert.ok(jQuery.sap.validateUrl(sUrl), sUrl + " valid");

		sUrl = "ftp://sap.com";
		assert.ok(jQuery.sap.validateUrl(sUrl), sUrl + " valid");

		sUrl = "images/pic.gif";
		assert.ok(jQuery.sap.validateUrl(sUrl), sUrl + " valid");

		sUrl = "../images/pic.gif";
		assert.ok(jQuery.sap.validateUrl(sUrl), sUrl + " valid");

		sUrl = "//test.html";
		assert.ok(jQuery.sap.validateUrl(sUrl), sUrl + " valid");

		sUrl = "


text:
class C {
    static create = () => new this("yep")

    constructor (private foo: string) {

    }
}


text:
class Base(object):

    def __init__(self, cls, fields):
        self.cls = cls
        self.fields = fields

    def read_attribute(self, field_name):
        return self.fields.get(field_name)

    def write_attribute(self, field_name, value):
        self.fields[field_name] = value

    def call_method(self, method_name, *args):
        method = self.cls.find_method(method_name)
        return method(self, *args)

    def isinstance(self, cls):
        return self.cls.issubclass(cls)

class Class(Base):

    def __init__(self, name, base_class, fields, metaclass):
        Base.__init__(self, metaclass, fields)
        self.name = name
        self.base_class = base_class

    def super_class_traversal(self):
        if self.base_class is None:
            return [self]
        else:
            return [self] + self.base_class.super_class_traversal()

    def issubclass(self, cls):
        return cls in self.super_class_traversal()

    def find_method(self, method_name):
        for cls in self.super_class_traversal():
            if method_name in cls.fields:
                return cls.fields[method_name]
        return MISSING

class Instance(Base):

    def __init__(self, cls):
        assert isinstance(cls, Class)
        Base.__init__(self, cls, {})

OBJECT = Class(name='object', base_class=None, fields={}, metaclass=None)
TYPE = Class(name='TYPE', base_class=OBJECT, fields={}, metaclass=None)
TYPE.cls = TYPE
OBJECT.cls = TYPE
MISSING = object()


text:
- call a gulp done callback if no folders are found

# 1.0.0
- Initial release
- callback for each folder with one merged stream