packages feed

crypton-2.3.1 / README.md

<p align="center">  <img src="docs/images/crypton.svg" alt="crypton" height="160"></p>![GitHub Actions status](https://github.com/kazu-yamamoto/crypton/actions/workflows/main.yml/badge.svg?branch=main)crypton==========`crypton` is a fork from `cryptonite` with the original author's permission.`crypton` is a low-level cryptography library. To achieve highperformance, it utilizes C and assembly language to define FFIbindings, structuring them in a way that makes them easy to use.Side channels-------------### AESAES is where this matters most, and which implementation runs is decided atruntime from what the processor has.On x86-64 with AES-NI and carry-less multiply, on AArch64 and on 32-bit ARMwith the ARMv8 cryptographic extension, and on ppc64le with the vectorinstructions PowerISA 2.07 brought to POWER8, AES and GHASH are instructionsrather than software.  crypton's AES and AES-GCM then make no branch and nomemory access that depends on the key or on the data: the secrets stay invector registers and never reach one a branch can test.  Every x86-64 partsince about 2010 and every AArch64 part in ordinary use has these, and theppc64le path is little-endian only.Where none of them is there, crypton computes AES and GHASH without a table.The portable AES is bitsliced -- the S-box is boolean algebra over fourblocks held across eight 64-bit words -- and the GF(2^128) multiply is builtfrom shifts, masks and integer multiplies.  Neither looks anything up, soneither derives an address from a secret, and **the portable path is constanttime as well**.  The code is BearSSL's, under MIT, in `cbits/bearssl`.The constant-time harness in `cbits/tests/ct` runs the same driver againstthe portable implementation and against each architecture's instructions, andevery one of them is required to report nothing at all.So the answer does not depend on the machine any more, and what is left toask is whether AES is fast on it.  `hasAESAcceleration` and`hasGHASHAcceleration` answer that without naming an architecture.`processorOptions` says what was found, in the processor's own names --`AESNI` and `PCLMUL` on x86, `ARMAES` and `ARMPMULL` on AArch64 and 32-bitARM, `PPCAES` and `PPCVPMSUM` on ppc64le -- along with everything else it wasasked about, which is unrelated to this.    ghci> import Crypto.System.CPU    ghci> hasAESAcceleration    True    ghci> processorOptions           -- on an x86-64 machine    [AESNI,PCLMUL,SSSE3,AVX,AVX2,SHANI,MOVBE,ADX,VAES]    ghci> processorOptions           -- and on an AArch64 one    [NEON,ARMAES,ARMPMULL,ARMSHA1,ARMSHA2,ARMSHA512]### RSARSA is the other place to know about, and there the choice is the caller's.The private key operations in `Crypto.PubKey.RSA.PKCS15`, `.OAEP` and `.PSS`take a `Maybe Blinder`, and `Nothing` is no harder to write than the safeform:    decrypt     :: Maybe Blinder -> PrivateKey -> ByteString -> ...    decryptSafer :: MonadRandom m => PrivateKey -> ByteString -> m ...The exponent itself is not what is at risk.  `expSafe` keeps the *value* of anexponent out of the work it does, so the private exponent does not leakthrough the exponentiation.  What a blinder covers is the other side: withoutone, the operation runs on the ciphertext the caller was handed, so how longit takes depends on a number an attacker may have chosen and can vary.  Thatis what a remote timing attack on RSA needs.  With a blinder the input ismultiplied by a random value first and the result divided out afterwards, sothe timing carries nothing an attacker can steer.`decryptSafer` and `signSafer` generate the blinder themselves and are theones to reach for.  Pass `Nothing` only where the input is not attackercontrolled and you have decided that it is not.The RSA rows in the tables below are the unblinded path.  A fresh blindercosts one more exponentiation, by the public exponent, which is the cheapdirection: measured on the M4, signing goes from about 316 to about 335microseconds, about six per cent.  `signSafer` and `decryptSafer` pay lessthan that from 2.2.4: they keep the blinder of a key they have seen and squareit for the next use, as OpenSSL does, drawing a fresh one every 32 uses.`Crypto.PubKey.RSA.Blinded` gives a caller the same thing to hold, a`BlindedKey` passed along from one operation to the next.From 2.2.5 every private-key operation also raises its result back to thepublic exponent before letting it out, as OpenSSL does.  A fault in one halfof a CRT computation would otherwise give an answer that reveals a prime ofthe key; that answer is now computed again without CRT instead.  It costs afew per cent of a signature, and the tables below include it.Performance-----------The algorithms a TLS connection uses, measured against the last releasebefore the rewrite and against OpenSSL on the same machine.  Throughput isover 16 KiB messages; the public key operations are one operation each; everyfigure is the best of several runs, and crypton and OpenSSL are runalternately so that neither gets the quieter machine.Bulk encryption and hashing are measured through crypton's C layer, as`openssl speed` measures OpenSSL's.  The public key operations are measuredthrough crypton's Haskell API, since that is where ECDSA and RSA live and itis what a program actually calls; the Haskell layer adds well under amicrosecond, which the X25519 and ECDH P-256 rows confirm by agreeing with aC-level measurement to within a percent.  Both releases of crypton are builtthe same way -- `-optc-O3`, which is what each asks for -- and by`cabal build`, since a copy of the sources compiled by hand does not measurewhat a program linking the library gets, and leaves out whole implementationswithout saying so.  Each column of a table comes from one run on the machinenamed above it.  A public key figure is taken after a quarter of a second ofthe same operation, so that a fresh process's first page faults are notcounted in it.### x86-64An AMD EPYC 7763, which has AES-NI, PCLMULQDQ, AVX2, ADX, VAES, VPCLMULQDQand the SHA extensions, against OpenSSL 4.0.3.Throughput in MB/s, **higher is better**:| | crypton 1.1.5 | crypton 2.3.1 | OpenSSL | 2.3.1 / OpenSSL || --- | ---: | ---: | ---: | ---: || AES-128-GCM | 1343 | **5928** | 4060 | 1.46 || AES-256-GCM | 1104 | **5443** | 3761 | 1.45 || ChaCha20-Poly1305 | 387 | 2197 | 2216 | 0.99 || SHA-1 | 722 | 1666 | 1679 | 0.99 || SHA-256 | 283 | 1587 | 1575 | 1.01 || SHA-512 | 444 | 771 | 749 | 1.03 || SHA3-256 | 109 | 422 | 437 | 0.97 |Time per operation in microseconds, **lower is better**:| | crypton 1.1.5 | crypton 2.3.1 | OpenSSL | OpenSSL / 2.3.1 || --- | ---: | ---: | ---: | ---: || X25519 | 43.55 | 28.18 | 35.11 | 1.25 || ECDH P-256 | 164.5 | 49.92 | 51.42 | 1.03 || ECDH P-384 | 2208 | **161.2** | 851.1 | 5.28 || Ed25519 sign | 30.1 | 17.87 | 33.91 | 1.90 || Ed25519 verify | 49.17 | 48.83 | 115.1 | 2.36 || ECDSA P-256 sign | 73.83 | 15.65 | 21.41 | 1.37 || ECDSA P-256 sign (IO) | 88.5 | 20.42 | 21.5 | 1.05 || ECDSA P-256 verify | 227.9 | 66.68 | 67.13 | 1.01 || ECDSA P-384 sign | 2230 | **289.4** | 894.1 | 3.09 || ECDSA P-384 sign (IO) | 2258 | **295** | 895.3 | 3.03 || ECDSA P-384 verify | 2623 | **456.2** | 726.7 | 1.59 || RSA-2048 sign/decrypt | 755 | 620.5 | 658.5 | 1.06 || RSA-2048 verify/encrypt | 30.95 | 17.83 | 18.79 | 1.05 || RSA-3072 sign/decrypt | 2492 | 2185 | 2006 | 0.92 || RSA-3072 verify/encrypt | 62.98 | 41.35 | 39.98 | 0.97 |### AArch64An Apple M4, which has the AES, PMULL, SHA-1, SHA-2, SHA-512 and SHA-3instructions, against OpenSSL 4.0.3.Throughput in MB/s, **higher is better**:| | crypton 1.1.5 | crypton 2.3.1 | OpenSSL | 2.3.1 / OpenSSL || --- | ---: | ---: | ---: | ---: || AES-128-GCM | 133 | **12136** | 11091 | 1.09 || AES-256-GCM | 99 | **9864** | 9344 | 1.06 || ChaCha20-Poly1305 | 796 | 2388 | 2297 | 1.04 || SHA-1 | 1231 | 3389 | 3364 | 1.01 || SHA-256 | 494 | 3398 | 3372 | 1.01 || SHA-512 | 756 | 1880 | 1895 | 0.99 || SHA3-256 | 557 | 1118 | 1098 | 1.02 |Time per operation in microseconds, **lower is better**:| | crypton 1.1.5 | crypton 2.3.1 | OpenSSL | OpenSSL / 2.3.1 || --- | ---: | ---: | ---: | ---: || X25519 | 17.6 | **11.88** | 15.34 | 1.29 || ECDH P-256 | 65.38 | **20.13** | 24.17 | 1.20 || ECDH P-384 | 3195 | **67.6** | 371.6 | 5.50 || Ed25519 sign | 13.23 | **7.783** | 13.23 | 1.70 || Ed25519 verify | 17.37 | 17.18 | 34.39 | 2.00 || ECDSA P-256 sign | 30.9 | **6.567** | 10.49 | 1.60 || ECDSA P-256 sign (IO) | 74.55 | **9.633** | 10.87 | 1.13 || ECDSA P-256 verify | 91.98 | **27.18** | 31.87 | 1.17 || ECDSA P-384 sign | 3223 | **121.8** | 395.3 | 3.25 || ECDSA P-384 sign (IO) | 3342 | **127.1** | 395.7 | 3.11 || ECDSA P-384 verify | 3885 | **201.8** | 331.6 | 1.64 || RSA-2048 sign/decrypt | 449.3 | 323.9 | 321.9 | 0.99 || RSA-2048 verify/encrypt | 18.2 | 9.517 | 8.376 | 0.88 || RSA-3072 sign/decrypt | 1478 | 960.2 | 935.5 | 0.97 || RSA-3072 verify/encrypt | 47.7 | 20.65 | 17.78 | 0.86 |### What the numbers sayThere are two changes behind the 1.1.5 column and the 2.3.1 one, not asingle steady improvement.The first, in 2.0.0, was a rewrite: the bulk algorithms moved into C, thecurves other than P-256 moved out of Haskell `Integer` arithmetic, andeverything that touches a secret was made to take the same time whatever thesecret is.  1.1.5 had no AArch64 code of its own at all, which is why AES-GCMthere is close to a hundred times what it was, and on x86-64 it had AES-NIand nothing else.The second, from 2.1.0 onwards, is assembly, for the operations where Ccannot reach.  Which of the two a row owes its gain to is not the sameeverywhere: ECDSA P-384 signing took nineteenfold from the rewrite and afurther fifth from the assembly, while X25519 waited for the assemblyentirely and ECDH P-384 is almost all of it.Most of that assembly is not crypton's.  The prime curves, the inverse moduloa group order, X25519, and RSA's Montgomery multiplication on x86-64 gothrough [s2n-bignum](https://github.com/awslabs/s2n-bignum), vendored in`cbits/s2n`.  Every routine in it carries a machine-checked proof inHOL-Light that it computes what it says, and is written in a constant-timestyle.  It is `Apache-2.0 OR ISC OR MIT-0`, and crypton takes it under ISC.That licence is why any of this was possible.  The obvious assembly to reachfor is OpenSSL's and BoringSSL's `ecp_nistz256`, and it cannot be used here:it is Apache-2.0 only, and Intel and CloudFlare hold copyright in it besidesOpenSSL, so nobody is in a position to relicense it.crypton is behind in a few rows now: RSA on AArch64, and RSA-3072 onx86-64.  TheAES-GCM rows were the other half of this section until 2.1.5; they are aheadon both machines now, and what the instructions do is still worth setting out.*RSA.*  2.0.0 made signing slower than 1.1.5 on purpose: its modularexponentiation stopped indexing a table with the bits of the exponent, andhiding the exponent is what the difference bought.  2.2.5 has repaid that coston both machines, by different means.  On x86-64 s2n-bignum's Montgomerymultiplication is twice the C's, because the C cannot form the two carrychains `ADCX` and `ADOX` give, and 2.2.5 signs in less than 1.1.5 took, at3072 bits as well as 2048.  On AArch64 s2n-bignum's routines measure no betterthan the C, so the gain there is the C's own: the multiplication and squaringfor each key size are generated and unrolled, with the reduction folded intoeach column as in Koç, Acar and Kaliski's FIPS method, and signing is within afew per cent of OpenSSL, the check of the result included.  The measurementsare in [#275](https://github.com/kazu-yamamoto/crypton/issues/275).On processors with AVX-512 IFMA, Intel Xeons from Ice Lake and AMD from Zen 4,crypton computes the two halves of the CRT together in 52-bit digits, Gueronand Krasnov's method and the one OpenSSL takes there.  Neither machine abovehas IFMA, so neither table shows it.Verification's exponent is 65537, seventeen bits, so there is littleexponentiation to speed up and the work around it counts.  crypton keeps R^2,the Montgomery constant of a modulus, for the moduli it has seen, and from2.2.5 hands the signature to the C as bytes and builds the padding without alist.  On macOS it verifies in its own C at every RSA size: the GMP that GHCbuilds into itself there is compiled without optimisation([ghc#28030](https://gitlab.haskell.org/ghc/ghc/-/work_items/28030)), which ismost of what the RSA-3072 verification row on AArch64 gained.  Elsewhere GMPkeeps the sizes other than 2048 bits, except on x86-64 with ADX, where theC takes 3072 and 4096 bits as well from 2.2.6; that is what the RSA-3072verification row there gained.*The wide AES instructions.*  `VAES` and `VPCLMULQDQ` do two blocks where`AES-NI` and `PCLMULQDQ` do one, and four in their 512-bit form.  crypton usesthe 256-bit form where the processor has it, which is Zen 3 and Ice Lakeonwards, and the 512-bit form where that is worth having, which is Ice Lake andZen 5 onwards.  There was nothing to borrow: the wide AES-GCM in OpenSSL,BoringSSL and AWS-LC is Apache-2.0 and s2n-bignum has no GCM, so both files arecrypton's own.Having the 256-bit one is where the 1.46 in the x86-64 table comes from, andit is narrower than it sounds.  The EPYC 7763 is Zen 3: VAES and VPCLMULQDQ,no AVX-512.  OpenSSL's x86-64 AES-GCM is `aesni-gcm-x86_64.pl`, which is128-bit -- its `vaesenc`s are the VEX encoding of `AESENC` on `xmm`, andthere is not one `ymm` in the file -- or `aes-gcm-avx512.pl`, which wants`AVX512VAES`.  There is no rung between them, so on this processor OpenSSLtakes a block at a time where crypton takes two.  The same idea as theirs,one step further down the feature ladder; not a better one.The 512-bit path arrived after 2.1.2, so it is in the 2.3.1 column -- butneither machine in the tables above has AVX-512, so neither column shows it.On the runners that do, measured over 16 KiB in MB/s: an EPYC 9V45 (Zen 5)goes from 9616 to 14268 with it, a Xeon 6973P-C from 8095 to 9848, a Xeon8573C from 6983 to 8447.  OpenSSL on those machines is ahead still -- 25760on the first of them -- because it interleaves the GHASH with the AES wherecrypton does them in turn.  Zen 4 keeps the 256-bit path: its 512-bitinstructions are two passes through a 256-bit datapath, so the wider encodingbuys nothing there and costs a little.AArch64 has no counterpart to any of these: one AES block and one GHASHmultiplication at a time is all the instruction set offers.  Its AES-GCMrows were 0.85 and 0.87 until 2.1.5, for that reason.  What closed it wasnot width but the GHASH's representation -- H is twisted once at key setupso that GCM's bit reflection is already undone, which turns a reduction ofsome twenty-five shifts and XORs into two PMULL and six EOR and makesKaratsuba worth taking.  The scheme is ARM's, from the BSD-3-Clause part of[AArch64cryptolib](https://github.com/ARM-software/AArch64cryptolib),written out in crypton's own intrinsics.  The AES there is ahead ofOpenSSL's and always was; it was the GHASH beside it that was behind.ECDSA signing has two rows.  `sign` is `signWith` given a nonce, thearithmetic alone.  `sign (IO)` is `sign` run in `IO`, which is what a programcalls and what `openssl speed` measures: from 2.3.0 the nonce is RFC 6979'swith 32 bytes from the system generator added to it, and the system generatorasks the OS on every draw.  In 2.3.0 that cost about 6 microseconds on x86-64and 3 on AArch64; 2.3.1 runs the nonce's HMAC_DRBG in C and takes back a thirdof it.  A per-thread generator, through `setSystemRandomMode`, makes the drawcheaper, and a program's own DRG, through `withDRG`, cheaper still.One row wants a word of its own: crypton's `Ed25519.sign` derives the publickey from the secret key every time it signs, so that a caller who passes apublic key that does not match cannot be made to leak the private one.  Thatcosts a second scalar multiplication, which OpenSSL's signing does not pay --and the row is still 1.70 on AArch64 and 1.90 on x86-64, so the safety is hadfor nothing here rather than paid for.Ed25519 verification wanted one too, for an unhappier reason, and 2.2.1settles it.  On x86-64 the row was about eight per cent slower from 2.1.8onwards: 2.1.5, 2.1.6 and 2.1.7 all measure near 48 microseconds there,2.1.8, 2.1.10 and 2.2.0 all measure near 52, and 2.2.1 is near 48 again.Nothing in Ed25519 ever changed -- no commit touches `cbits/ed25519` acrossany of it, and AArch64 never moved, the compiled `ed25519.o` there beingbyte for byte the same object either side of 2.1.8.  What moved was a linein this package's cabal file.  The ML-KEM and ML-DSA backends that 2.1.8vendored want `-mavx2 -mbmi2`, and they were given as `cc-options` inside an`if arch(x86_64)` block -- but cc-options in a conditional belong to thecomponent and not to the block, so every C file in the library was compiledwith AVX2 allowed, `cbits/ed25519` among them, and what the compiler made ofit that way is slower on this machine than what it replaced.  Signing, whichis the same file and a different routine, is where it always was.  2.2.1narrowed the flags to the assembly that asked for them, which is also whatstopped a binary built on one x86-64 machine from dying on another, and therow came back.SHA-1 is in the tables because a number of protocols and file formats stillask for it, not because it is a good choice for anything new.  The algorithmsthat nothing should ask for any more -- MD5, 3DES, RC4, CBC mode -- are leftout.ML-KEM and ML-DSA are left out too, though 2.1.8 brought both and they arefast -- `mlkem-native` and `mldsa-native`, from the PQ Code Package.  Nocomparison is reported here: the implementations to measure against arestill developing.