Who is Who
(Forcibly incomplete but still quite pertinent list of core cryptographers)
-@[] REF 1: Wikipedia list of Cryptographers
-@[] REF 2: Mc Curley list
- Carl Friedrich Gauss
 Developed the modern approach to Modular Arithmetic, the core pilar of cryptography.

-ºClaude Shannonº
  he was not a cryptographer,
  but theºfounder of information theoryº
  ºon which "everything" is basedº
-ºCharles Babbageº
-ºAda Lovelaceº
-ºRon Rivestº(the 'R' in the RSA)
-ºAdi Shamirº(the 'S' in the RSA)
- Leonard Adleman (the 'A' in the RSA) @[]
-ºWhitfiled Diffieº
  (Diffie-Hillman key exchange protocol)
- @[]  Claus-Peter Schnorr
  Inventor of Shnorr signatures
- Eli Biham: Biham
   Ph.D. for inventing (publicly) differential cryptanalysis,
   while working under Adi Shamir. It had, it turned out, been invented
   at least twice before. A team at IBM discovered it during their work
   on DES, and was requested/required to keep their discovery secret
- Nick Szabo (Bitcoin "co?"inventor),
  came up with the idea of "bit gold" and developed
  the idea of smart contract
- @[] Wei Dai,
  create b-money, mentioned in the  second version
  of the Bitcoin paper
-ºHal Finneyº
 ºPGP Developerº Bitcoin co?inventor
- Paul Kocher
- Moxie Marlinspike
  founder of secure messaging organization Signal
- Ross Anderson
  University of Cambridge, Computer Lab.
- Martin Kleppmann
  Senior Research Associate and Affiliated Lecturer at 
  the University of Cambridge Department of Computer Science and Technology.
  Author of 
- Adam Back
 ºproof-of-workºsystem used by several anti-spam systems (and Bitcoin,..)
- Don Beaver
- Mihir Bellare
@[] ,
  - professor at the University of California San Diego.
  - published several seminal papers in the cryp. field
    (notably in the area of provable security), many
    of which were co-written with Phillip Rogaway.
    and Format-Preserving Encryption.
-ºEran Tromerº@[] ,
  - ZCash Inventor and founding scientist
    privacy-preserving cryptocurrency which implements our
    @[] Zerocash protocol.
   - RSA Key Extraction via Low-Bandwidth Acoustic Cryptanalysis
    """particularly interested in what happens when cryptographic
     systems meet real world offaulty and leaky computation."""
  -  heads the @[] Laboratory
     for Experimental Information Security (LEISec) investigating side
     channel info leakage in computers through physical emanations
     electric and electromagnetic) and software (e.g.,
  -  cache contention in local and cloud computing
     Remote Identification of Encrypted Video Streams
  -  cofoundedºSCIPR Labº@[]:
     cryptographic zero -knowledge SNARK proof systems-
  -  Interested in blockchain-based cryptographic protocols,
  -  Other research interests:
     - tamper resilience, homomorphic encryption,
     special-purpose code-breaking hardware and various
     aspects of network and systems security.
  -  Publications: @[]
     publications for more information.

- @[] Steve Bellovin,
   a researcher on computer networking and security.
   Professor in the Computer Science department at Columbia
   University,[1] having previously been a Fellow at AT⅋T Labs
   Research in Florham Park, New Jersey.[2][3]
   - In September 2012, Bellovin was appointed Chief
   Technologist for the United States Federal Trade Commission,
   replacing Edward W. Felten, who returned to Princeton University
- Philippe Béguin
- Josh Benaloh(formerly Cohen)
  - pioneered new technologies including:
    - "cast or spoil" paradigm that brings voters into
      the verification process with minimal burden.
- OºDaniel Julius Bernsteinº (@[])
 (@[] Wikipedia).
  critic of the leading email and DNS packages of the time,
  Sendmail and BIND. Bernstein attempted to address the situation
  by designing and implementing secure email and DNS services
  (qmail, ezmlm, djbdns, etc.)
  - sued the United States Government in 1995 (Bernstein
  v. United States).
  - His software received significant attention and no bugs
    were found in it for eight years.
  - Designer of theºSalsa20ºstream cipher
    in 2005 and submitted it to eSTREAM for
    review and possible standardization.
  - In 2008 published a closely related stream cipher,
  - Heºalso proposed the elliptic curve Curve25519ºas a basis
    for public-key schemes in 2005, and worked as the lead
    researcher on the Ed25519 version of EdDSA.
- @[]  Ke Xu
- @[]  Sung-Ming Yen
- @[]  Tatu Ylönen
- @[]  Adam Young
- @[]  Moti Yung
- @[]  Yulian Zheng
- @[]  Phil Rogaway
- @[]  Avi Rubin
- Steven Rudich
- @[]  Kouichi Sakurai
- @[]  Takashi Satoh
- @[]  Berry Schoenmakers
- @[]  Jennifer Seberry
- Joan Feigenbaum
- Niels Ferguson
- Marc Fischlin
- Yair Frankel
- Matt Franklin
- Peter Gemmell
- Rosario Gennaro
- Ian Goldberg
- Oded Goldreich
- Shafi Goldwasser
- Li Gong
- Wei Dai (Crypto++)@[']
- Mark Goresky
- Shai Halevi
- Helena Handschuh
- Carlo Harpes
- Martin Hellman (pubs only)
- Amir Herzberg
- Frederic Huygens
- Hideki Imai
- Russell Impagliazzo
- David McGrew
- Alfred Menezes
- Ralph Merkle
- Daniele Micciancio
- Chris Mitchell
- Shiho Moriai
- Sean Murphy
- Clifford Neumann
- Mats Näslund
- Moni Naor
- Harald Niederreiter
- Valtteri Niemi
- Luke O'Connor
- Andrew Odlyzko
- Kazuo Ohta
- Rafail Ostrovsky
- Christof Paar
- Torben Pryds Pedersen
- Rene Peralta
- Giuseppe Persiano
- Holger Petersen
- Birgit Pfitzmann
- Josef Pieprzyk
- Tom Berson, Advisory Board Member
  and Chief Security Advisor at since 1999 foundation
- Thomas Jakobsen
 - Markus Jakobsson
 - Stanislaw Jarecki
 - Antoine Joux
 - Marc Joye
 - Ari Juels
 - Mike Just
 - Kwangjo Kim
 - Seung-Joo Kim
 - Andy Klapper
 - Lars Knudsen
 - François Koeune
 - Kaoru Kurosawa
 - Markus Kuhn
 - Eyal Kushilevitz
 - Lam Kwok-Yan
 - Pil Joong Lee
 - Reynald Lercier
 - Helger Lipmaa
 - Mark Lomas
 - Mike Luby
 - Philip MacKenzie
 - Spyros Magliveras
 - Gilles Brassard
 - Lawrie Brown
 - Johannes Buchmann
 - Mike Burmester
 - Christian Cachin
 - Jan Camenisch
 - Ran Canetti
 - Anne Canteaut
 - Florent Chabaud
 - Che-Hao (Albert) Chang
 - David Chaum
 - Benny Chor
 - Andy Clark
 - Lorrie Cranor
 - Claude Crépeau
 - Ivan Damgård
 - George Davida
 - Alfredo de Santis
 - Giovanni Di Crescenzo
 - Don Davis
 - Dorothy Denning
 - Yvo Desmedt
 - Cunsheng Ding
 - Hans Dobbertin
 - Carl Ellison
 - Paul Fahn
 - Jean-François Dhem
 -  Ted Wobber
 -  Stefan Wolf
 -  Dong-Ho Won
 -  Avishai Wool
 -  Dongho Won
 -  Rebecca Wright

 - Ueli Maurer
 - Kevin McCurley
 - Robert J. McEliece
 - Benny Pinkas
 - David Pointcheval
 - Thomas Pornin
 - Guillaume Poupard
 - Bart Preneel
 - Jean-Jacques Quisquater
 - Tal Rabin
 -  Omer Reingold
 -  Mike Reiter
 -  Ali Aydin Selcuk
 -  Alan Sherman
 -  English
 -  Adam Shostack
 -  Victor Shoup
 -  Tom Shrimpton
 -  Alice Silverberg
 -  Joseph H. Silverman
   by the NSA, who evidently knew about it as well.
 - John R. Black
 - Simon Blackburn
 - Matt Blaze
   (corporate @[] here)
 - Daniel Bleichenbacher
 - Manuel Blum
 - Carlo Blundo
 - Dan Boneh
 - Antoon Bosselaers
 - Joan F. Boyar (formerly Joan Plumstead)
 - Colid Boyd
 - Stefan Brands,
   - cryptographer specialized in electronic cash and digital identity.
   - best known for designing Microsoft's U-Prove protocols .
 -  Markus Stadler
 -  Frank Stajano
 -  Jacques Stern
 -  Anton Stiglic
 -  Doug Stinson
 -  Yuriy Tarannikov
 -  Stafford Tavares
 -  Yiannis Tsiounis
 -  Jeroen van de Graaf
 -  Joos Vandewalle
 -  in English
 -  David Wagner
 -  Susanne Wetzel
 - Thomas Beth
   Albrecht Beutelspacher,
   mathematic "broadcaster"
External Links
 Ian Coleman JS Tools for:
   - BIP39 Mnemonic Code Converter
   - Blockchain Blocksize/SAFE Network Attack/...
   - Group Size Calculator
   -  Cost Benefit Calculator
   - Multisig Tool
   - ...
  information about our different cryptographic schemes and constructions,
  their specifications, cryptanalysis on them, the ongoing contests and the
  related scientific papers.
- Outline of Cryptography at Wikipedia
- The Bouncy Castle FIPS Java API in 100 Examples 
- IACR Cryptology ePrint archives
- Ronald L.Rivest List of Links!!!
- Kevin McCurley's links
- University of Southern California (Information Sciences Institute; Global Operating Systems Technology (GOST) Group)
- articles on exploits, security alerts, ...
- Electronic Colloquium on Computational Complexity
- ACM Special Interest Group on Security, Audit and Control (SIGSAC)
- NSA Playset (OOSS ANT catalog)

- SCIPR Lab:
  is a multi-institutional academic collaboration of researchers
  seeking to bring to practice cryptographic proof systems that
  provide succinct integrity and privacy.

ºNumber Theoryº
- Web
- Number Theory and its History
- The Prime Pages
- NTL: A Library for Doing Number Theory

- Crypto101
- Encyclopedia of Cryptography and Security
- Handbook of Applied Cryptography, by Menezes, van Oorschot, and Vanstone.
- Intro to Crypto.
- "Applied Cryptography", Bruce Schneier, ISBN 0-471-11709-9
- ºDoing encryption right is tough, managing secrets is even harder.º

- Perfect Secrecy
  refers to a cryptosystem whose security derives purely from information theory.
  In other words, it cannot be broken even if the adversary had unlimited computing power.
   The adversary simply does not have enough information to break the encryption and so the
  cryptosystems are considered cryptanalytically-unbreakable.

- (Perfect) Forward Secrecy
     gives assurances your session keys will not be compromised even if the private key
     of the server is compromised. Forward secrecy protects past sessions against future
     compromises of secret keys or passwords.
     WARN: Simple simetric encryption schemas are NOT forward secrecy compliant, and a
     compromised keys can reveal past encrypted-communications.

- Secret_sharing
    refers to methods for distributing a secret amongst a group of participants,
    each of whom is allocated a share of the secret. The secret can be reconstructed
    only when a sufficient number, of possibly different types, of shares are combined
    together; individual shares are of no use on their own.

- Avalanche_effect:
  desirable property of cryptographic algorithms, typically block ciphers and cryptographic
  hash functions, wherein if an input is changed slightly (for example, flipping a single bit),
  the output changes significantly.

- Malleability
  - An (often) undesirable property of some cryptographic algorithms.
  - An encryption algorithm is "malleable" if it is possible to transform a ciphertext
    into another ciphertext which decrypts to a related plaintext.

- Sponge Function
   In cryptography, a sponge function or sponge construction is any
   of a class of algorithms with finite internal state that take an
   input bit stream of any length and produce an output bit stream of
   any desired length. Sponge functions have both theoretical and
   practical uses. They can be used to model or implement many
   cryptographic primitives, including cryptographic hashes, message
   authentication codes, mask generation functions, stream ciphers,
   pseudo-random number generators, and authenticated encryption.[1]
brute force attacks
According to the second law of thermodynamics,
the minimum amount of energy required to record a single
bit by changing the state of a system is:

  K x T  (Boltzman Constant "times" the temperature of the system)

Assuming our computer is ideal and running at 3.2 K (The temperature
of the cosmic background radiation), a bit change would consume
4.4 x 10^-16 erg.
Since the annual output of the Sun is 1.21 x 10^41 Erg, if we
used all its energy we could power 2.7 x 10^56 single bit changes,
which is enough to put a 187-bit counter through all its values.

To run through a 256-bit key we would need to build Dyson spheres
and capture the energy of:

º2^69 = 5.9 x 10^20 Suns during a year!!!º
Random number generators
- True random number generators(quantum, thermanl, oscillators,...)
- Cryptographically secure pseudorandom generators (Unix /dev/urandom, Windows CryptGenRandom,...)
- Psuedorandom number generators

Wrong Random number generation can break many systems. Example:
!!!!Poor Random Number Generation Makes 1 in Every 172 RSA Certificates Vulnerable!!!! ← !!!!
Symmetric cryptography
Symmetric primitives
Peer 1                              Peer 2
Plain → |Encrypt|→ C1 → |Decrypt| → Plain
            ^                ^
            └─ KEY("Secret") ┘
         Shared by peer 1 and 2
NOTE: In symmetric crypto the key is often refered with
      the name of "password" to distinguish from the "private key"
      used in asymmetric crypto. schemas.

Symmetric cyrptography broadly splits into:
ºStream cipherº:
 - inputs of "any lenght". Very difficult to implement properly
   Implementations: ChaCha, ...

     INPUT     → |Keystream |→ K0, K1, ...
   (KEY, NONCE)  |Generator |         → XOR → C0, C1, ...
                               M0, M1, ...

 - "BUTS": Generate a safe (non predictive) KEY for the stream cipher is "difficult"
ºBlock cipherº:
 - inputs must be divided into chunks of same size
 - Hide plaintext transformation to ciphertext through:
   - ºconfusionº: mapping input to output hard to predict (not linear and parts of keys)
   - ºdiffusionº: permutate bits
 - Most block ciphers are based on SP-Networks composed of:
   - Subtitution box : "map˂byte, byte˃"   (replace bytes with bytes )
   - Permutation box :  moves bits around
   - Some substitution plus permutation are combined into a single round
   - Rounds are then repeated enough times to ensure the algorithm is secure
   - SP-Networks alone are not enought. KEY secret is used like:
                  ROUND1                ROUND2
   Plain → XOR → |Subsitution| → XOR → |Subsitution| → C
           KEY   |Permutation|   KEY   |Permutation|

- used when the message does exactly match a multiple of key size.
- Required by block padding cyphers. Streaming modes of operation
  can encrypt and decrypt messages of any size and therefore do
  not require padding.
Modes of operation
- A block cipher by itself is only suitable for the secure cryptographic
  transformation (encryption or decryption) of one fixed-length group of bits
  called a block. A mode of operation describes how to repeatedly apply a
  cipher's single-block operation to securely transform amounts of data larger
  than a block.
- Most modes require a unique binary sequence, often called
  an initialization vector (IV), for each encryption operation. The IV has to
  be non-repeating and, for some modes, random as well. The initialization
  vector is used to ensure distinct ciphertexts are produced even when the
  same plaintext is encrypted multiple times independently with the same key.
- Block ciphers have one or more block size(s), but during transformation
  the block size is always fixed.
- Block cipher modes operate on whole blocks and require that the last part
  of the data be padded to a full block if it is smaller than the current
  block size.
- There are, however, modes that do not require padding because they
  effectively use a block cipher as a stream cipher.
- Electronic code block (ECB):
  (WARN: Don't use it, if different messages share same data information leaks cans rise)
M1 → |E_k| → C1
M2 → |E_k| → C2
M3 → |E_k| → C3
- Cipher block chaining (CBC):
IV: Initialization vector
M1 → |XOR(IV)| → |E_k| → C1
   → |XOR(M2)| → |E_k| → C2
   → |XOR(M3)| → C3
   - Not paralelizable , and can not seek randomnly
   - Needs an IV (Difficult to generate)
- Counter Mode (CT):(Can be paralellized)
  Nonce + 0 → |E_k| → XOR(M1) → C1
  Nonce + 1 → |E_k| → XOR(M2) → C2
  Nonce + 2 → |E_k| → XOR(M3) → C3
 ºNoces are used onceº
 ºIVs must be unpredictableº
-ºº: SP-Network based (Advanced Encryption Standard).
  - "Almost every block cipher uses AES". Supersedes DES (2002 Standard)
  - Built around Rijndael (SP-Network with 128bit block size) and key length of 128,192, 256 bit
  - Round count depends on key lenght: 10, 12 or 14 cycles
  - Each Round: SubBytes, ShiftRows, MixColumns
  - Modern CPUs have hardware instruccions to accelerate AES computation
  - AES-NI x86 acceleration:
  - REF: study of AES-NI acceleration using (Libre|Open)SSL
    @[] November 08, 2018
  - AES-NI x86-extension provides:
    - improved the speed of cryptographic calcs. using AES standard (AES-128,AES-256,...).
    - Must be enabled through the BIOS.
    - Only supported by real CPU cores, NOT hyper-threaded/Virtual cores
    - Designed to provide 4x to 8x speed improvements.
    - Checking AES-NI enabled on linux:
      $ cat /proc/cpuinfo | grep flags
      flags           : fpu vme ...ºaesº ... arat

  - Test benchmark:
    - TLS v1.2 and TLS v1.3 connections (typical connections in HTTP/2 , HTTPS clients)
    - Testing soft:
      LibreSSL 2.5.0 ( ~ OpenSSL 1.0.2d) ; FreeBSD 11 ; Clang LLVM compiler
      8192 byte blocks
       Script used for testing:
       $ openssl speed -elapsed -evp chacha
       $ openssl speed -elapsed -evp aes-128-gcm
       $ openssl speed -elapsed -evp aes-256-gcm
       $ openssl speed -elapsed -evp aes-128-cbc
       $ openssl speed -elapsed -evp aes-256-cbc

  AES Performance per-CPU-core for TLS v1.2 Ciphers
  - MegaBytes-per-sec, Higher is Better
  - ChaCha20 (256 bit stream cipher, ºNOT acceleratedº) used as reference/baseline
    (Note,ºGoogle opts for ChaCha20 for low-powered devicesº)

                    ºChaCha20  AES-128-GCM  AES-256-GCM  AES-128-CBC  AES-256-CBC  Total Scoreº
  AMD Ryzen 7 1800X   573       3006         2642         1513         1101        = 8835
  Intel W-2125        565       2808         2426         1698         1235        = 8732
  Intel i7-6700       585       2607         2251         1561         1131        = 8135
  Intel i5-6500       410       1729         1520         1078          783        = 5520
  AMD FX 8350         367       1453         1278          716          514        = 4328
  AMD FX 8150         347       1441         1273          716          515        = 4292
  Intel E5-2650 v4    404       1479         1286          652          468        = 4289
  Intel i5-2500K      358       1274         1140          728          522        = 4022
  AMD Opteron 6380    293       1203         1063          589          423        = 3571
  Intel Xeon E5-2630  247        962          864          541          394        = 3008
  Intel Xeon L5630    225        701          610          626          450        = 2612
  Intel E5-2603 v4    236        866          754          382          274        = 2512
  Intel i7-950        401        256          218          358          257        = 1490
  Intel ATOM D525      98         51           43           28           20        =  240
  Snapdragon S4 Pro*1 131         41            -            -            -        =  172
  ARM Cortex A9    *1  73         24            -            -            -        =   97

  *1: Snapdragon and ARM Cortex values reported by Google Developers

  ºHow do I interpret the results ?º
  Let's suppose:
    - connection bandwidth: 10 Gbs (=1,250MBs)
    - Web server is able to concurrently encrypt|decrypt
      data to saturate the 10 gigabit connection.
    - Suppose 100% of our clients use AES-128-GCM cipher

  IDEALLY we would like the CPU could processes 10Gbs/1,250MBs of AES encrypted data per-cpu-core.
  - Since we need to recieve (decrypt) and send (encrypt) the data we need at least two(2) CPU cores.
    -  each CPU must be able to sustain 1,250 MB/s.
  - From previous performance-table, just "AMD Opteron 6380" and  faster ones will be able to keep to pace.
    (Note: Opteron-6380 has 16 cores, so it leaves many other CPU cores for network I/O, firewall rules, ...)

    - Clients connect with a variety of ciphers and the system is not dedicated to
      just cipher processing.
    - It is also possible that the cipher processing of multiple cpu cores can be
      added together to reach the desired speed.
      - "Intel Xeon L5630" four cores that can process up to 701 MB/s AES-128-GCM data.(2,804 MBs)
      (enough speed for encrypting and decrypting data on a 10 gigabit link using AES-128-GCM)

RºTODO:º What every Software Engineer should know about AES
       ...In this article I will bring you up to speed on the Advanced
       Encryption Standard (AES), common block modes, why you need padding
       and initialization vectors and how to protect your data against
       modification. Finally I will show you how to easily implement this
       with Java avoiding most security issues.
Asymmetric cryptography
Asymmetric primitives

- 4 keys are need for bidirectional communication.
- Public  key (known to everyone) is used for encryption
- Private key (known to owner   ) is used for decryption

PEER 1                                                     PEER 2
        | Encrypt with |                | Decrypt with |
Plain → |    Peer 2    | → CypherText → |   Peer 2     | → Plain
text    | public  key  |                | private  key |   text


        | Decrypt with |                | Encrypt with |
Plain ← |    Peer 1    | ← CypherText ← |   Peer 1     | ← Plain
text    | private  key |                | private  key |   text

  - ºpublic/private keyº where Public Key can be computed easely from private key
      but the inverse in infeasible (intractable mathematical problem).
      WARN: Quantum computer will totally defeat it

  - ºSigningº "==" message →Hash → PrivKey_encrypt → signature
    Everyone can decrypt using pub.key., probiding:

    - Non repudiability: Private key owner can not neglect having signed
    - Non tampering:message can not be moddified by third parties without the priv.key

  - ºEncryptº  "==" (one-directional) encrypt using public key
      One-directional: Only private key owner can de-encrypt. Priv.key owner can not encrypt, only sign

  - Asymmetric keys problems
    - Repeated use of key makes it easier to crack

Digital Signature
- Private key (known to owner   ) is used for signing.
- Public  key (known to everyone) is used for checking document signature.
-ºUse-Case:ºSign an input document (transaction-order) using a priv.key to
  prove non-repudiabely the intention of the owner of akcnodledment of the document
  (or transaction-order).

-GºProves authenticity of senderº← Only sender owning priv.key
                                   could have created the signature
-BºNon-repudiableº               ← Sender can NOT neglect the signature
                                   since he is the only owner of priv.key
-GºAuthenticityº  + BºNon-repudiabilityº impies OºLegal valueº:
 OºIt proves the original intention of signer to sign/agree whatº
 Oºis reflected in the documentº

 ºIS KNOWN AS THE DIGITAL SIGNATURE SCHEMA                                          º
 º GENERATE THE signer private key)                                                 º

NOTE: Signature is applied to the hash of the document

               INPUT                         OUTPUT          USE CASE
          ┌──────┴──────┐                ┌──────┴─────┐
SIGNING:   Doc ─ ─ ─ ─ ─ ─→ Doc Hash ─┐                      "prove of intention"
                                      ├─→ Doc.Signature
           signerºprv.Kº ─────────────┘   (r, s, v) in ECDSA
               INPUT                         OUTPUT          Verify doc signature
          ┌──────┴──────┐                 ┌────┴──────┐      knowning the public key
VERIFYING  Doc ─ ─ ─ ─ ─ ─→ Doc Hash ─┐
(Recursive signerºpub.Kº ─ ─ ─ ─ ─ ─ ─┼─→  TRUE | FALSE
           Doc.Signature ─ ─ ─ ─ ─ ─ ─┘
               INPUT                         OUTPUT          Verify doc. signature
          ┌──────┴──────┐                 ┌────┴──────┐      knowning only doc.hash
Pub.Key    Doc Hash -----------------─┐                      and doc.hash signature.
Recovery                              ├─→  signer pub.K      This imply that we can
           Doc.Signature ─ ─ ─ ─ ─ ─ ─┘                      compaq the storage by
           (r, s, v )                                        registering only
                                                             (doc, signature) vs
                                                             (doc, signature, pub.k)

RºWARN:ºkey-generation algorithm is as important as the signing and verification
        algorithms. See for example:
       "How Perfect Offline Wallets Can Still Leak Bitcoin Private Keys"
      """... ECDSA has become a popular choice as lightweight alternative to RSA and
      classic DL based signature algorithms in recent years. As standardized, the
      signature produced by ECDSA for a pair of a message and a key is not
      deterministic. This work shows how this non-deterministic choice can be
      exploited by an attacker to leak private information through the signature
      without any side channels, an attack first discovered by Young and Yung for
      classic DL-based cryptosystems in 1997, and how this attack affects the
      application of ECDSA in the Bitcoin protocol. """

(EC)DSA vs RSA compared
2 Approaches                                          YEAR
  ├→ RSA                                              1977
  └→ DSA Digital Signature Algorithm                  1985
      ├──→ (Used for) DSS Digital Signature Standard  1994
      └──→ When replacing Mod N by Elliptic Curve     1978
           ECDSA                                      2005
           Used, amongst many others, by
           Bitcoin/Ethereum/... to sign TXs

1976: Whitfield Diffie and Marting Hellman describe
      the notion of digital Signature
      (previous work existed but was not disclosed
       in public)

1977: The RSA algorithm is invented
      first version,"primitiv algorithm"
      RSA stays for:
      - (R)onal Rivest
      - Adi (S)hamir
      - Len (A)dleman
      - MIT was granted US patent 4.405.829 from 1983-2000

1978: Jacques Vélu, publish
      "Courbes elliptiques munies d'un sous-group Z/nZxmu_n"
      Société Mathématique de France, 57, 1-152, Paris, 1978.

1985: ElGamal signature scheme by Taher Elgamal,
      later adopted by the DSS/DSA standard by
      US Guvernamental agencies.
      (REF: "Applied Cryptography", Bruce Schneier, ISBN 0-471-11709-9)

1985: Neal Koblitz[7] and Victor S. Miller[8] suggest the use
      of elliptic curves in cryptography
      (We must wait until 2004/2005 to see broad ussage).
      1985 @[]
      1987 @[] 1987

1988: Shafi Goldwasser, Silvio Micaly and Ronald Rivest
      rigorously define the security requirements of
      digital signature schemes.
      Remember: in cryptography the scheme
      is the tuple of algorithm that define how to
      create the private key, distribute the public
      key, create a signature and verify it

1989  Schnorr patents its signature method
      Patent expired in 2008.
      As of 2013+ software companies tend to
      replace ECDSA with Schnorr.
      2014: C&P from @[]
     ...  After months of analysis and testing, we’ve concluded
     that a Schnorr-based cryptosystem will greatly enhance the
     security, flexibility, and performance of the Ripple protocol
     (when compared to Koblitz curves with secp256k1 parameters and
     ECDSA signatures as defined in :
     Standards for Efficient Cryptography
     @[] )

1991: Phil Zimmermann developes PGP

1994: First DSA schema approved as DSS
      (US National Institute of Standards and Tech NIST)
      and specified in Federal Information Processing
      Standard (FIPS) 186 (FIPS 186-1):
      DSA can use lot of "tunable switches" like the hash-funcs,
      (L, N)-param-length,....  DSS defines what those
      "tunnable switches" will be for the standard:
      - It should use hash-function: SHA-1 (recently SHA-2).
      - It should use specific length pairs: (2048,224), (3072,256),...
      - 2013 FIPS-4: @[]
    RºWARNº: See problems with DSA/DSS(year 2015)

1995: Kocher described a new attack on RSA based on
      sufficient detail on hardware and time-measures
      to deduce the decryption key d quickly.
      Randomization of time output is needed to avoid it.

1995: FIPS 180-1, Secure Hash Standard

1998: ANSI X9.62-1998: Public Key Cryptography for the
      Financial Services Industry. The Elliptic Curve Digital
      Signature Algorithm. January 1999.

1999: NIST recommends 15 elliptic curves.

2000: ESIGN Act makes online signatures legally binding

2013: Second DSA schema approved by DSS (FIPS 186-2).

2005: Elliptic Curve DSA

2009: PAdES: PDF Advanced Electronic Signatures

2009: Benjamin Moody factored an RSA-512 bit key in
      73 days using only public software (GGNFS) and
      a desktop computer with less than five gigabytes
      of disk storage and ~2.5 Gbytes RAM.
      - In 1999 it required the equivalent of
        8_400MIPS years/seven months.
      - First exploits where reported in 2011
      (minimun 2048 bit is recomended)

2009: SEC 1: Elliptic Curve Cryptography
2010: SEC 2: Recommended Elliptic Curve Domain Parameters
2013: SEC 3: Elliptic Curve Qu-Vanstone Implicit Certificate
                      Scheme (ECQV)

2013: The New York Times stated that Dual Elliptic Curve Deterministic
      Random Bit Generation (or Dual_EC_DRBG) had been included as a
      NIST national standard due to the influence of NSA, which had
      included a Rºdeliberate weakness in the algorithmº and the
      recommended elliptic curve. RSA Security in September 2013
      issued an advisory recommending that its customers discontinue using
      any software based on Dual_EC_DRBG.
      - Cryptography experts have also expressed concern over the
        security of the NIST recommended elliptic curves, suggesting a
        return to encryption based on non-elliptic-curve groups.

2013: Fourth DSA schema approved by DSS (FIPS 186-4).

2015: NSA announces plans to replace some ECDSA Suite B algorithms
      with a new cipher suite due to concerns about quantum-computing
      attacs on ECC.
      SSH decided to Rºdrop DSS/DSA keysºin favor of RSA due to "inherit weakness"º
        - See also critics to DSS @:

BºRSA SIGNATURE:º ("Symmetric" to Encryption with Pub.Key)
  ┌───────┐        ┌──────┐  ┌────────────┐   ┌────┐
  │Message│───────→│CONCAT│─→│Message     │──→│HASH│──────┐
  └───────┘        └──────┘  │            │   └────┘   ┌──v────┐
    │                 ^      ├────────────┤            │Compare│
    │ ┌────┐  ┌──────┐│      │C(PrivKey,h)│─→┌──────┐  └───────┘
    └→│HASH│─→│Sign  │┘      └────────────┘  │Deciph│     ^
      └────┘  └─^────┘                       └──^───┘─────┘
                │                               │
              PrivKey                         PubKey
                   Sign                        Verify

  ┌─────────┐            ┌──────┐  ┌───────┐
  └─────────┘            └──────┘  │       │  ┌──v─────┐
    │                       ^      ├───────┤  │Verifier│─┐
    │  ┌────┐      ┌──────┐ │      │s(sign)│─→└───^────┘ │
    └─→│HASH│─→h1─→│Sign  │─┘      ├───────┤      │  ┌───v───┐
       └────┘      └─^──^─┘        │r(sign)│─┬────┘  │Compare│
                     │  │          └───────┘ │       └───^───┘
               PrivKey  K(Non secret)        └───────────┘
                        Sign                     Verify

BºDSA PRESETUP (In Standards like DSS or protocols):º
  REF: @[]
  Public params defined by standard or protocol
  p = Prime Number : 2^L-1 ˂ p ˂ A^L
  q = Prime Number : q divides p-1
  g: a generator of an order-q group G
  G : Group defined by { 1,2,...p }
            Operator: Multiplication Mod p
      (Finite group)
  g = Group ( h^(p-1) ) / q

BºDSA PRESETUP: Key Generation in Clientº
  Select Private key x = random (1 to q-1 )
  Generate Pub.key y = g^x mod p

BºSIGNATURE Generationº            BºSIGNATURE Verificationº
  Select K = random ( 1 to q-1)      Take (r, s)
  Define:                            Calculate:
  X = g^k mod p                      e = Hash(M)
  r = X mod q                        U1 = e/s mod q
  e = Hash(M)                        U2 = r/s mod q
  s = K^-1 * (e + x*r) mod q         X = g^U1 y^U2
  pub.key = (r, s)                   v = X mod q
  (Retry with new K if r             Verify Result: v == r
   and/or s are 0)

  -ºcryptographic algorithmº that generates keys, signs data,
    and verifies signatures.

  - based on the mathematical concept of modular exponentiation and the
    discrete logarithm problem.
ºRSA                                      vs          DSAº

- compatible with integer prime number              - variant of the ElGamal adding secondary
  factorization                                       160-bit modulus(q) to speed up execution
-RºIn-compatible with not with                        and reduce the size of final signature.
  elliptic curvesº                                  -RºCan NOT be used for encryptionº
- computationally more expensive                    - DSA Key Generation
-BºDoes not require a source of randomnessº           1) shared global pub.key values (p,q,g)
   Prefered of embedded systems/smartcards/....          are chosen (DSA public parameters):
- RSA provides us with Public (e,n) and                 ºpº= 2 power L "Large prime"
  Private (d)                                                        ^
 ºeºis usally a small number                                       L := 512/1024 bits
 ºdºis a much large number                                              multiple of 64
- n=p.q (very large) semi-prime number                  ºqº= a 160 bit prime factor of p-1
- given an RSA scheme {(e,R), (d,p,q)}                  ºgº= h power (p-1)/q
- RSA Schema: Sign a message:                          - for any h1
  Compute:                                            2) Each user chooses a priv.key and
OºSº= M power d (mod R)                                  computes their public key:
- RSA Schema: Verify a message:                          - choose x compute y =ºgºpower x(modºpº)
  M = S power e(mod R) =                            - DSA SCHEMA: SIGN MESSAGE  'M'
    = M power e.d(mod R)                              1) generate random per message sign.key Qºkº
    = M(mod R)                                        2)Oºrº= (ºgºpower Qºkº(modºpº))(modºqº)
- RSA encryption and decryption are                     Oºsº= ºkº- 1.SHA(M)+ x.r (modºqº)
  commutative allowing to use both                       send signature (r,s) with message
  for encryption and digital sign,                    NOTE: adding (mod q) improve execution.
  simply reversing the order of
  exponents:                                        - DSA SCHEMA: VERIFY
  - secret exponent(d) used to create                 w = s-1(mod q)
    the sign.                                         u1= (SHA(M).w)(mod q)
  - public exponent(e) for anyone to                  u2= r.w(mod q)
    verify it.                                        v = (g power u1.y power u2(mod p))(mod q)
  Everything else is identical.                       if v=r then the signature is verified

ed25519/ECDSA compared
Extracted from @[]
" Deterministic signatures retain the cryptographic
  security features associated with DSA/ECDSA digital signatures
  but can be more easily implemented in various environments,
  since they do not need access to a source of high-quality randomness
  (point of failure) for the "k" parameter
  It is possible to turn DSA and ECDSA into deterministic schemes by
  using a ºdeterministic processº for generating the "random" value "k"
  fulfilling some crypto. characteristics "

- designed by prominent cryptographer Daniel J. Bernstein
- cryptosystem powering Bitcoin, Ethereum, ...
- elliptic curve implementation
- more optimal and secure design schemes
- Summary of advantages versus secp256k1:

- Large absolute value for the CM field discriminant
 (large |D| )—although there is no evidence of security problems with small |D|
- Supports simple, fast, complete
  constant-time single-scalar multiplication using
  a Montgomery ladder.
- A random curve point can be represented in a way that's
  indistinguishable from random data.
- Faster performance
- ...  Our initial tests and analysis suggest ...
  Curve25519 halves verification time versus secp256k1 based on efficient implementations
  of both curves.
  - These results were achieved with lower variance, which point to the constant time
    properties of Curve25519.
  - the default signature format for Ed25519 allows batch signature verification,
    which promises twice the performance of DSA.
  - Raw test results
  - Benchmark source code

  - the new curve implementation is expected to quadruple performance versus secp256k1
    based on our preliminary benchmarking.

- Extracted from @[]
  sums up the benefits of Schnorr as follows:
  "simple blinding, compact multi-sig, clearer security proofs, better security margin,
   less dependence on hash properties."

Summary of advantages versus ECDSA:
  - Simpler to securely implement
  - Composable threshold signatures without multi-party computation
  - Verification happens off-network allowing for sophisticated functionality without increasing network load or complexity
  - Conducive to highly distributed systems
  - Less constraints allows for more optimal and secure design schemes

  - DSA schemes are difficult to manage because the schemes are easy to get wrong.
    An improper implementations is trivial to break, and what might seem like a minor
    misstep can precipitate a system-wide vulnerability—as demonstrated by
    ...  Hackers were able to access full control of the PS3 employing "simple algebra" after Sony
    set a constant in its custom DSA implementation instead of a randomly generated number.
    The sensitivity of DSA signatures to human error allowed this single oversight to fully
    compromise the console's encryption protections, exposing the platform and Sony's partners
    to the perpetual threat of piracy.
  - Alternatively, Schnorr signatures are more forgiving and simpler to implement because its
    security is inherently more robust based on the scheme’s dynamic hash function
    The ephemeral public value r is tightly bound to the message, which means that the security
    of the scheme is no longer dependent on the collision resistance of the hash function.

  - Independent verification and combining:
    Another advantage of Schnorr is related to threshold signatures
  - ECDSA can create threshold signatures, but requires multi-party computation
    This means that the number of participants required to generate a signature
    without revealing their secrets is twice the number of shares required to recover the key.
    - In contrast, Schnorr has no such restriction. Shares of a signature can be independently
      verified and then composed.
Elliptic curves intro:
Elliptic Curves Comparative
- ¿Safe?Curves:
- Browser support

- TLS-RSA cert. with elliptic curve:

Comparisions of secp256r1-vs-secp256k1 Elliptic Curves:
Ed25519 JS Signature

- Minimal implementation of Ed25519Signature2018 in JavaScript.

- This library focuses on verification of signatures, and does not
  attempt to mix validation with verification logic. You may prefer to
  use jsonld-signatures.
Hash Primitives
Hash primitives
Plain  → | Hash | → Hash Result

- A single bit change in "Plain" input causes a completely
  different Hash Result
- There are infinite plain inputs for each possible hash output,
  still given a single hash output, it's extremnly difficult to
  find any of the infinite plain inputs (without previous knowledge)
- Used to validate input integrity (input has not been modified).
- Frequently combined with symmetric/asymmetric primitives.

- takes message of any lenght, and returns a pseudoramdom hash of fixed length
┌─── Loop ←──┐
│            │
Block of   Current ──→ Final hash
message     Hash
- HMAC: An attacker doesn't know the shared KEY so he can not add the correct HASH
PlainText → |symmetric(KEY)| → CipherText

CipherText + HASH(KEY+CipherText)
- Q: Why the "5381"/"33"/... constant in hash?:
  A: """ 5381 is just a number that, in testing, resulted in
  fewer collisions (@[] and
  better avalanching(@[]).
  You'll find "magic constants" in just about every hash algo.
SHA-3 is a subset of the broader cryptographic primitive family Keccak
BLAKE3: CPU Parallelizable Hash
BLAKE3 Is an Extremely Fast, Parallel Cryptographic Hash
- BLAKE3 is the most recent evolution of the BLAKE cryptographic hash
  function. Created by Jack O'Connor, Jean-Philippe Aumasson, Samuel
  Neves, and Zooko Wilcox-O'Hearn, BLAKE3 combines general purpose
  cryptographic tree hash bao with BLAKE2 to provide a big performance
  improvement over SHA-1, SHA-2, SHA-3, and BLAKE2.
HMAC primitives
"secret-shared signature"

- HMAC = "MAC + symmetric encryption"
- Message passes throuh a hash function twice, and is combined with
  the (secret key) key before each pass

    → sym.cypher(key inner)
        → hash
            → sym.cypher(key outer)
                → hash
                    → out

  An HMAC authenticates a message (principal == "owner of private key").
    If a message comes with a correct MAC attached, it means this message
    was seen by a holder of the secret key at some point.
    HMAC is a signature based on a secret key, providing similar
    assurances to a signature scheme based on public-key cryptography
two non-local parties can jointly agree a shared secret over an insecure channel

    - DH-KEX (Key exchange) Underpins almost every aspect of our modern lives!
    - DH security is based first on "very big numbers", with 4096 bits becoming more ussual.
    - The DH-KEX generated shared-secret is usually called the "pre-master secret"
    - It's used to derive session keys through hashing for example
    - Ephemeral Mode. DH is used only for minutes/hours and not stored.
Randomness of secret keys is not enough in most scenarios.
Next elements of randomness complements to keys:
Init Vector (IV) (symmetric enc)
- in symmetric encryption is used to ensure distinct ciphertexts are
  produced even when the same plaintext is encrypted multiple times
  with the same key. ºIV must not be repeated,ºand depending on the
  scheme used must also be UN-predictable (cryptographically random)

Salt (Hashing)
- is random data that is used as an additional input to a one-way
  function that "hashes" data, a password or passphrase. Salts are
  closely related to the concept of nonce. The primary function of
  salts is forºkey derivation functions ºand to ºdefend againstº
 ºdictionary attacksº or against its hashed equivalent, a
 pre-computed rainbow table attack.  ºNonce must not be repeated,º
ºbut can be predictable. Salts can be repeated,
 and ºalso they must be cryptographically random to be secure,º
 (in Crypto 101 it cites: "salts generally do not have to be secret,
  and can be re-used, in the context of key derivation functions).

Nonce (session establishment)
- an arbitrary number that ºcan only be used onceº.
- Can be public or predictable but ussually it's a
  pseudo-random number ºissued in an authentication protocolº
 ºto ensure that old communications cannot be reused in replay attacks:º
  - In this attack a cracked limits to replay the encrypted
    session-establishment encrypted raw data between client and
    server hopping to obtain a session token.
  - Since the nonce has already been used/wasted by the original
    client, the session establishment will fail.
- They can also be useful as IVs and in cryptographic hash functions.
Advanced Primitives
Fernet sym. encrypt
- Fernet guarantees that a message encrypted using it
  cannot be manipulated or read without the key.
- Fernet also has support for implementing key rotation via MultiFernet.
Key Derivation Function
- @[]
- Derive one or more secret keys from a first secret one
- Many key derivation fun. admit a salt to avoid returning the smae output
  keys from the same input secret
- (cite from Crypto101): Useful, for example, when a cryptographic protocol
  starts with a single secret value, such as a shared password or a secret
  derived using Diffie-Hellman-Merkle key exchange, but requires multiple
  secret values to operate, such as encryption and MAC keys.

- Two main categories, depending on the entropy content of the secret value
  which determines how many differnet possible values the secret value can
  - input secret is user-supplied (low entropy): Key d.f will require lot
    of computing resources to avoid attackers to just compute all possible
  - input secret is random (high entropy): A trivial key derivation will
    suffice (HKDF)
- HKDF (HMAC-based (Extract-and-Expand) Key Derivation Function, defined in
  RFC 5869, @[] requires high entropy initial
  input key.
- Argon2Id(@[] is a key der. func.,
  selected as winner of the Password Hashing Competition in July 2015.
  - It maximizes resistance to GPU cracking attacks and time-memory-trade-off
    (TMTO) attacks.
  - It maximizes resistance to resist side-channel attacks.
  - It is an hybrid version (Recomended). The Internet draft[4] recommends
    using Argon2id except when there are reasons to prefer one of the other
    two modes.
Verifiable Secret Sharing
In cryptography, a secret sharing scheme is verifiable if auxiliary
information is included that allows players to verify their shares as
consistent. More formally, verifiable secret sharing ensures that
even if the dealer is malicious there is a well-defined secret that
the players can later reconstruct. (In standard secret sharing, the
dealer is assumed to be honest.) The concept of verifiable secret
sharing (VSS) was first introduced in 1985 by Benny Chor, Shafi
Goldwasser, Silvio Micali and Baruch Awerbuch.

In a VSS protocol a distinguished player who wants to share the
secret is referred to as the dealer. The protocol consists of two
phases: a sharing phase and a reconstruction phase.

Ex implementation:
Key Shadowing
-  technique of generating key shadows performed by at least one 
   computing device including at least one tangible computing element. 
   The method includes receiving an indication of a first number X 
   representing how many of the key shadows are to be generated, 
   receiving an indication of a second number Y representing how many of 
   the key shadows are to be required for decrypting an encrypted 
   message, determining or receiving a master key for decrypting the 
   encrypted message, and determining X key shadows of the master key. Y 
   of those key shadows is sufficient to generate a range of more than 
   one possible master keys that can be computationally feasibly 
   searched for the master key. Less than Y of those key shadows is 
   insufficient to determine any part of a value for the master key. 
   Also, a technique of decrypting an encrypted message using Y of the 
   key shadows. Further, associated systems.

2017 @[]
MultiSig vs threshold Signature Schemes
- Multi-signature schemes require the network to verify each signature,
  increasing load with the number of participants.

- Conversely, threshold signatures are generated offline and result in
  a single signature regardless of total number of parties participating.
┌────────────────┬───────────────────────────────────────────────────────────────┐ ┌────────────────────────┬───────────────────────────────────────────────────┐
│ºMULTISIGNATUREº│                                                               │ │ºTHRESHOLD CRYPTOSYSTEMº│                                                   │
├────────────────┘                                                               │ ├────────────────────────┘                                                   │
│@[]                                 │ │@[] (TODO)               │
│- Digital signature scheme which allows a group of users to                     │ │- In order to decrypt an encrypted message, several parties                 │
│  sign a single document. Usually, a multisignature algorithm produces          │ │  (more than some threshold number) must cooperate in the decryption        │
│  a joint signature that is more compact than a collection of distinct          │ │  protocol. The message is encrypted using a public key and the             │
│  signatures from all users                                                     │ │  corresponding private key is shared among the participating parties.      │
│- A tuple of N signatures is the simplest (non-compacted)                       │ │  Let "n" be the number of parties. Such a system is called (t,n)-threshold,│
│  multisignature scheme                                                         │ │  if at least t of these parties can efficiently decrypt the ciphertext,    │
│- Multisignature can be considered as generalization of both group              │ │  while less than t have no useful information.                             │
│  and ring signatures.                                                          │ │- Similarly it is possible to define (t,n)-threshold signature scheme,      │
│  - Used to add additional security for cryptocurrency transactions             │ │  where at least t parties are required for creating a signature.           │
│  - The required number of signatures is agreed upfront                         │ │- The most common application is in the storage of secrets in multiple      │
│  - Allows for the creation of N-of-M escrow services                           │ │  locations to prevent the capture of the ciphertext and the subsequent     │
│  - Tree-signatures (Aug 24, 2015 by Pieter Wuille, Ph.D.):                     │ │  cryptanalysis on that ciphertext. Most often the secrets that are         │
│    @[]                   │ │  "split" are the secret key material of a public key cryptography key      │
│   """Imagine you want to create a 1-of-11 multisig (with 11 known public keys).│ │  pair or the ciphertext of stored password hashes.                         │
│   You compute the SHA256 hashes of the public keys involved and put them in    │ │- In October 2012 after a number of large public website password           │
│   a Merkle tree. In the graph below, all symbol names represent 32-byte hashes,│ │  ciphertext compromises, RSA Security announced that it would be           │
│   except the 1. The 1 is used as a simple constant instead of a right branch   │ │  releasing software that makes the technology available to the general     │
│   when there is none."""                                                       │ │  public                                                                    │
│                                 R                                              │ └────────────────────────────────────────────────────────────────────────────┘
│                              /     \                                           │
│                           /           \                                        │
│                       /                   \                                    │
│                   Z1                          Z2                               │
│                /      \                     /   \                              │
│           Y1              Y2              Y3     1                             │
│          /  \            /  \            /  \                                  │
│       X1      X2      X3      X4      X5      X6                               │
│      / \     / \     / \     / \     / \     / \                               │
│     K1 K2   K3 K4   K5 K6   K7 K8   K9 K10 K11  1                              │
│                                                                                │
│   "" Using the script in our Alpha sidechain, we can build a script that takes │
│   as input a public key, a signature, and a Merkle path. At verification time, │
│   it would use the Merkle path to prove that the public key belongs to a tree  │
│   with root R, and that the signature checks out with that public key."""      │
│ºGROUP SIGNATUREº│                                                           │
├─────────────────┘                                                           │
│@[]                             │
│- A group signature scheme is a method for allowing a member of a group to   │
│  anonymously sign a message on behalf of the group.                         │
│- For example, a group signature scheme could be used by an employee of      │
│  a large company where it is sufficient for a verifier to know a message    │
│  was signed by an employee, but not which particular employee signed it.    │
│- Essential to a group signature scheme is a group manager, who is in charge │
│  of adding group members and has the ability to reveal the original signer  │
│  in the event of disputes. In some systems the responsibilities of adding   │
│  members and revoking signature anonymity are separated and given to a      │
│  membership manager and revocation manager respectively.                    │
│ºPROXY SIGNATUREº│                                                   │
├─────────────────┘                                                   │
│ A proxy signature allows a delegator to give partial signing rights │
│ to other parties called proxy signers. Proxy signatures do not offer│
│ Anonymity                                                           │
│ºRING SIGNATUREº│                                                          │
├────────────────┘                                                          │
│@[]                            │
│- Type of digital signature that can be performed by any member of         │
│  a group of users that each have keys.                                    │
│  One of the security properties of a ring signature is                    │
│  that it should be computationally infeasible to determine which of       │
│  the group members' keys was used to produce the signature                │
│- Ring signatures are similar to group signatures but differ in two key    │
│  ways: first, there is no way to revoke the anonymity of an individual    │
│  signature, and second, any group of users can be used as a group without │
│  additional setup.                                                        │
│- Invented by Ron Rivest, Adi Shamir, and Yael Tauman, and introduced      │
│  at ASIACRYPT in 2001                                                     │
│- Suppose that a group of entities each have public/private key pairs,     │
│  (Pub_1, Secret_1), ..., (Pn, Secret_n).                                  │
│  Party i can compute a ring signature σ on a message "m", on input        │
│  ("m", Secret_i, Pub_1, ..., Pub_n). Anyone can check the                 │
│  validity of a ring signature given σ, m, and the public keys involved,   │
│  P1, ..., Pn. If a ring signature is properly computed, it should pass    │
│  the check. On the other hand, it should be hard for anyone to create a   │
│  valid ring signature on any message for any group without knowing any    │
│  of the private keys for that group.                                      │
│ºBLIND (CHAUMIAN) SIGNATUREº*│                                              │
├─────────────────────────────┘                                              │
│@[]                            │
│- Blind signature schemes exist for many public key signing protocols       │
│  Blind RSA signatures, Blind ECDSA signatures,                             │
│- Java implementation:                                                      │
│  @["]        │
│                                                                            │
│- form of digital signature in which the content of a message is            │
│  disguised/blinded before being signed. The resulting blind signature can  │
│  be publicly verified against the original, unblinded message in the manner│
│  of a regular digital signature.                                           │
│- Blind signatures are typically employed in privacy-related                │
│  protocols where the signer and message author are different parties.      │
│  Examples include cryptographic election systems and digital cash schemes: │
│                                                                            │
│  ┌────────────────────────────────────────────────────────────────┐        │
│  │Seq. Diagram                                                    │        │
│  │participant user # creates a message ("vote") and blinds it     │        │
│  │participant signer # authenticates user and sign blinded message│        │
│  │signer → user: authenticate user                                │        │
│  │user   → user: +message                                         │        │
│  │user   → user: message → blind → blinded_message                │        │
│  │user   → signer: blinded_message                                │        │
│  │signer → signer: +signed_blinded_message                        │        │
│  └────────────────────────────────────────────────────────────────┘        │
│ºIdentity-Based Aggregate Signaturesº│                              │
├─────────────────────────────────────┘                              │
│@[]            │
│ An aggregate signature is a single short string that convinces any │
│ verifier that, for all 1 ≤ i ≤ n, signer S i signed message M i ,  │
│ where the n signers and n messages may all be distinct. The main   │
│ motivation of aggregate signatures is compactness. However, while  │
│ the aggregate signature itself may be compact, aggregate signature │
│ verification might require potentially lengthy additional          │
│ information – namely, the (at most) n distinct signer public keys  │
│ and the (at most) n distinct messages being signed. If the verifier│
│ must obtain and/or store this additional information, the primary  │
│ benefit of aggregate signatures is largely negated.                │
Crypto accumulator
- one way non-invertible function.
- It answers a query as to whether a potential candidate is
   a member of a set without revealing the individual members of the set.

  Ex: large composite number CP01 = P1 x P2 x P3 x ... PN
      Does P2 "belongs" to CP01? Yes, but we still don't known P1, P3, ... PN
- New members may be added or subtracted to the set of
  factors simply by multiplying or factoring out the number respectively.

Extracted from:
We can think of accumulators as a super-charged hash function that
works on sets. A regular hash function, like SHA-3, takes a single message and
outputs a fixed-size hash. An accumulator, however, takes a set of values and
turns them into a single number, also of constant size.

Alice secret
  → alt 1: hash secret        → publish hash  → reveal message to Bob (Bob can check)
  → alt 2: add to accumulator → publish accu  → reveal message to Bob, Bob can check,
                                                but the rest of secrets of the
                                                accumulator stay in place.

Batching Techniques for Accumulators @[] Batching Techniques for Accumulators with Applications to IOPs and Stateless Blockchains BºAbstract:º We present batching techniques for cryptographic accumulators and vector commitments in groups of unknown order. .. tailored for distributed settings where no trusted accumulator manager exists and up-dates to the accumulator are processed in batches. We develop techniques for non-interactively aggregating membership proofs that can be verified with aconstant number of group operations. We also provide a constant sized batchnon-membership proof for a large number of elements. BºWe use these new accumulator and vector commitment constructions toº Bºdesign a stateless blockchain, where nodes only need a constant º Bºamount of storage inorder to participate in consensus. º Further, we show how to use these techniquesto reduce the size of IOP instantiations, such as STARKs. BºApplications:º - Stateless blockchains - Short IOPs. Merkle tree paths contribute significant overhead to both the proof size of a compiledIOP proof and its verification time. Vector commitments with smaller openings thanMerkle trees, or batchable openings (i.e. subvector commitments), can help reducethis overhead ... our VCs reduce the sizeof the Aurora proofs on a 220size circuit from 222 KB to less than 100 KB, a 54%reduction, and the size of STARK proofs for a circuit of 252gates from 600 KBto approximately 222 KB, a 63% reduction. BºConclusion:º We expect that our techniques and constructions will have more applications beyond what was discussed. Several interesting open questions remain: What practical limitations occur when deploying the scheme? Is it possible to efficiently compute unions of accumulators? This is certainly true for Merkle trees but these do nothave the batching properties and constant size of RSA accumulators. Similarly canone build an accumulator with constant sized witnesses from a quantum resistant assumption? Additionally, we hope that this research motivates further study ofclass groups as a group of unknown order
Zero  Knowledge Probes
Extracted from @[]
""" we are currently experiencing a Cambrian Explosion in the field 
  of cryptographic proofs of computational integrity (CI), ☞a subset of 
  which include zero-knowledge proofs☜ . While a couple of years ago, 
  there were about 1–3 new systems a year, the rate has picked up so 
  much that today we are seeing this same amount monthly, if not 

- A zero-knowledge proof is a cryptographic method where one party (the prover)
  can prove toanother party (the verifier) that the prover knows a value x,
  without conveying any informationapart from the fact that the prover knows
  the value x.
Homomorphic Encryption
Data integrity
BºHash chainº
  - non-repudiable probe of data chronology
    doc1 → hash → has1 ─┬→ hash → has2 ─┬→ hash → has3 ─┬→ hash
                   doc2─┘         doc3 ─┘         doc4 ─┘
BºMerkle treeº
  - Allows to check if a leaf (data) is part of the tree with just a
    subset of the tree.
  - NOTE: In blockchain leafs are transactions and the tree is a block

  - It is deterministic and cryptographically verifiable:
    - The only way to generate a state root is by computing it from each
      individual piece of the state, and two states that are identical can
      be easily proven so by comparing the root hash and the hashes that led
      to it (a Merkle proof).
    - Conversely, there is no way to create two different states with
      the same root hash, and any attempt to modify state with different
      values will result in a different state root hash.

  └BºPatricia Treeº (Used by Ethereum,...)
   Fun fact: ‘Trie’ is originally taken from the word ‘retrieval’, but most
   people pronounce it as ‘try’ to distinguish it from ‘tree’ when speaking.
   "...At one end of the trie, there are all of the particular pieces of
   data that describe state (value nodes). This could be a particular
   account’s balance, or a variable stored in a smart contract (such
   as the total supply of an ERC-20 token). In the middle are branch
   nodes, which link all of the values together through hashing. A
   branch node is an array containing the hashes of its child nodes, and
   each branch node is subsequently hashed and put into the array of its
   parent node. This successive hashing eventually arrives at a single
   state root node on the other end of the trie..."

Secret sharing
- provides a method of secret sharing, where a secret is divided into parts,
  giving each participant its own unique part, where some of the parts or all
  of them are needed in order to reconstruct the secret.
   Counting on all participants to combine the secret might be impractical, and
   therefore sometimes the threshold scheme is used where any "k" of the parts
   are sufficient to reconstruct the original secret
  The essential idea of Adi Shamir's threshold scheme is that 2 points are
   sufficient to define a line, 3 points are sufficient to define a parabola, 4
   points to define a cubic curve and so forth. That is, it takes k points to
   define a polynomial of degree k − 1
- cryptographic primitive
- Used mostly in communication protocols.
- Authentication server encrypts a challenge
  (typically a random number) with a public key.
  The device proves it possesses a copy of the
  matching private key by providing the decrypted
Authenticated Encryption with associated data(AEAD)

- The need for AE emerged from the observation that securely combining
   separate confidentiality and authentication block cipher operation modes
   could be error prone and difficult confirmed by a number of practical
   attacks introduced into production protocols and applications by
   incorrect implementation, or lack, of authentication (including SSL/TLS)
- A typical programming interface for AE mode implementation would provide the following functions:

     Input : plaintext, key, and optionally a header in plaintext that will not
             be encrypted, but will be covered by authenticity protection.
     Output: ciphertext and authentication tag (message authentication code).
     Input : ciphertext, key, authentication tag, and optionally a header.
     Output: plaintext, or an error if the authentication tag does not match
             the supplied ciphertext or header.

- Approaches to authenticated encryption:
  - Encrypt-then-MAC (EtM)
  - Encrypt-and-MAC (E-and-M)
  - MAC-then-Encrypt (MtE)
WebApp. Crypto
JWT intro
- (Very Good) Introduction to JWT!!!
- online JWT debugger to decode, verify and generate JWT,
  detailed list of libraries (Java, Python, C#, Rust,...)
  and other useful info.
JSON Web Token (JWT)
- URL-safe means of representing claims to be transferred between
  two parties.
  - Ussually encoded as:
    - payload of a JSON Web Signature (JWS) structure
    - plaintext of a JSON Web Encryption (JWE) structure.

JWTs can be signed with:
- symetric shared secrets (HMAC)
- asymetrict key pairs RSA/ECDSA.
(opt): JWTs can also be encrypted to provide secrecy between parties.

OºJWT structureº (JWS structure)
  xxxxx.yyyyy.zzzzz ← Base64URL encoded
  ^     ^     ^
  │  ┌──┘     │     ↖
  │  │  ┌─────┘      ☞ format more compact when compared to
  │  │  │              XML-based standards such as SAML.
  │  │ ºSIGNATUREº
  │  │ Base64URL (
  │  │   Sign (shared secret or private key,
  │  │         Base64URL encoded HEADER,
  │  │         Base64URL encoded PAYLOAD)
  │  │ )
  │  │ (Using signature algorithm of HEADER)
  │  │
  │  │
  │  - claims about an entity + additional data.
  │  - types of claims:
  │    -ºregistered : non mandatory but recommended for interoperability:
  │      º"iss"º(issuer)            º"sub"º(subject)
  │      º"exp"º(expiration time)   º"aud"º(audience)
  │      ...
  │    -ºpublicº    : Defined at will. To avoid collisions they should be defined
  │                   in the IANA JSON Web Token Registry or be defined as a URI
  │                   that contains a collision resistant namespace.
  │    -ºprivateº   : custom claims between parties
  typically consists of:
    "alg": "HS256", ← signing algorithm used (HMAC SHA256, RSA, ECDSA...)
    "typ": "JWT"    ← type of tokern (JWT)

ºJWT common ussage patterns:º
- user agent should send the JWT in the HTTP Authorization header
  using the Bearer schema like:
  Authorization: Bearer 
  (ºStateless authorizationº)

 º☞ By sending in the Authorization header, Cross-Origin Resource Sharingº
 º  (CORS) won't be an issue as it doesn't use cookies.º

- A typicalºOpenID Connect compliant web applicationºwill go through the
 º/oauth/authorizeºendpoint using the authorization code flow.
  When the authorization is granted, the authorization server returns an
  access token back to the  application.

- no secret information must be placed into the PAYLOAD unless the JWT is

- Don't store JWT inside localStorage since it's accessible by any script
  inside the page: an XSS attack can let an external attacker get access
  to the token.
- Don’t store JWT in local or session storage.
  If third-party scripts in the page  get compromised,
  they can access all your users' tokens.
- Stored JWT inside an httpOnly cookie, that’s only sent in
  HTTP requests to the server and it's never accessible
  (both for reading or writing) from JS running in the browser.

- Don't use JWT as Sessions since it's error prone.

Since JWT are signed, the receiver can be sure the client is really who it
thinks it is.

- Signing XML with XML Digital Signature is very complex and error prone
  when compared to the simplicity of signing JSON.

JSON Web Signature (JWS)
   JSON Web Signature (JWS) represents content secured with digital
   signatures or Message Authentication Codes (MACs) using JSON-based
   data structures.  Cryptographic algorithms and identifiers for use
   with this specification are described in the separate JSON Web
   Algorithms (JWA) specification and an IANA registry defined by that
   specification.  Related encryption capabilities are described in the
   separate JSON Web Encryption (JWE) specification.

JSON Web Encryption (JWE)
   JSON Web Encryption (JWE) represents encrypted content using
   JSON-based data structures.  Cryptographic algorithms and identifiers
   for use with this specification are described in the separate JSON
   Web Algorithms (JWA) specification and IANA registries defined by
   that specification.  Related digital signature and Message
   Authentication Code (MAC) capabilities are described in the separate
   JSON Web Signature (JWS) specification.

JSON Web Key (JWK)
   A JSON Web Key (JWK) is a JavaScript Object Notation (JSON) data
   structure that represents a cryptographic key.  This specification
   also defines a JWK Set JSON data structure that represents a set of
   JWKs.  Cryptographic algorithms and identifiers for use with this
   specification are described in the separate JSON Web Algorithms (JWA)
   specification and IANA registries established by that specification.

JSON Web Algorithms (JWA)
   This specification registers cryptographic algorithms and identifiers
   to be used with the JSON Web Signature (JWS), JSON Web Encryption
   (JWE), and JSON Web Key (JWK) specifications.  It defines several
   IANA registries for these identifiers.

· JOSE == JSON Object Signing and Encryption == JWS + JWE + JWK + JWA

 Following is a decoded JSON payload representing an example
 of JOSE protected header parameters as defined by the JWS JSON
 Serialization syntax.
   "name": "identityKey",← extension 1
   "alg" : "ES256K",     ← ECDSA using secp256k1 curve + SHA-256
   "typ" : "JOSE+JSON",  ← media type of complete JWS
   "b64" : false,        ← extension 2
                           true ⇒ payload=ASCII(BASE64URL(JWS Payload))
   "crit": ["b64"],      ← Critical extensions that must be accepted
   "jwk" :  {            ← pub.key used to sign JOSE header+JWS payload.
     "kty": "EC",          represented as JSON Web Key
     "use": "sig",       ← Intended user
     "crv": "secp256k1",
     "x"  : "0",         ← X-coordinate of corresponding pub key.
     "y"  : "0",         ← Y-coordinate of the corresponding pub key.

- @[]
  JS implementation of the JSON Object Signing and Encryption (JOSE)
  for current web browsers and node.js-based servers. This library implements
  (wherever possible) all algorithms, formats, and options in JWS, JWE, JWK, and
  JWA and uses native cryptographic support (WebCrypto API or node.js' "crypto"
  module) where feasible.
  Ex ussage:
  // Create Self Signed JSON token
  const ºprivKey01º= jose.JWK.asKey(
      "-----BEGIN PRIVATE KEY-----\n" +
      "-----END RSA PRIVATE KEY-----");
  const payload = { iss:"service1", aud:"service2" };
  constOºJWT01º=ºjose.JWT.signº(payload,ºprivKey01º, { expiresIn: "1 hours" });

ºUse casesº
- application that can read user data from another application
- application that enables other applications to access its user data

ºOAuth entitiesº
- Resource: (the User)  entity capable of granting access to a
  owner     protected resource.
            When the resource owner is a person, it
            is referred to as an end-user.
- Resource: ("API"server) server hosting the protected
  Server    resources, accepting and responding to
            protected resource token-attached-requests
- Client  : An application making protected resource requests
            on behalf of the resource owner and with its
            authorization. Client ca be a web app,
            server app, mobile app,...
- Authorization: Act of issuing access tokens to the client
                 after successfully authenticating server the
                 resource owner and obtaining authorization.
- access  : represents a permission granted to a client to
  token     access some protected resources.
- Scope   : ("permission") limit an application's access to a
            user's account. An App will request 1+ scopes.
            Scopes will next presented to owner (popup,...),
            finally issued access-tokens  will be limited
            to granted scopes.
            No particular scopes ared defined in
            OAuth spec(highly dependent on
            service's internal Architecture)
            Note: Auth.Ser. can limit further the set
                  of scopes (permission) granted to App

ºINITIAL (only-once) PRESETUP:º
  Register server app to OAuth2 Service provider.
  Write down Gº'' and 'client.secret'ºreturned from Service provider
  (Keycloak, Cloud Control Panel, Facebook,  ...).
   App Dev → OAuth Server : Register OAuth client
   App Dev ← OAuth Server : Gºclient.idº
   App Dev ← App Dev      : write in safe place

│ºRESOURCE OWNER CREDENTIALS GRANT (section 4.3)º   ││ºclient credentials grant (sect.4.4)º ││ºrefresh token grant (section1.5)º│
│  - "great user experience" for trusted first party││  - simplest oauth 2.0 grants         ││client → auth.Ser: post           │
│     clients (web and native device applications)  ││  - suitable for machine-to-machi.Auth││                   grant_type     │
│                                                   ││    where a specific user's permission││                   refresh_token  │
│user   → client  : request ...                     ││   to access data is not required.    ││                 gºclient_idº     │
│user   ← client  :  ask authorization credentials  ││client → auth.Ser: post               ││                   client_secret  │
│user   → client  :  authorization credentials      ││                   grant_type         ││                   scope          │
│client → auth.ser: POST                            ││                 gºclient_idº         ││client ← auth.Ser: json           │
│                grant_type with the value password ││                   client_secret      ││                   token_type     │
│              Gºclient_idº with the the client’s ID││                   scope              ││                   expires_in     │
│                client_secret with the client’s    ││client ← auth.Ser: json               ││                 Oºaccess_tokenº  │
│                secret scope with a space-delimited││                   token_type "bearer"││                   refresh_token  │
│                list of requested scope permissions││                   expires_in         │└──────────────────────────────────┘
│                username with the user’s username  ││                 Oºaccess_tokenº      │
│                password with the user’s password  │└──────────────────────────────────────┘
│client ← auth.ser: JSON object                     │
│                   token_type "Bearer"             │
│                   expires_in                      │
│                 Oºaccess_tokenº                   │
│                 Oºrefresh_tokenº                  │
┌─────────────────────────────────────────────────────────┐  ┌──────────────────────────────────────────────────────────────────────┐
│ºAUTHORIZATION CODE GRANT (Section 4.1)º                 │  │ -ºIMPLICIT GRANT (SECTION 4.2)º                                      │
│                                                         │  │   "WEB BROWSER*                                                      │
│ ºSTEP 1: Authenticating user and getting Auth. code     │  │   - similar to AUTHORIZATION CODE GRANT Sec. 4.1) with               │
│ user → client: req resource                             │  │     two distinct differences:                                        │
│ user ← client: redirect to Authorization Server         │  │     - Targeting user-agent-based clients (e.g. single page web apps) │
│                --------------------------------         │  │       that can't keep a client secret because all of the application │
│            URL query parameters in redirect URL         │  │       code and storage is easily accessible.                         │
│            - response_type with the value code          │  │     - instead of the Authorization Server returning an authorization │
│          Gº- client_idº    with the client identifier   │  │       code which is exchanged for an access token, the authorization │
│            - redirect_uri  (opt) defaults to            │  │       server returns an access token.                                │
│                            pre-registered URI           │  │                                                                      │
│            - scope         a space delimited scope-list │  │ user → client: request access                                        │
│            - state         (opt, but highly recommended)│  │ client → user: redirect to Auth.Server                               │
│                            Used to avoid "mixing"       │  │                -----------------------                               │
│                            different user's session on  │  │                URL req. param:                                       │
│                            callback                     │  │                response_type     with the value token                │
│ user → auth.ser: ...?response_type=..                   │  │              Gºclient_idº        with the client identifier          │
│                     ⅋client_id=..                       │  │                redirect_uri      Optional. pre-registered one │
│                     ⅋redirect_uri=..                    │  │                scope             a space delimited list of scopes    │
│                     ⅋scope=..⅋state=...                 │  │                state             (optional but highly recommended)   │
│ auth.ser → auth.ser: validate input                     │  │ user → auth.server: ...                                              │
│ user ← auth.ser: Login                                  │  │ auth.server → auth.server: checks...                                 │
│ user → auth.ser: "Credentials" proof                    │  │ user ← auth.server: request Credentials                              │
│              (can involve form with user/pass           │  │ user → auth.server: login with "credentials" proofs                  │
│               or complex multiFactor Auth/channel/steps)│  │                     and  approve the client                          │
│ auth.ser → auth.ser: Validate "credentials" proof       │  │ user ← auth.server: redirect to client                               │
│ user ← auth.ser: Redirect to reditect_uri               │  │                     -----------------------                          │
│                     ------------------------            │  │                     token_type    "Bearer"                           │
│                     URL reditect parameters:            │  │                     expires_in    TTL                                │
│             Oº- code  with the authorization codeº      │  │                   Oºaccess_tokenº the access token itself            │
│               - state (param.sent in original request)  │  │                     state         must be compared in client         │
│ user → client  :URL?code=....⅋state=...                 │  │                                   with the original value            │
│ client → client: check Init State = Receive state       │  │                     ^^^^^^^^^^^^                                     │
│                  (Avoid mixing different user sessions) │  │                     this grant does NOT return                       │
│                  Associate code to user's session       │  │                     refresh token because the browser                │
│                                                         │  │                     has no means of keeping it private               │
│ ºSTEP 2: Using code to get Access Tokenº                │  └──────────────────────────────────────────────────────────────────────┘
│ client → auth.ser: POST                                 │
│                    ────                                 │
│                    grant_type with the value of         │
│                    authorization_code                   │
│                  Gºclient_idº with the client identifier│
│                  Gºclient_secretº with the client secret│
│                    redirect_uri (original redirect URI) │
│                  Oºcodeº                                │
│ client ← auth.ser: JSON object                          │
│                token_type     usually "Bearer"          │
│                expires_in     access token TTL(Integer) │
│              Oºaccess_token   the access token itselfº  │
│                refresh_token  used refresh on expiration│
│                               time                      │
See also:
    OpenID is about verifying a person's identity.
    OAuth is about accessing a person's stuff.
    OpenID Connect does both.
OpenID Connect (2014) combines the features of OpenID 2.0, OpenID Attribute Exchange 1.0, and OAuth 2.0 in a single protocol.

Dex is an identity service that uses OpenID Connect
to drive authentication for other apps.
Dex acts as a portal to other identity providers through
"connectors." This lets dex defer authentication to
LDAP servers, SAML providers, or established identity
providers like GitHub, Google, and Active Directory.

 Clients write their authentication logic once to talk
to Dex, then Dex handles the protocols for a given backend.
OpenID vs OAuth2 vs SAML

- single sign-on (SSO) allows a user to enter sign once
  and "enter" multiple applications or web-sites.
  This means that some sort of "authentication token"
  must be provided to the user on first sign for later

- developers of the SSO applications don't have to
  store or request for passwords. Instead, they can
 ºaccept proof of identity or authorizationº
 ºfrom a trusted sourceº

- OpenID, OAuth2 and SAML are different security protocols
  for single sign-on

  the relying party.
- open standard for authentication
- As of March 2016, there are over a billion
  OpenID-enabled accounts on the internet.
- Google, WordPress, Yahoo, PayPal use OpenId
  to authenticate users.

user → id_provider01: request OpenID account
user ← id_provider01: OpenID account
                      technically it's a URL

user → web_site login_screen: Select "sign with id_provider01"
       (relying party)
web_site login_screen → id_provider01: request association handle
web_site login_screen ← id_provider01: association handle
user ← web_site login_screen: redirect to id_provider01 login page
user → id_provider01: enter OpenID account + credentials (pass,...)
user ← id_provider01: auth.token + url_redirect o web_site
                      signed claim statying that id_provider01
                      believes user is actually user
user → web_site url : auth.token
web_site url → web_site url : Check auth.token is signed by trusted
web_site url → web_site url : Create session for user
user ←→ web_site url : --- app session ---

- 2014: Latest version (OpenID Connect) combines:
  - OpenID authentication  (user is who he claims to be)
  - OAuth2 authorization   (user is authorized a set of actions)

- Confusingly, OAuth2 is also the basis for OpenID Connect -2014-)
- Confusingly, authorization is also considered some time a form
 of pseudo-authentication and OAuth2 is claimed to be an
 authentication standard. (An authorization signed token is a
 claim that the user is believed to be himself for the act of
 executing an action or accesing some resource).

- open standard for authorization.
- OAuth2 provides secure delegated access:
  - application clients will use temporal tokens issued by
    the identity-provider to the user to access resources
    on another resource-server on behalf of the user.

- 2001: oldest standard of the three
- 2005: latest update.
- stands for Security Assertion Markup Language.
- provides authentication + authorization.
- SAML defines:
  - principal (end user).
  - service provider (application web site)
  - identity provider:  server holding principal's ids + credentials.

user           → ser_rovider01: request service (action on a webapp)
ser_provider01 → id_provider  : XML message
                                required info
                                who_is_asking (ser_provider01)
id_provider    → response_url : SAML signed response assertion
                               (similar to a token in OpenID/OAuth2).
                                The assertion can contain statements
                                about authentication, authorization,
                                and/or attributes (emails, phones,...).

SAML 2.0 defines:
- assertions:
- protocols : assertion requests and responses)
- bindings  : how requests/responses happen between the service provider and identity provider
              using communication methods like HTTP POST
- profile   : allowed combinations of (assertions, protocols, bindings)
              for various use cases, like SSO.

                    OAuth2             OpenId              SAML

Token format        JSON or SAML2      JSON                XML

Authorization?      Yes                No                  Yes

Authentication?     Pseudo-auth        Yes                 Yes

Year created        2005               2006                2001

Current version     OAuth2             OpenID              SAML 2.0

Transport           HTTP               HTTP                - HTTP Redirect
                                       GET/POST              (GET) binding
                                                           - SAML SOAP
                                                           - HTTP POST
                                                           - "others"

SECURITY RISKS      Phishing[1]        Phishing[1]         XML Signature
                                                           Wrapping to
                                                           any user

Best suited for     - API              - consumer apps     enterprise
                      authorization      Single sign-on    Single sign-on
                                         delegating SSO
                                         to Google,...
TLS protocol
External Links
- Wikipedia
- Mozilla SSL config generator
- Mozilla Server Side TLS
- SSL Server Test

(ITU_T standard)
Can be seen as an accepted (== signed by CA) public-key
plus metadata about such public-key.
The CA signature claims that the public-key and metadata
are valid for the CA.

The current content will be:
- ºpublic key certificatesº
- ºidentityº: hostname + organization/individual
- ºcertificate revocation listsº: certificates are no longer
- ºcertification path validation algorithmº allowing for
  certificates to be signed by intermediate CA certificates, which are in
  turn signed by other certificates, eventually reaching a trust anchor.
- Used amongst others by Internet protocols like TLS/SSL
- X.509 v3:
  Serial Number
  Signature algorithm
  Issuer name
  Validity period
  Subject name
  Subject PK Info
  Issuer ID#
  Subject ID#
  CA Signature
- "Extended attributes" (Used by different services)
ºView x509 contents:º
$ openssl x509 -text -in myCert.pem
                                (P)rivacy (E)nhanced (M)ail
│ºExternal Refsº
│@[] X.509 PKI
│- The Most Dangerous Code in the World: Validating SSL Certs ...:

│ºCommon optsº
│-nodes: flag: ºDO NOTº pass-phrase-encrypt Pub.Key
│-noout: prevents output of encoded version of request
│-text : Show human readable output (vs hex formated binary))

│ºGlobal Flowº                             │ºuseful ENV.VAR (DOMAIN/SUBJ)º
│admin→admin: Create Private Key           │$ export DOMAIN=""
│admin→admin: Create CSR                   │$ export SUBJ=""
│alt                                       │$ export SUBJ="${SUBJ}/C=ES"
│  admin→admin: Create self-certificate    │$ export SUBJ="${SUBJ}/ST=Aragon"
│else:                                     │$ export SUBJ="${SUBJ}/L=Zaragoza"
│  admin→CA   : CSR                        │$ export SUBJ="${SUBJ}/O=MyOrganization"
│  CA→CA      : Create certificate         │$ export SUBJ="${SUBJ}/CN=${DOMAIN}"
│  CA→amdin   : certificate                │$ export NUM_OF_DAYS="999"
│Cert.Sign.Requestº                        │ºCreating a CSR*
│ºCSRº                                     │$ openssl req \
│CSR :=                                    │  º-newº\
│    PUBLIC KEY                            │   -nodes
│  + Distinguised Name (DN) :=             │   -newkey rsa:2048 \
│       + Common Name (CN)                 │   -keyout ${DOMAIN}.key \
│         (SHOULD be the exact             │   -out ${DOMAIN}.csr -subj "${SUBJ}"
│          Fully Qualified Dom Name(FQDN)  │
│          of the host)                    │(replace -newkey rsa:.... -keyout... by
│       + "additional info                 │            -key ${DOMAIN}.key to use
│          about organization"             │            already existing private key)

│ºManaging Private Keysº                   │ºdump x509 infoº
│ºCREATE A PRIVATE KEY:º                   │$ openssl x509 -in myCert.pem -text
│$ openssl \                               │$ openssl x509 -in myCert.crt -text -inform DER
│    genrsa -des3 \                                                   ^                 ^
│    -out ${DOMAIN}.key 2048                                crt/cer admits PEM and DER binary
│(Enter password when prompted)                             encoding. For binary the option
│                                                           "-inform DER" must be passed or
│                                                           the command will fail.
│$ openssl rsaº-checkº-in ${DOMAIN}.key
│ºVerify private key matches certificate and CSRº
│ (If the output of each of the next command is identical there is an
│  extremely high probability that the private key, certificate,
│  and CSR are related)
│  $ openssl rsa  -noout -modulus -in ${DOMAIN}.key | openssl md5
│  $ openssl x509 -noout -modulus -in ${DOMAIN}.crt | openssl md5
│  $ openssl req  -noout -modulus -in ${DOMAIN}.csr | openssl md5
│ºEncrypt/Decrypt private keyº
│$ openssl rsa -des3 -in unencrypted.key -out encrypted.key
│$ openssl rsa       -in encrypted.key   -out decrypted.key

│ºworking on Chrome/Java/...º
│- chrome deprecates subject cn matching]
│- Fixing Fixing Chrome 58+ [missing_subjectAltName] with openssl&S.S.certs
│- getting-chrome-to-accept-self-signed-localhost-certificate
│ |#!/usr/bin/env bash
│ |openssl genrsa -out rootCA.key 2048
│ |openssl req -x509 -nodes \
│ |    -days $NUM_OF_DAYS \
│ |    -key rootCA.key -sha256 \
│ |    -out rootCA.pem
│ |    -new
│      ^^^^
│      replace with -in $DOMAIN.csr to reuse crt

│ |#!/usr/bin/env bash
│ |
│ |if [ -z "$1" ]; then
│ |  echo "Ussage: $0"
│ |  echo "           ^^^^^^^^^^^^"
│ |  echo "    # alt1     wildcard"
│ |  echo "        $0"
│ |  echo "           ^^^^^^^^^^^^^^^^"
│ |  echo "    # alt2 non-wildcard"
│ |  exit 1;
│ |fi
│ |if [ ! -f rootCA.pem ]; then echo 'no rootCA.pem detected. Please, run first, and try again!' ; exit 1; fi
│ |if [ ! -f v3.ext     ]; then echo 'Please download the "v3.ext" file and try again!' ;  exit; fi
│ |
│ |if [ -f $DOMAIN.key ]; then KEY_OPT="-key" else KEY_OPT="-keyout" fi #  ← Create new Priv.Key || reuse existing one
│ |
│ |cat ˂˂ EOF ˃ /tmp/__v3.ext
│ |authorityKeyIdentifier=keyid,issuer
│ |basicConstraints=CA:FALSE
│ |keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
│ |subjectAltName = @alt_names
│ |
│ |[alt_names]
│ |EOF
│ |
│ |openssl req -new -newkey rsa:2048 \
│ |   -sha256 -nodes $KEY_OPT $DOMAIN.key \
│ |   -subj "$SUBJECT" -out $DOMAIN.csr
│ |openssl x509 -req -in $DOMAIN.csr \
│ |   -CA rootCA.pem -CAkey rootCA.key \
│ |   -CAcreateserial -out $DOMAIN.crt \
│ |   -days $NUM_OF_DAYS -sha256 \
│ |   -extfile /tmp/__v3.ext
│$ ./        # ← STEP 01: create root Auth cert
│$ ./ \ # ← STEP 02
│                          #   Alt 1
│       #   Alt 2
│Note: You will also new to import the new cert. authority.
│For example on Mac:
│    Open Keychain Access
│    Choose "System" in the "Keychains" list
│    Choose "Certificates" in the "Category" list
│    Choose "File | Import Items..."
│    Browse to the file created above, "rootCA.pem", select it, and click "Open"

│ºConverting Formatsº
│- X.509 DER ENCODING: Binary       encoding for X.509v3 certificates
│                                   DER stands for ASN.1 (D)istinguished (E)ncoding (R)ules
│                                   (vs BER-Basic, CER - Canonical)
│- X.509 PEM ENCODING: Base64-ASCII encoding for X.509v3 certificates,
│                                   prefixed with a "—– BEGIN ..." line
│                     ºPEMºis an acronym forº(P)rivacy (E)nhanced (M)ailº
│- NOTE common X.509 file extensions include:
│  - .CRT: certificates encoded as binary der or as ascii pem.
│  - .CER: certificates . Mostly similar to .CRT, recognized
│          by some Microsoft products (IE, MS cryptoAPI commands, ...)
│  - .KEY: used for private PKCS#8 keys (and its corresponding public key)
│          encoded as binary DER or as ASCII PEM.
│- PKCS#7  Standard: Cryptographic Message Syntax used to sign and/or encrypt messages under PKI
│                    - ASCII files, also known as P7B,
│                      which can contain (non-secret) certificates
│                      and CA certificates.
│- PKCS#12 Standard: file format commonly used for (private)keystores, protected with a password-based
│                    symmetric key. Used by:
│                    - Java key store
│                    - client auth. certs in Firefox, Apache Tomcat
│                    - Files are also known as PFX files
│ (OpenSSL defaults to X.509 PEM format
│$ openssl x509 -inform pem -in ${DOMAIN}.crt -outform der -out ${DOMAIN}.der # PEM   → DER
│$ openssl x509 -inform der -in ${DOMAIN}.der -outform pem -out ${DOMAIN}.crt # DER   → PEM
│# PEM   → PKCS7
│$ openssl crl2pkcs7 -nocrl -certfile ${DOMAIN}.crt -certfile ca-chain.crt -out ${DOMAIN}.p7b
│# PKCS7 → PEM
│$ openssl pkcs7 -in ${DOMAIN}.p7b -print_certs -out ${DOMAIN}.crt
│# PEM → PKCS12
│$ openssl pkcs12 -inkey ${DOMAIN}.key \
│   -in ${DOMAIN}.crt -export -out ${DOMAIN}.pfx
│# PKCS12 → PEM
│$ openssl pkcs12 -in ${DOMAIN}.pfx -nodes -out ${DOMAIN}.combined.crt
│# x509 → PEM
│$ openssl x509 -in ${DOMAIN}.cer -outform PEM -out ${DOMAIN}.pem

│- Fingerprints are short sequences of bytes used to identify a longer public key,
│  applying a cryptographic hash function to the public key
│- Are used as "ids" to the longer public keys
│- To generate a fingerprint from a TLS certificate, run:
│$ openssl x509 -in ${DOMAIN}.crt -noout -fingerprint -sha256
│(output will be similar to
│ fa:23:a4:48:............:56

│ºfetch first-in-chain web cert.,º              │ºlist openssl version/buildº
│ºthen add to Java.KeyStore:º                   │$ openssl version -a
│$ openssl s_client \
│   -connect \
│   -showcerts ˂/dev/null 2˃/dev/null | \       │ºView and Verify CSRº
│  openssl x509 \                               │$ openssl req \
│    -outform PEM ˃ infura-morden.pem           │  -text  \  # "view"
│$ ($JAVA_HOME/Contents/Home/jre/bin/)keytool \ │  -verify \ # "verify"
│    -import -noprompt -trustcacerts \          │  -noout \
│    -alias -f                │-in ${DOMAIN}.csr

│*Verify that cert. was
│ signed by a given CA:
│$ openssl verify -verbose
│    \ -CAFile ca.crt ${DOMAIN}.crt

│ºCertificate revocation listsº
│RºWARN:º Some companies/applications have deprecated CRLs and are
│         instead using the ºOnline Certificate Status Protocol (OCSP)º
│- A CRL provides a list of certificates that have been revoked.other TLS projects
│STEP 1: Prepare CLR config file
│$ vim .../intermediate/openssl.cnf
│ [ CA_default ]
│ ...
│ default_crl_days = 30 ← STEP 2 must be periodically executed
│ ...                     this delay
│ [ server_cert ]
│ # ... snipped ...
│*crlDistributionPoints = URI:
│ ^^^^^^^^^^^^^^^^^^^^^
│ See man page for more crl options
│STEP 2: Create the CLR
│(Repeat perioadically according to default_crl_days in config)
│$ cd ~/ca
│$ openssl ca \
│  -config intermediate/openssl.cnf \
│ º-gencrlº \
│  -out intermediate/crl/intermediate.crl.pem
│STEP 3: Verify output of STEP 2:
│$ openssl crl \
│  -in intermediate/crl/intermediate.crl.pem \
│  -noout -text
│→ ... No Revoked Certificates
│ (No certificates have been revoked yet)
│STEP 4: make intermediate.crl.pem accessible through
│        the HTTP URL  indicated in STEP 1
│NOTE: For servers authenticating clients through
│      X.509 certs, copy the generated crl file
│      to a path indicated by the server config
│      ('SSLCARevocationPath' in Apache HTTP,
│      'crl-verify' in OpenVPN,...)
│$ cd ~/ca
│$ openssl ca -config intermediate/openssl.cnf \
│ º-revokeº \
│  intermediate/certs/
│For a given X.509 certificate the CRL distribution
│points are visible in the certificate X509v3 details.
│# openssl x509 -in ${DOMAIN}.cert.pem -noout -text
│→ ...
│→   X509v3 CRL Distribution Points:
│→       Full Name:
│→         URI:
│→ ...

Related projects:
Auto SSL

Caddy HTTPS server - Caddy simplifies your infrastructure. It takes care of TLS certificate renewals, OCSP stapling, static file serving, reverse proxying, Kubernetes ingress, and more. - Its modular architecture means you can do more with a single, static binary that compiles for any platform. - Caddy runs great in containers because it has no dependencies—not even libc. Run Caddy practically anywhere. Automated SSL certificates monitoring, renewal and deployment from blueprint. module for Python 2.7+/3.5+ that can be used to to automate SSL certificate monitoring, renewal and deployment. This module can be customized with plugins mechanism to support any type of: - server: where the certificate is deployed, can be 1 or more server, potentially of different types - storage: where to store your artifacts (private key, public certificate, ...) - tracking mechanism: how to track renewal process (ticket creation) - renewal method: how to get a new certificate (local CA, ACME protocol, ....)
AutoSSL in OpenLiberty - Red Hat Runtimes now supports the new Open Liberty Java runtime. Open Liberty features support for the Automatic Certificate Management Environment (ACME) protocol, which automates the process of obtaining a certificate signed by a certificate authority (CA). The Open Liberty release also includes many bug fixes.
Portecle: Cert+Keystore GUI
Portecle is a user friendly GUI application for creating, managing and
examining keystores, keys, certificates, certificate requests, certificate
revocation lists and more.

The scenario for using such a tool is if a server system lacks the capability
of generating a CSR keypair on its own. Another Senario would be if large
networks of multiple server types, data centers and such are faced with a CSR
keypair on one system environment and the tireless key store conversions that
are required to import a keypair into a different server environment, which can
be very time consuming and frustrating.

Portecle eliminates the need for a server to create a CSR keypair. It acts as
keypair CSR generator where you can generate a single key pair, create a CSR,
import a Signing SSL certificate, convert and save different format types of
this key pair, and migrate them into the various systems required.

Portecle can be used to, for example:
- Create, load, save, and convert keystores.
- Generate DSA and RSA key pair entries with self-signed X.509 certificates.
- Import X.509 certificate files as trusted certificates.
- Import key pairs from PKCS #12.
- Clone and change the password of key pair entries and keystores.
- View the details of certificates contained within keystore entries,
  certificate files, and SSL/TLS connections.
- Export keystore entries in a variety of formats.
- Generate and view certification requests (CSRs).
- Import Certificate Authority (CA) replies.
- Change the password of key pair entries and keystores.
- Delete, clone, and rename keystore entries.
- View the details of certificate revocation list (CRL) files.
RFC 8555: PKI using X.509
Published on 2015-05-22 according to
Public Key Infrastructure using X.509 (PKIX) certificates are used
for a number of purposes, the most significant of which is the
authentication of domain names.  Thus, certification authorities
(CAs) in the Web PKI are trusted to verify that an applicant for a
certificate legitimately represents the domain name(s) in the
certificate.  As of this writing, this verification is done through a
collection of ad hoc mechanisms.  This document describes a protocol
that a CA and an applicant can use to automate the process of
verification and certificate issuance.  The protocol also provides
facilities for other certificate management functions, such as
certificate revocation.
- ACME stands for Automatic Certificate Management Environment (ACME) protocol.
- Public Key Infrastructure using X.509 (PKIX) certificates are used
  for a number of purposes, the most significant of which is the
  authentication of domain names.  Thus, certification authorities
  (CAs) in the Web PKI are trusted to verify that an applicant for a
  certificate legitimately represents the domain name(s) in the
  certificate.  As of this writing, this verification is done through a
  collection of ad hoc mechanisms.  This document describes a protocol
  that a CA and an applicant can use to automate the process of
  verification and certificate issuance.  The protocol also provides
  facilities for other certificate management functions, such as
  certificate revocation.
Certs Transparency

Trillian is an implementation of the concepts described in the
VerifiableDataStructures.pdf white paper, which in turn is an extension and
generalisation of the ideas which underpines @[]

- G.C.T. project fixes several structural flaws in the SSL certificate system
matching- open framework for monitoring and auditing SSL certificates in nearly real time.
  detecting SSL certificates that have been mistakenly issued by a certificate authority
  or maliciously acquired from an otherwise unimpeachable certificate authority.
  It also makes it possible to identify certificate authorities that have gone rogue
rl.pem*  and are maliciously issuing certificates.
-ºCertificate LOGSº:simple network services that maintain cryptographically
assured, publicly auditable, append-only records of certificates. Anyone can
submit certificates to a log, although certificate authorities will likely be
the foremost submitters
-ºMonitorsº are publicly run servers that periodically contact all of the log
servers and watch for suspicious certificates. For example, monitors can tell
if an illegitimate or unauthorized certificate has been issued for a domain,
and they can watch for certificates that have unusual certificate extensions
or strange permissions, such as certificates that have CA capabilities.

-ºAuditorsº: lightweight components performing two functions:
- verify that logs are behaving correctly and are cryptographically
consistent. If a log is not behaving properly, then the log will need to explain
itself or risk being shut down.
- verify that a particular certificate appears in a log. This is a particularly
important auditing function because the Certificate Transparency framework
requires that all SSL certificates be registered in a log. If a certificate has
not been registered in a log, it’s a sign that the certificate is suspect, and
TLS clients may refuse to connect to sites that have suspect certificates.


Complementary to TLS:
SASL is used for authentication and TLS for traffic encryption.

A SASL mechanism implements a series of challenges and responses.
Defined SASL mechanisms[1] include:
  - EXTERNAL, where authentication is implicit in the context (e.g.,
    for protocols already using IPsec or TLS)
  - ANONYMOUS, for unauthenticated guest access
  - PLAIN, a simple cleartext password mechanism, defined in RFC 4616
  - OTP, a one-time password mechanism. Obsoletes the SKEY mechanism.
  - SKEY, an S/KEY mechanism.
  - CRAM-MD5, a simple challenge-response scheme based on HMAC-MD5.
  - DIGEST-MD5 (historic[2]), partially HTTP Digest compatible
    challenge-response scheme based upon MD5. DIGEST-MD5 offered a data
    security layer.
  - SCRAM (RFC 5802), modern challenge-response scheme based
    mechanism with channel binding support
  - NTLM, an NT LAN Manager authentication mechanism
  - GS2- family of mechanisms supports arbitrary GSS-API mechanisms
    in SASL.[3] It is now standardized as RFC 5801.
  - GSSAPI, for Kerberos V5 authentication via the GSSAPI. GSSAPI
    offers a data-security layer.
  - BROWSERID-AES128, for Mozilla Persona authentication[4]
  - EAP-AES128, for GSS EAP authentication[5]
  - GateKeeper (& GateKeeperPassport), a challenge-response mechanism
    developed by Microsoft for MSN Chat
  - OAUTHBEARER, OAuth 2.0 bearer tokens (RFC 6750), communicated
    through TLS[6]
  - OAUTH10A, OAuth 1.0a message-authentication-code tokens (RFC
    5849, Section 3.4.2)[6]

As of 2012 protocols currently supporting SASL include:
- Application Configuration Access Protocol
- Advanced Message Queuing Protocol
- Blocks Extensible Exchange Protocol
- Internet Message Access Protocol
- Internet Message Support Protocol
- Internet Relay Chat (with IRCX or the IRCv3 SASL extension)
- Lightweight Directory Access Protocol
- libvirt
- ManageSieve (RFC 5804)
- memcached
- Post Office Protocol
- Remote framebuffer protocol[8] used by VNC
- Simple Mail Transfer Protocol
- Subversion svn protocol
- Extensible Messaging and Presence Protocol
Cert.Authorities (CAs)
Let's Encrypt
- free, automated, and open Certificate Authority.

- Certbot is a free, open source software tool for automatically using Let’s
  Encrypt certificates on manually-administrated websites to enable HTTPS.

- Certbot might be right for you if you:
  - have comfort with the command line
  - have an HTTP website that’s already online
  - and administer your website via a dedicated/cloud server
  - which you can access via SSH
  - have the ability to sudo

- Certbot is part of EFF’s larger effort to encrypt the entire Internet.
  Websites need to use HTTPS to secure the web. Along with HTTPS Everywhere,
  Certbot aims to build a network that is more structurally private, safe, and
  protected against censorship.
- Mission Statement: create a Non-Profit Certificate Authority;
                     alternative to the commercial CAs.
-  Simple scripts around OpenSSL to create a local certificat authority
TLS Related

- Internet protocol used for obtaining the revocation status of an X.509 digital certificate.
- Alternative to Certificate Revocation Lists to addressg problems associated with
  using CRLs in a public key infrastructure (PKI).
- Messages are encoded in ASN.1

- Architecture is "request/response" message based.
- Supported by different web browsers

ºComparison to CRLsº
- OCSP response contains less data than a typical CRL file
- easier to parse by end client-side libraries
- OCSP discloses to the responder that """a particular
  network host used a particular certificate at a particular time"""
- OCSP lookups can be performed on transaction or authorization level,
  but CRLs must be updated at intervals.

ºBasic PKI implementationº
participant: Alice  with certificate issued by CA Carol
participant: Bob    with certificate issued by CA Carol
Carol      : CA

Alice wishes to perform a transaction with Bob.
Alice → Bob: Alice pub.key Certificate
Bob   → Bob:(concerned that Alice's priv.key is compromised)
             creates an 'OCSP-request'
Bob   → Carol: OCSP-request
Carol → Carol: reads certificate serial number.
               Search if serial number is in revocation ddbb
Carol → Bob  : Signed OCSP-response with
               'good'|'revoked'|'unknown'|'error code'
               key signing OCSP-response must be the
               original key signing the cert. originally
               or another cert. issued by the original CA
               that is marked with a certain extension to
               flag it as OCSP signing authority.

Bob   → Bob  : verifies Carol's signed response.
               (it's supposed that Bob has stored Carol's
                pub.key sometime before this transaction)

Bob   → Alice: ...

ºProtocol detailsº
- OCSP request format supports additional extensions.
- OCSP can be vulnerable to replay attacks,[5] where a signed,
  'good' response is captured by a malicious intermediary and
  replayed to the client at a later date after the subject
  certificate may have been revoked.  A nonce can be included
  to avoid it.
  - Because of high load, most OCSP responders do not use the
    nonce extension to create a different response for each
    request, instead using presigned responses with a validity
    period of multiple days.
   ºThus, the replay attack is a major threat to validation systemsº

- OCSP can support more than one level of CA chaining/forwarding
  initial OCSP-requests to by delegated path validation (DPV) servers.

(See Criticisms in original wikipedia article)

Supported by
Internet Explorer, Mozilla Firefox 3+, Safari-macOS.
RºGoogle Chrome disabled OCSP checks by default in 2012º
Rºciting latency and privacy issues and instead uses theirº
Rºown update mechanism to retrieved revoked certificatesº
XML Signature

- also called XMLDSig, XML-DSig, XML-Sig
- XML syntax for digital signatures
- W3C recommendation
- it has much in common with PKCS#7 but is more extensible
- used by various XML related technologies like SOAP or SAML

- typically used toto sign XML documents,
 ºbut anything that is accessible via a URL can be signedº

- An XML signature used to sign a resource outside its containing
  XML document is called a detached signature;
- If used to sign some part of its containing document, it is
  called an enveloped signature;
- if it contains the signed data within itself it is called an
  enveloping signature.

- Rºcreation of XML Signatures is substantially more complexº
  Rºthan the creation of an ordinary digital signature becauseº
  Rºa given XML Document may have more than one legal serializedº
  - XML canonicalization transform is employed to alleviated some of
    those problems

(See detailed description in Wikipedia source)
Best Patterns
Common protocol issues
- ciphertext that aren't secured with a MAC
- message that don't include a time-stamp or counter
- protocols that don't use PK for authenticity
- Reuse of Nonces of IVs
- ... many more
# Dont's!!#
- Don't Implement your own algorithms
- Don't Use hard-coded keys, use a Vault service.
  Don't use a Vault when you can use wallet. (that will use an
  internal vault and never expose secrets outside)
- Never use ECB mode. Prefer CBC, better yet CTR or
  - RºWARN: ECB is the default mode in JAVAº.
  - Ex.:ºAES is secureº, but Rºpairing it with ECB is insecureº.
  WARN: even GCM has its flaws; encrypting too much data
        with the same key or make a mistake with the IV/nonce,
        can leak key material.  Other modes are free in to
        those leaks.
- Don't use small public key sizes. At least 2048
- Elliptic curve preferable: p-256 or X25519
- Don't use the same private key for encrypting and signing
- Don't reuse the same nonce twice -it will no be a nonce-
- Don’t use old/broken stuff. Non-exhaustive list includes:
  -RºDES, MD4, MD5, SHA1, RC4, AES-ECBº
  -BºRSA is old, but not brokenº,  but prefer ECC-mode.
kerberos+ldap "=" AD
Kerberos protocol
- computer-network protocol designed to
 ºprovide strong client/server mutual authenticationº

- ºbuilt on symmetric key cryptographyº and
  ºmay (optionally) use public-key cryptographyº
  ºduring certain phases of authenticationº
- ºrequires a trusted third partyº
- ºworks on the basis of ticketsº
- allow nodes communicating over a non-secure network
  to prove their identity to one another in a secure manner,
  protecting against eavesdropping and replay attacks.

ºHistory and developmentº
- 19?? MIT 1st Kerberos version
  based on the earlier Needham–Schroeder symmetric key protocol.
- Versions 1-3 were only MIT internals.

- Late 1980s: version 4 (by Steve Miller and Clifford Neuman)

- 1993: Version 5, becomes also RFC 1510

- 2000: Default authentication method in Windows 2000
        - RFC 3244 documents Microsoft additions to the standard
          suite of protocols:
        "Microsoft Windows 2000 Ker. Change and Set Password Proto."
        RFC 4757 documents Microsoft's use of the RC4 cipher.
        Kerberos is used as preferred authentication method:
       ºIn general, joining a client to a Windows domain means   º
       ºenabling Kerberos as default protocol for authenticationsº
       ºfrom that client to services in the Windows domain and   º
       ºall domains with trust relationships to that domain.     º
       (fallback to NTLM ifeither client or server are not joined to a domain*

- 2005: RFC 4120 makes (1993) RFC 1510 obsolet. Updates by IETF included:
  - Encryption and Checksum Specifications (RFC 3961)
  - AES (RFC 3962)
  - new edition of the Kerberos V5 spec
    "The Kerberos Network Authentication Service (V5)" (RFC 4120).
  - new edition of
    "The Kerberos V5 Generic Security Service API (GSS-API) Mechanism: Version 2." (RFC 4121).

- 2???: MIT implementation freely available (BSD license)

- 2007: MIT formed the Kerberos Consortium to foster continued development.
        Founding sponsors include Oracle, Apple, Google, Microsoft, Centrify Corporation, TeamF1,
        Royal Institute of Technology in Sweden, Stanford University, MIT, CyberSafe.

ºProtocol Descriptionº

participant client
participant Service Server          as SS
participant Auth.Server             as AS
participant Key.Distribution.Center as KDC
participant Ticket.Gathering.System as TGS
            Ussually KDC and TGS share the
            same host

PRE-SETUP: Register SPN at TGS with a Service Principal Name (SPN01)
SS → TGS: Register SPN01

LOGIN-FASE: Gathering new TGT (ticket-granting ticket)
  client →  client: username01, password01
  client →  client: alt 1: key01 = chiper(secret_key, password01)
                    alt 2: key01 = hash  (password01)
  client →  AS: username01
  AS     → KDC: username01
  KDC    → KDC: issues new TGT01
                           - time-stamp
                           - expiration-time

  KDC    → KDC: encryptedTGT01 = sym_cipher(secret_key, TGT01)
  KDC    → client: encryptedTGT01 (usually at user logon)

STEP 2: Communicating with other nodes ("principal")
  client → TGS: TGT01 + SPN01
                        SPN01 registered in PRE-SETUP.
  TGS    → TGS: verify TGT01
                verify client is allowed access to TG01
  TGS    → client: Session Ticket st01 + Session Keys
  client → SS: session ticket st01 + sess.keys + service request

ºDrawbacks and limitationsº
- Kerberos requires user accounts, user clients
  and the services on the server to all have a
  trusted relationship to the Kerberos token server
  All must be in the same Kerberos domain or in domains
  that have a trust relationship between each other.
  - creating staged environments (e.g. separate domains for
    test, pre-production, production) is difficult.

ºKerberos delegationº
- Kerberos delegation is used in multi-tier application/service situations:
-  A common scenario would be a web server application making calls to
   a database running on another server.
   -  The first tier is the user who browses to the web site’s URL.
   -  The second tier is the web site.
   -  The third or data tier would be the database.
  ºDelegation allows the database to know who is actually accessing its dataº

  Non-Kerberos Security Setup:
    webserver_admin → database1_admin : request database  access for "WebServerAcct"
    database1_admin → database1_admin : grant "sufficient" access to "Database1Acct"
    webapp developers and/or admins determine who can access the web application
    and by extension the data in the back end.
    Rº(it may be unacceptable to the database admins as they cannot control whoº
    Rº ultimately has access to the data)                                      º

  Kerberos delegation Setup:
    - grant "WebServerAcct" permission to delegate to the "Database1Acct".
      When a user accesses the web site they authenticate with Windows Integrated Authentication:
      user → webserver: request + user-kerberos-ticket1
                                  contains a list of the user's
                                  AD group memberships.

      webserver → webserver: check that user-kerberos-ticket1 is in Database group
      webserver → AD controller: (delegation configure)
                                 request a Kerberos ticket to the database
                                 impersonating the user rather than "WebServerAcct"
      webserver → Database1: request + user-kerberos-ticket2
      Database1 → Database1: check that user-kerberos-ticket1 is allowed

- application protocol for accessing and maintaining distributed
  directory information services over an Internet Protocol (IP) network.

- Directory services roles:
  - share information about users and services throughout the network,
    like mails, phones, user/passwords, ...

- 1980s: Telco companies develop the concept of directory services
         culminating in the comprehensive X.500 specification
         by the International Telecommunication Union (ITU) in the 1980s.

- 1993 : First version created as a subset of X.500 for TCP/IP
         While the X.500 was "heavy" in network bandwith, LDAP was
         "light", better suited for TCP/IP at that time.

- 1997: LDAPv3
        - added support for extensibility
        - integrates Simple Authentication and Security Layer

- 2006: Latest version (RFC 4511)
        road map to the technical specifications is provided by [RFC4510]
        - The Protocol [RFC4511]
        - Directory Information Models [RFC4512]
        - Authentication Methods and Security Mechanisms [RFC4513]
        - Uniform Resource Locator [RFC4516]
        - ...

ºProtocol overviewº
- ASN.1 binary BER encoded (Basic Encoding Rules)

participant Directory_System_Agent (LDAP_server) as DSA
client → DSA: connect
client → DSA: operation request  ← With some exceptions, client does
client ← DSA: operation response   not need to wait for a response
              ^^^^^^^^^            before sending the next request.
                │                  Server may respond in any order.
 operation can be:
 - StartTLS    :
 - Bind        : authenticate and specify LDAP protocol version
 - Search      : search for and/or retrieve directory entries
 - Compare     : test if a named entry contains a given attribute value
 - Add    entry:
 - Delete entry:
 - Modify entry:
 - Modify DN   : move/rename an (D)istinguished (N)ame
 - Abandon     : abort a previous request
 - Extended Op : generic operation used to define other operations
 - Unbind      : close the connection (not the inverse of Bind)

ºDirectory structureº
- (Follows X.500 1993 model)
- attribute = [ name, value+]
- attributes are defined in a schema
- entry == [parent DN, Relative DN  , [attribute1, attribute2,...] ]
                       ─────────────   ──────────  ──────────
                       att name: cn    name        name
                       att value:...   val1        val1,val2
             Distinguished Name (DN)

      Example entry in LDIF format
      (LDAP Data Interchange Format)
   ┌─→dn: cn=John Doe,dc=example,dc=com  ← /com/example/John Doe
   │      └───────────────────────────┘    └──────────┘ └──────┘
   │        Distinguished Name (DN)         Parent DN     RDN
   │  cn: John Doe                         └───────────────────┘
   │  givenName: John                              DN
   │  sn: Doe
   │  telephoneNumber: +1 888 555 6789               ┌────  Each entry must have an objectClass
   │  telephoneNumber: +1 888 555 1232               │      attribute, containing named classes
   │  mail:                         │      defined in the schema.
   │  manager: cn=Barbara Doe,dc=example,dc=com      │      The schema definition of the classes
   │  objectClass: inetOrgPerson                 ←───┤      of an entry defines what kind of
   │  objectClass: organizationalPerson          ←───┤      object the entry may represent
   │  objectClass: person                        ←───┤      (e.g. person, org, domain,...)
   │  objectClass: top                           ←───┘      The object class definitions also
   ├─ UUID: 3ff91489-7d7e-4cdf-884e-f04753d2e6fa            define the list of attributes that
   │                                                        - must contain values
   └─ DN may change over the lifetime of the entry          - may  contain values.
      for instance, when entries are moved within a tree.
      An UUID attribute might be provided in the set of
      the entry's operational attributes to really have
      a Unique ID associated to the entry
      - 'dn' is neither an attribute nor a part of the entry.

      Note: dc stands for (D)omain (C)omponent

- A server holds:
  - a subtree starting from a specific entry*
    For example: "dc=example,dc=com"
  - (optional) references to other servers
    an attempt to access a dn in other server will
    return a server-referral to the client.
    - (optional) some servers support chaining:
      - The server will directly contact the other
        servers on behalf of the client

-ºLDAP rarely defines any orderingº
 (sets need not be ordered)

BIND also sets the LDAP protocol version by sending a

When LDAP servers are in a replicated topology, LDAP clients should consider using the post-read control to verify updates instead of a search after an update.

ºURI schemeº
ldap://host:port/"Distinguished Name"?csv_list_attributes?search_scope?filter?extensions
                  ^^^^^^^^^^^^^^^^^^  ^^^^^^^^^^^^^^^^^^^ ^^^^^
                  Used as search base    comma-separated  search
                                         list of attr     scope:
                                         to retrieve    - base DN
                                                        - one (level)
                                                        - sub (tree)

ºDirectory Schemaº
- set of rules (definitions and constraints) concerning
  the structure of the directory information tree (DIT),
  or what information the server can hold.
  - Attribute Syntaxes: Provide info about the kind of info that can be stored in an attribute.
  - Matching Rules    : Provide information about how to make comparisons against attribute values.
  - Matching Rule Uses: Indicate which attribute types may be used in conjunction
                        with a particular matching rule.
  - Attribute Types   : Define an object identifier (OID) and a set of names that may be
                        used to refer to a given attribute, and associates that attribute with a
                        syntax and set of matching rules.
  - Object Classes    : Define named collections of attributes and classify them into sets of
                        required and optional attributes.
                        ObjectClasses can be inherited.
  - Name Forms        : Define rules for the set of attributes that should be included in the
                        RDN for an entry.
  - Content Rules     : Define additional constraints about the object classes and attributes
                        that may be used in conjunction with an entry.
  - Structure Rule    : Define rules that govern the kinds of subordinate entries that a given
                        entry may have.

BºNOTEº: Clients may learn about the schema elements that the server supports
         by retrieving an appropriate subschema subentry.

- A schema for representing individual people within organizations is termed a white pages schema.

ºAccess control is not standardizedº  though there are commonly used models.

ºLDAP extension pointº
  - define new operations.
  - modify requests/responses (sort results,...)
  - New search scopes and Bind methods can be defined.
  - new attributes options modifying their semantics.
  - ...

ºAccess protocolº
- As LDAP has gained momentum, vendors have provided it
  ºas an access protocol to other servicesº
  For example, Unix user and group information (via PAM, NSS modules)
- LDAP is often used by other services for authentication.

- two common styles of naming:
  - top level objects are the c= (country) object
                    l=Locality, ou=Some Organizational Unit, o=Some Organization,        c=FR
    cn=Common Name, l=Locality, ou=Some Organizational Unit, o=Some Organization, st=CA, c=US

  - top level objects are domains
    cn=Common Name, dc=example,  dc=com
Active Directory
Active Directory LDAP requires that names of directory objects be
formed according to RFC 1779 and RFC 2247:
- @[]
    This document defines an algorithm by which a name registered with
    the Internet DNS can be represented as an LDAP distinguished name.  ←→  dc=subdomain,dc=com

    The algorithm for transforming a domain name is to begin with an
    empty distinguished name (DN) and then attach Relative Distinguished
    Names (RDNs) for each component of the domain, most significant (e.g.
    rightmost) first. Each of these RDNs is a single AttributeTypeAndValue,
    where ºthe type is the attribute "DC"º and
          ºthe value is an IA5 string containing the domain name componentº

    Two LDAP object classes are also defined.
    - dcObject: to integrate into alreaded existing schemas,
                alowing the dc attribute to be present in an entry.
    -   domain: structural object class used for entries in which no
                other information is being stored

- @[]
    X.500/LDAP distinguished names (primary keys) are encoded in ASN.1.
    there is a need to have a user-oriented string representation of DNs.
    ("human to human")

    Standardised Keywords*             Exs:
    Key     Attribute (X.520 keys)     |CN=Christian Huitema, O=INRIA, C=FR
    ------------------------------     |CN=Christian Huitema; O=INRIA; C=FR
    CN      CommonName                 |˂CN=Christian Huitema; O=INRIA; C=FR˃
    L       LocalityName
    ST      StateOrProvinceName        |CN=James Hacker,
    O       OrganizationName           |L=Basingstoke,
    OU      OrganizationalUnitName     |O=Widget Inc,
    C       CountryName                |C=GB
    STREET  StreetAddress
                                       |OU=Sales + CN=J. Smith, O=Widget Inc., C=US
                                          |CN=L. Eagle, O="Sue, Grabbit and Runn", C=GB
                                          |CN=L. Eagle, O=Sue\, Grabbit and Runn, C=GB

  PGP: Pretty Good Privacy: encryption program (1991 Phil Zimmermann)
       Used for signing, encrypting, and decrypting texts, e-mails,
       files, directories, disks, e-mails.
  OpenPGP: Open Standard around PGP software (RFC 4880)

  GPG: Gnu Privacy Guard implementation

Bº* Symmetric file encryption *º
 - simpler and more secure than asym. one.
 - Can NOT be used to publish with anonymous or untrusted users.
   For example, it can NOT be used to cypher (or sign) content in
   public software repositories since there is no way to distribute the
   private key to future and unknown/untrusted recipients.
 - In can be used to store secrets safely in private repositories like git.
 - Ex Ussage:
     "master key" : Private key that git team keeps secret (ideally "memorized")
                    Different master keys can be used in different contexts.

     $º$ ls secrets.txt*            º
     Rºsecrets.txtº                    ← Secrets to access login, cloud resources, ddbbs,...
                                       Rºadd to .gitignoreº to avoid distributing secrets

     $º$ cat secrets.txt \                    º
     $º  | gpg -c --batch --passphrase $pass\ º ← Generates binary encrypted output Qº*1º
     $º  | base64 \                           º ← (optional): Allows to copy in mail/stdin/... 
     $º  ˃ secrets.txt.gpg.base64             º
         BºCan be added to gitº: Each time "master key" is
           rotated, this file must be regenerated (and old
           master key used in the mean time to decrypt).

     $º$ cat secrets.txt.gpg.base64 \         º
     $º  | base64 -d \                        º
     $º  | gpg -d --batch --passphrase $pass \º   Qº*1º
     $º  ˃ secrets.txt                        º

     Qº*1º: Remove --batch --passphrase options to ask for password interactively.
            (probably safer, but can not be scripted easily)

    $º$ shred -n 2 -z -v secrets.txtª  ← deleting the file leaves original bytes in the hard-disk

Bº***************************º Bº* managing pub/priv. keys *º Bº***************************º - Before signing and encripting we need to learn how to create/import/export PGP keys. REF:@[] $º$ gpg --gen-key º ← Create new key pair defs: RSA 2048bit, no-expire # (enter name,email ^^^^^^^^^ when prompted) Recommended ˂=2 years Once expired it can be extended providing key (and passphrase) $º$ gpg2 --list-keys º ← ºLIST ALL PUB. KEYS (ours and imported/pulled)º /home/juven/.gnupg/pubring.gpg ------------------------------ pub 1024D/C6EED57A 2010-01-13 ← Seed key uid ...˂˃ sub 2048g/D704745C 2010-01-13 ← Sub.signing key └─┬─┘ └──┬───┘ length Bºkey idº $º$ gpg2 --list-secret-keys º ← ºLIST PUBLIC KEYS FROM OUR PRIVATE KEYSº /home/juven/.gnupg/secring.gpg ------------------------------ sec 1024D/C6EED57A 2010-01-13 ← Seed key uid ...˂˃ ssb 2048g/D704745C 2010-01-13 ← Sub.signing key OºKEYSERVER="hkp://"º ┌─────────────────────────────────────┬─────────────────────────────────────┐ │ º"PUSH" PUB.KEY │ "PULL" PUB.KEYº │ ├─────────────────────────────────────┼─────────────────────────────────────┤ │$º$ gpg2 --keyserver ${KEYSERVER} \º │ $º$ gpg2 --keyserver ${KEYSERVER} \º│ │$º --send-keys B C6EED57A º │ $º --recv-keys C6EED57A º│ └─────────────────────────────────────┴─────────────────────────────────────┘ $º$ gpg2 --edit-key A6BAB25C º ← ºMODIFY KEYº ... Secret key is available. pub 2048R/A6BAB25C created: ... expires: ... trust: ultimate validity: ultimate sub 2048R/DD289F64 created: ... expires: ... Juven Xu (for testing) ˂˃ ... gpg˃ Oº1º # ← Choose key pub 2048R/A6BAB25C created: ... expires: ... usage: SC trust: ultimate validity: ultimate sub 2048R/DD289F64 created: ... expires: ... usage: E (1)* Juven Xu (for testing) ˂˃ gpg˃ Oºexpireº ← ºEXPIRE A KEYº → ... → Please specify how long the key should be valid. 0 = key does not expire ˂n˃ = key expires in n days ... gpg˃ Oºsaveº ← send key ("push") to sync changes remotely BºTroubleshooting problems with Maven and others: mvn and some other app will only recognise the primary key, ignoring subkeys. A "patch" solution consists in deleting the singing subkey forcing GPG to use the primary key. $º$ gpg2 --edit-key A6BAB25C º ← ºMODIFY KEYº ... pub 2048R/A6BAB25C created:... usage: SC ← Seed Key. RºOnly key recognised by maven and othersº trust: ultimate validity: ultimate sub 2048R/DD289F64 created:... ºusage: E ← Default (E)ncryption key sub 2048R/8738EC86 created:... ºusage: S ← Default (S)igning key (RºMust be removed to use maven pgp pluginº ) gpg˃ Oºkey 2º (index start at 0) (Not needed if using gpg from comand line) ... │ gpg˃ Rºdelkeyº ← Alt 1: Key not yet published ←─┘ gpg˃ Rºrevokeº ← Alt 2: Key already published gpg˃ Oºsaveº
Bº*****************º Bº* Signing files *º Bº*****************º $º$ gpg2 -ab º ← ºSIGNING A FILEº -a create ASCII armored output -b make detached signature $º$ gpg2 --verify º ← ºVerify new signatureº
Bº****************************************º Bº* Advanced (Symmetric) file encryption *º Bº* multi-level password: (Bell–LaPadula) *º Bº****************************************º @[] - Level 3 user have passwords to encrypt/decrypt level 3 - level 2 user have passwords to encrypt/decrypt level 2,3 - level 1 user have passwords to encrypt/decrypt level 1,2,3 LEVEL1=level1Ciphered.base64 ; DECODE_LEVEL1=decodedlevel1 ; LEVEL2=level2Ciphered.base64 ; DECODE_LEVEL2=decodedlevel2 ; LEVEL3=level3Ciphered.base64 ; DECODE_LEVEL3=decodedlevel3 ; GPG_C="gpg -c --batch --passphrase " # Encode GPG_D="gpg -d --batch --passphrase " # Decode # Encode ( echo "secrets level 1" ) | ${GPG_C} ${PASS_LEVEL1} | base64 ˃ ${LEVEL1} ( cat ${LEVEL1} ; echo "secrets level 2" ) | ${GPG_C} ${PASS_LEVEL2} | base64 ˃ ${LEVEL2} ( cat ${LEVEL2} ; echo "secrets level 3" ) | ${GPG_C} ${PASS_LEVEL3} | base64 ˃ ${LEVEL3} # Decode cat ${LEVEL3} | base64 -d | ${GPG_C} ${PASS_LEVEL1} ˃ ${LEVEL2} ← cat ${LEVEL2} | base64 -d | ${GPG_C} ${PASS_LEVEL2} ˃ ${LEVEL1} ← cat ${LEVEL1} | base64 -d | ${GPG_C} ${PASS_LEVEL3} ˃ PLAIN_TEXT ←
Convert keys GPG|OpenSsh|OpenSSL

- OpenPGP is a standard that defines formats for encryption keys and
  messages. By providing a Linked Data Signature suite that uses
  OpenPGP we can leverage a more established standard to support an
  emerging one (Linked Data Signatures). A Linked Data Signature Suite
  for OpenPGP also enables OpenPGP to be used as a building block for
  other standards, such as Decentralized Identifiers.

This signature suite follows the approach taken by:
- Ed25519Signature2018  :
- RsaSignature2017
- EcdsaKoblitzSignature2016

- cli Ussage example:
  - Sign a json document:
  $ openpgpsignature2019 sign -u "3AF00854CF8D9237" \
    $(pwd)/src/__tests__/__fixtures__/documents/example.json \
  - Verify a document:
  $ openpgpsignature2019 verify $(pwd)/src/__tests__/__fixtures_\

- library ussage example:
  const keys = await OpenPgpSignature2019.generateKey({....})
  const signedData = await OpenPgpSignature2019.sign(
      { data: jsonDoc,
        privateKey: keys.privateKey,
        proof: {
          verificationMethod: "",
          proofPurpose: "assertionMethod"

  const verified = await OpenPgpSignature2019.verify({
    data: signedData,
    options: ...
Keybase ("GPG++")
- Keybase essentially introduced a modern way to build trust networks, because
  people can check that user123 on Keybase is also user123_coder on GitHub,
  user123 on Twitter, and that the user owns the domain. One can
  do so by posting Keybase-signed messages to these social networks and places.
  This is a good idea, because from social networks and Keybase accounts linked
  to those social networks, you can build a trust network on Keybase.

- Keybase provides a simplified workflow for common tasks including key
  management (e.g., fetching keys of your contacts), and it has GnuPG
  interoperability. You may even make the devilish (read: convenient) choice of
  having your keys stored on Keybase, or just attach existing GnuPG keys that you
  will still manage locally.

Guncat (Gpg UNencrypting CAT) was designed to tackle a problem encountered
with (partially) PGP encrypted files (which may be encountered in, e.g.,
mailboxes).  Tools to process text-files (like grep(1), or less(1)) may be
used to process those files, but standard tools like cat(1) leave PGP
encrypted sections within such files as-is. As a consequence, browsing the
`real' contents (i.e., clear-text sections and the unencrypted contents of PGP
encrypted sections) of those files is difficult.

Guncat  acts like cat, but unencrypts encrypted sections encountered in
the files processed by guncat, copying the unencrypted  information  to
guncat's  standard  output  stream, which may thereupon be processed by
other tools.
JavaScript implementation of the OpenPGP protocol defined in RFC 4880.
- a/symmetric (En/de)crypt Uint8Array with PGP key/password.
- Encrypt with compression
- Data Streaming support.
- key pair generation / revocation.
- "Push"/"pull"  public keys from HKP server
- Sign/verify cleartext/Uint8Array stream messages
  (detach signature support)
- Uses Crypto.Message (PKCS#7) and pub.key infraestructure for encryption and signing
- PGP/SMIME EFail vulneravility
- protocol for securing/authentication/encrypting instant messaging communication amongst people.
 Encrypts messages, prevents eavesdroppers, authenticates peers to each other.
 It also provides OTR provides forward secrecy and malleable encryption.

- OTR uses a combination of AES 128bits sym-key algorithm,  1536-bits group-size Diffie–Hellman
  and the SHA-1 hash function.
- The primary motivation behind the protocol was providing deniable
  authentication for the conversation participants while keeping
  conversations confidential, like a private conversation in real life, or
  off the record in journalism sourcing. This is in contrast with
  cryptography tools that produce output which can be later used as a
  verifiable record of the communication event and the identities of the
  participants. The initial introductory paper was named "Off-the-Record
  Communication, or, Why Not To Use PGP".[1]
- The OTR protocol was designed by cryptographers Ian Goldberg and Nikita
  Borisov and released on 26 October 2004.[2] They provide a client library
  to facilitate support for instant messaging client developers who want to
  implement the protocol. A Pidgin and Kopete plugin exists that allows OTR
  to be used over any IM protocol supported by Pidgin or Kopete, offering an
  auto-detection feature that starts the OTR session with the buddies that
  have it enabled, without interfering with regular, unencrypted
Dmarc sec mail
DMARC is a protocol that helps protect the integrity and
authenticity of email. DMARC is not a single technology but rather
is a combination of several components, including the Sender Policy
Framework (SPF) and Domain Keys Identified Email (DKIM), to help
verify email authenticity. There are also different levels of DMARC
policies. The "p=none" policy enables organizations to monitor
their email systems for senders, while the "p=reject" policy will
block non-compliant messages completely. BOD 18-01 mandates the use
of the p=reject policy by Oct.16.
PKCS: Set of "high-level" "Public Key Cryptography Standards":
- ºPKCS #1º math. properties + format of RSA pub/priv keys, and
  basic algorithms and encoding/padding schemes for RSA
  (de/en)cryption,  producing/verifying signatures.
- ºPKCS #3º Diffie–Hellman Key Agreement Standard
- ºPKCS #5º Password-based Encryption Standard
- ºPKCS #7º Cryptographic Message Syntax used to sign
  and/or encrypt messages under a PKI
  See also (PKCS #7 derived)Cryptographyc Message Syntax
- ºPKCS #8 º to carry private certificate kye (and matching pub.key)
- ºPKCS #9 º Defines selected attribute types for use in PKCS #6,#7,#8,#10
- ºPKCS #10º  Certification Request Standard
- PKCS #11
  Cryptographic (Athentication) Token Interface
  ("Cryptoki") API defining a generic interface to cryptographic tokens
- ºPKCS #12º Personal Information Exchange Syntax defining file
  format commonly used to store private keys, protected with a password-based
  symmetric key. Used by:
  - Java key store
  - client auth. certs in Firefox, Apache Tomcat
- ºPKCS #15º idetification through tokens allowing users to identify
  themselves to applications, independent of the application's Cryptoki
  implementation (PKCS #11) or other API

  See also:
  - ISO 7816 standard for electronic identification cards with contacts, especially smart cards.
WebCrypto API
BºWebCrypto API providesº;
  "relatively" new browser API helping efficient and secure delivery
  of cryptographic primitives.
  - low-level ciphers.
  - hashes
  - "other" encryption components.

   Being directly implemented into (trusted) browser and taking
   advantage of local native execution and even hardware acceleration)
   they are much safer than js code.
   RºWARN:º They do NOT prevent certain attacks, like
   just sending an unencrypted copy of the data to the "bad guys".

   See also: Trusted web code at @[/WebTechnologies/map.html?query=trusted.web.code]
XML Advanced Electronic Signatures (XAdES)
OASIS XML Digital Signature Services (DSS) TC
(Not to be confused with Digital Signature Standard DSS)
ºopen-source software libraryº for ºelectronic signature creation and
validationº. DSS supports the creation and verification of interoperable
and secure electronic signatures in line with European legislation.
In particular, DSS aims to follow the eIDAS Regulation and related standards closely.

DSS can be re-used in an IT solution for electronic signatures to ensure that
signatures are created and verified in line with European legislation and
standards. DSS allows re-use in a variety of different ways: in an applet, in
a stand-alone application or in a server application. DSS can also be used as
a reference implementation for IT solutions which do not directly re-use it.
Demos are also available to assist the use of DSS as a reference implementation.

The library, ºrealised in Javaº, is open-source, available to all Member States
, businesses and citizens for re-use in electronic signature solutions. It is
continuously updated and maintained to anticipate and follow developments in
regulations and standards.

Anyone can integrate it and redistribute it under the terms of the Lesser
General Public License (LGPL 2.1).

In accordance with ETSI standards, DSS supports various document and
signature formats including PAdES, XAdES, CAdES and ASiC and is compliant
with Implementing Decision 2015/1506/EU. A “cook-book” is also provided with
documentation targeting implementers/developers and aiming at facilitating
the integration and use of DSS in their applications.

  The Cryptographic Message Syntax (CMS) is the IETF's standard
  for cryptographically protected messages. It can be used to
  digitally sign, digest, authenticate or encrypt any form of
  digital data.
  Extensions to 'Cryptographic Message Syntax'
- ASiC_format
  ASiC Baseline Profile. ASiC (Associated Signature Containers)
  specifies the use of container structures to bind together one
  or more signed objects with either advanced electronic signatures
  or time-stamp tokens into one single digital (zip) container.
Why do we want to support AdES formats using x509 certificates? JAdES
may be the only one worth considering if it can be used e.g. in a VC
proof and under certain conditions... I'd even argue that JAdES could
be just the adoption of a VC with a well defined proof format, but
I'm not sure this is the plan of ETSI ESI TC.

I put this here as it was in Jesus' proposal. We never discussed in
detail, what we'd support. + this doc is not very up to date.

I agree with Oscar BURGOS in that the only one worth considering is
JAdES, and even so I do not think that EBSI should do anything. They
were put in the document as a reminder, because AdES formats are the
ones widely legally accepted for business transactions, eg.
eInvoincing. But as Oscar says, ideally (using the axample of a
eInvoice), the eInvoice could be represented as a VC.
However, I would like to check that we are not doing something
"incompatible" or that makes somewhat difficult that representation
(I have no idea of what can it be, just it may be woth checking).
The JAdES standard is ongoing work in ETSI
=52897), and they want to publish in March this year.
Anyway, I will try to talk with Juan Carlos Cruellas, who is the
person more active driving the drafts, just to see if they are aware
and check.
X.509 TimeStamp Protocol

- RFC describes format for request and responses sent to a
  Time Stamping Authority (TSA)
- It establishes several security-relevant requirements for TSA

- TSA service:
  - provides proof-of-existence:
    - Some data datum existed before a particular time.
      (only the hash representation is used by the protocol)
  - Can also be used as the base for Non-repudiation services [ISONR]
  - only time-stamp a hash representation of the datum, i.e., a
  - CAs will issue custom certificates for this service indicating
    that it is exclusively used for this TSA purpose

2.2. TSA Transactions

A → TSA: request1

TSA → A: response1

A →   A:- verify status error
        - verify fields contained in the TimeStampToken
        - verify validity of digital signature
        - verify that what was time-stamped corresponds
           to what was requested
        - verify that the TimeStampToken contains:
          - the correct certificate identifier of the TSA
          - the correct data imprint
          - the correct hash algorithm OID.
        - verify time included in the response against
          local trusted time reference

See original RFC for extended details
Project Everest

A combination of several sub-projects:
- F*, a verification language for effectful programs
- miTLS, reference implementation of the TLS protocol in F*
- KreMLin, a compiler from a subset of F* to C
- HACL*, a verified library of cryptographic primitives written in F*
- Vale, a domain-specific language for verified cryptographic
  primitives in assembly
- EverCrypt, a verified crypto provider that combines HACL* and Vale
  via an agile, multi-platform, self-configuring cryptographic API.
- EverParse, a library and tool to automatically generate verified
  parsers and serializers for binary data formats

- introduced in @[]
- Using F* (@[])formally probed language
  for implementation of cryptographic primitives (otherwise
  extremely difficult and error prone to implement in C/Rust/...).
- formally-verified Curve25519, ChaCha20, Poly1305,
  P256 elliptic curve for ECDSA and ECDH, GCM, P384/P521 elliptic
  curves, ECDSA signature scheme,...
- Performance close to native assembler manual implementation
- Fiat-Crypto project:

- Used in newer versions of Chrome/Firefox/...

- See also:
- Formally Verified Cryptographic Web Applications in WebAssembly
Software Development
Think lib: crypto for non-experts
- Crypto.libr for *non cryptographic experts
- cross-platform
- developed by experts to help developers implement cryptography
  correctly ºwithout being cryptographic expertsº.
- version 1.2 adds support for Cloud, Android, and iOS platforms,
  C++ and Objective-C.
- stress cryptographic libraries against known attacks:
  - biased nonces
  - invalid curves
  - ...
-OºTink provides support for key managementº
 Oºincluding key versioning/rotation/remote key management systems(KMS):º
 Oº-  Currently, the following KMSes are supported:º
 Oº  Google Cloud KMS, Amazon KMS, Android Keystore, Apple iOS KeyChain (planned)º

- ensure crypto.algorithms behave as expected (DSA, RSA, AES-EAX, ...)

- Tink strives to make as explicit as possible what security guarantees each
  provided API gives:
  - For example, if a given operation is safe against chosen-ciphertext attacks,
    this is displayed in the interface and that same guarantee has to be satisfied
    by each primitive used to implement it.

- currently four cryptographic operations are provided, implemented by specific primitives:
  - authenticated encryption with associated data (primitive: AEAD)
  - message authentication codes (primitive: MAC),
  - digital signatures (primitives: PublicKeySign and PublicKeyVerify)
  - hybrid encryption (primitives: HybridEncrypt and HybridDecrypt).

- Each operation has an associated set of minimal properties and a guarantee.
  A primitive can have multiple implementations and the user chooses the actual
  implementation to use by instantiating a key of a corresponding type.

Ursa library
- Hyperledger Ursa is a shared cryptographic library, it enables
  implementations to avoid duplicating other cryptographic work and
  hopefully increase security in the process. The library is an opt-in
  repository (for Hyperledger and non Hyperledger projects) to place
  and use crypto. Hyperledger Ursa consists of sub-projects, which are
  cohesive implementations of cryptographic code or interfaces to
  cryptographic code.
Quantum Related
Lamport signatures
- quantum-proof cryptographic signatures
- Quantum Safe Ethereum proxy with
  Winternitz One-Time signatures
Zero Knowledge Execution
Ext. Links
- Awesome ZKP:

- Tjaden Hess Github:
Fully homomorphic Encrypt.

Broadly classifiable within the same arena as secure multi-party
computation, Homomorphic Encryption is an approach to secure
computation that does not require decrypting your data in order to
process them. Instead, homomorphic encryption enables processing
ciphertexts with the guarantee that encrypted results match those
that would be produced by first decrypting input data, processing
them, and finally encrypting them.

IBM Fully Homomorphic Encryption Toolkit is based on HELib, an open
source HE library providing a number of low-level routines such set,
add, multiply, shift, and others, along with higher-level features
for automatic noise management, multi-threading, and so on.

Homomorphic encryption is still a rather young field which attracts
lots of research efforts.
- Microsoft, for instance, released SEAL (Simple Encrypted Arithmetic Library)
- Google recently unveiled its Private Join and Compute tool:
Extracted from

zk-SNARK stands for "Zero Knowledge Succinct Non-Interactive Argument of Knowledge"

- It is a family of privacy tools called zero knowledge proofs (ZKP).

-  While other privacy techniques like bulletproofs, ring
  signatures and stealth addresses, etc. mask the identities of the
  entities involved in a business transaction, ZKP techniques allow to
  prove logical statements without divulging any information and yet
  proving the validity of such proofs. Particularly, zk-SNARKs are
  mathematical concepts and tools to establish zero knowlege
  verification of succinct proofs, which convert logical statements to
  arithmetic circuits, that are then leveraged to generate proofs.

- Normally zk-SNARKs are used as a way to say "I have a secret" to
  someone and prove that you indeed have the secret without telling
  them what the secret is. What the Baseline Protocol uses it for is a
  little different. It's more like saying to a specific set of
  counterparties, "We have a secret" and using a machine that we all
  can access to tell us that we all have the same secret (or that we do
  not) without telling that machine anything that would let someone
  else with access to it discover anything about the secret...or even
  that we have one.

Wallet vs KeyStore vs Vault
- In KeyStore, secrets are kept safe until needed by an application.
- Vault are mostly the same that Keystores. In cloud vaults they ussually
  provide access policies (that probably are not available in local key-stores).

- In wallets, the secrets (ideally) are never exposed outside the wallet.
  Unsigned transactions come in, then signed transactions come out.
  The wallet usually have aditional utility functions like "address agenda",
  "browser of transactions", ...

- A wallet makes use of a keystore. (A vault is a "layer down the stack")

- Keystores are generic for any type of app.

- Wallets are mostly used for blockchain-like applications.

- Vault, being a "marketing" biased nomenclature, can and ussually do
  include wallet alike functionality allowing to sign input and get
  signed output from the vault, with no intervention from the original
  ("unsecure") app. For example Parity considers vaults to be """
   an additional privacy feature on top of wallets to lock away accounts
   behind a second layer of protection encrypting the meta-data
   (public addresses,...) """. Such features just apply to the particular
   Parity vault implementation when compared to the Parity wallet

Wallet vs Smart-Cards
  - Some types of Smart-Cards can be considered a type of wallet, in
  the sense that they can be used to sign content using a hardware
  protected private-key.
  - Still Smart-Cards are mostly designed with Authentication as
    primary use-case, to provide that the user accessing a website,
    a bank terminal, ... is the real authorized user.
  - Wallets is mostly a blockchain concept, while smart-card is
    a general device that can be used for many purposes
    (Web TLS or SSH Client Authentication, PGP signature, ...)
  - Wallets are designed with TX signature in mind.
    A wallet protects the private key, signs the TXs and probably
    has a display that shows what's going to be signed and a
    physical button that the user must "click" in order to confirm
    the transaction.
  - Stealing of the wallet can mean stealing of the money.
  - Stealing of the smart-card means money can be stealed until
    the smart-card is cancelled.
Deterministic Wallet
A deterministic wallet is a system of deriving keys from
a single starting point known as a seed. The seed allows
a user to easily back up and restore a wallet without
needing any other information and can in some cases allow
the creation of public addresses without the knowledge of
the private key. Seeds are typically serialized into
human -readable words in a Mnemonic phrase.
JS Carbon Wallet

- No server side storage, ºprivate keys are generated from º
 ºthe passphrase and only exist in the memory of the browserº
- Deterministic key generation: Write down the passphrase
  generated for you and it's all you need
- Transactions are signed locally in the browser: Your
  private keys are not shared with the server. You do not
  have to trust the server with your money
- Privacy: No need to register a passphrase is all that
  is required
- Public code hosted on Github which anyone can audit
- free, open source, light-weight and easy-to-use password manager in a ¿secure?
- All passwords are stored in a single database file (encrypted with AES/Twofish)
  locked with one master key or a key file.
            (The only pass needed to remember)

Hardware wallets
Lattice 1
- Generalized remote (WiFi, Bluetooth?,...) transaction signer.
  Private key is never transmited outside the hardware.

- Update 2020-10-22: First pre-orders available:

- Features:
  - Better Interface: (when compared to hardware wallets)
                      read exactly what you're signing on a 5" TFT touchscreen.
  - More Secure     : Mitigates attack vectors from edge cases that other
                      hardware wallets do not take into account.
  - Extensible      : Back up accounts to a PIN-protected SafeCard
  - Firmware updates: They will enable support for easy N-of-M hardware multisig using SafeCards.
  - Programmable    : Lattice == Linux mini-computer + general and secure compute environments
                      This makes it possible to use permissioned signing for subscriptions
                      or to automate processes such as signing as a proof-of-stake validator.
  - Connectivity    : - Pair devices via WiFi.
                      - IoT communication through Zigbee antenna.

 - USER INTERFACE: interface to:
   - persisted user data: addresses, TX history,...
   - network nodes: allow to display account info
 - TX BUILDER    :
   convert parameters (amount, recipient address, ...)
   into one or more hashes that make up a TX compatible
   with the Network protocol.
   Note: in Ethereum, each TX is represented by a
     single hash, whereas in Bitcoin each consumed
     input has its own hash to sign,  there can be
     one or many inputs per Bitcoin transaction.
 - TX SIGNER     : sign TX hashes with private key.

 - STEP 1:
   let's consider moving TX signer to cloud machine.
   =˃ you have to store your private key on the cloud
 - STEP 2:
   Move TX builder in the cloud too

 """In Lattice1 we have separated the protocol and
    cryptographic functionality away from the application
    layer ... Of course keys are in a secure chip within
    the Lattice1."""

- robust and secure connection between application
  ("wallet GUI") and TX builder/signer components.

 ┌────→ "GUI Apps in Cloud"
Standard Chip ←─────────→ Secure Chip 1 ←────→ Secure Chip 2
    ↑                        ↑                    ↑
- connect to           - Build TX hashes      - Store priv.keys
  outside apps         - Placed on device     - Make signatures
- request signatures                          - Placed on device
- facilitates (wireless)                        and each Safe Card
  communication app←→Sec.Chip
  (Lattice1 addition)

BºPRE-SETUP: GUI App Connectionº:
  STEP 1) App    generates EC25519 key pair (just once)
  STEP 2) Chip 1 generates EC25519 key pair (for each new app pairing)
  STEP 3) PAIRING: ECDH Key exchange is use to interchange
                   App.pub_key ←→ Chip1.pub_key_for_app1

BºPairing App ←→ Lattice 1º:
  ""app wants to pair with a user’s Lattice1 device.""

 -ºSTEP 1º) Find device by serial number
           (not needed if Lattice1 can connect with the app
            on a local area network).
 -ºSTEP 2º) Pairing: (Similar to pairing Bluetooth)
            - User must enter in Lattice1 the same code shown in App.

 -ºSTEP 3º): Establish a Read-Only (Minimal) Permission
             Lattice1 gives app permission to view addresses,
             request signatures (that must be authorized on device screen)
             for one-off (vs automated) signatures,...

  After STEP 3, App can be used as a generalized TX Signer like any other
  hardware wallet.  Unlike other hardware wallets, however, the paired
  application is capable of communicating with the device wirelessly.

- As mentioned above, the pairing process also creates a minimal "permission".
  The application may request a signature using similarly to existing hardware
  wallet TXs:
  - Lattice1 displays TX data to the user and must wait for the user
    to hit "accept" on the touch screen.
  - A few technical differences that are worth noting:
    - data must conform to a pre-defined "schema".
     (periodically released as use cases emerge, like
      ETH transfers and BTC transactions (P2SH|P2PKH).

BºAUTOMATIC REMOTE SIGNINGº (Ex. recurring payments, keep-alive messages)
  - Use of "recurring permissions", which require a pre-defined schema
    (just like manual signatures) in addition to a set of "rules" on the
    data that will be signed in the future. Such a permission might look like this:

      schemaIndex: 0,     ← published "schema" for Eth TX (0)
      typeIndex: 0,       ← ETh TX type.  0: standard TX (empty data)
      rules: [
        null    , null                                        , null,
        null    , null                                        , null,
        null    , null                                        , null,
        'equals', '0x39765400baa16dbcd1d7b473bac4d55dd5a7cffb', null,  ←  recipient
        'equals', 1000                                        , null,  ←  wei ammount
        'equals', ''                                          , null,
           ^                        ^                            ^
        typeOfRule             value1                           value2
      timeLimit: 10000                                                ← seconds elapsed between requests

    specific rules [ nonce, gas, gasPrice, to, value, data ]

  - Requester can only send a request once every 10_000 seconds.  (~ 2h 40min)

BºGrid+ Application SDKº:
  - OOSS node.js module.
  - Example  mobile wallet application also provided as example.
  - JS code snippet: (WiP: 2018)

    const Sdk = require('gridplus-sdk');
    const sdk = new Sdk({ btcNode: 'localhost:48332', ethNode: 'localhost:8545' });

    const req = {
      type: 'eth-transfer',
      rules: {
        value: { 'equals': 1000 },
        to: { 'equals': '0x39765400baa16dbcd1d7b473bac4d55dd5a7cffb' }
      interval: 10000

    sdk.createAutomaticPermission(req, (err, res) =˃ {
      ... do stuff ...
Azure Sphere Pluton
Azure Sphere is solution for creating highly secured,
connected MCU-powered devices.

- The Pluton security subsystem creates a hardware root of trust,
  stores private keys, and executes complex cryptographic operations.
"Top" hard.Wallets
(Updated to 2018)

ºLedger Nanoº
- securised key store system:
  - Fully-certified by ANSSI, the French cybersecurity agency.
  - BºBackup:º crypto assets stay safe even if you lose Ledger Nano S.
    A confidential recovery phrase backs up your device,
    and your accounts can easily be restored on any Ledger device.

- Controlled through Google Chrome.
- RºRecovery method?º

ºSafe T-Mini (Archos)º
 Notre avis complet sur le Safe T-mini
- RºRecovery method?º

ºLedger Blueº
- architecture double-chip.
- To validate TXs, it can comunicate through USB/Bluethooth.
- Targeting business.
- "Big" screen for easy ussage.
- RºRecovery method?º

ºCoolBitX CoolWalletº
- Credit Card format
- RºRecovery method?º

Trezor Wallet
- BIP 0032 Deterministic hardware wallet.
- TREZOR is basically a small computer. It is designed to
  protect your private keys from possible online and
  offline risks.
- RºRecovery method?º
Hardware Security Module(HSM)
(Vaults, encrypt modules,...)
        ┃  COMMUNICATION          ┃
        ┃ APIs/PROTOCOLS          ┃
        ┃                         ┃
        ┃ Standard Cross-Platform ┃
        ┃   -ºPKCS#10º            ┃
        ┃   -OpenSSL              ┃ HARDWARE
        ┃   -KMIP                 ┃ SECURITY
APP     ┃                         ┃  MODULE
        ┃ Non-Standard and/or     ┃
        ┃ Non-Cross-Platform      ┃
        ┃   -Java JCE             ┃
        ┃   -MS/CAPI              ┃
        ┃   -"others"             ┃

                        ºPKCS#11 flowº
     SOFTWARE                 ┇            HARDWARE
______________________________    ┃   ____________________________________________
                              ┃       ┌─────────────┐  ┌───┐  ┌──────────────────┐
App ←→ Driver PKCS#11 ←→ OpenSC → ┃ ←→│Crypto OpenSC│←→│Phy│←→│SmartCard ISOXXXX │
                              ┃       └─────────────┘  └───┘  └──────────────────┘

- Securosys HSM, used by R3 Corda to encrypt and sign offline.
  - REF:
  @[] (~8min:00)

Arch.considerations for cryptanalytic hardware
""the industry's #1 security key, enabling strong
two-factor, multi-factor and passwordless authentication."""

- Works with hundreds of services incluing Windows/Mac login,
  Gmail, Dropbox, Facebook, Salesforce, Duo, ...

- Multi-protocol support: FIDO2, U2F, Smart card, OTP
USB Armory
The following example security application ideas
illustrate the flexibility of the USB armory concept:

- Hardware Security Module (HSM)
- encrypted file storage with malware scanning,
  host authentication and data self-destruct
- USB firewall, bridging built-in receptacle and plug ports
- OpenSSH client and agent for untrusted hosts (kiosk)
- router for end-to-end VPN tunnelling, Tor
- password manager with integrated web server
- electronic wallet (e.g. pocket Bitcoin wallet)
- authentication, provisioning or licensing token
- portable penetration testing platform
- low level USB security testing
Enterprise HSM

             SECP256K1                      Crytographic APIs
           │              ┌──────────┬────────────────┬─────────────────────┬────────┐
           │              │ PKCS#11  │ Java (JCA/JCE) │ Microsoft CAPI  CNG │ OpenSSL│
nChiper    │              │          │                │                     │        │
           │              │          │                │                     │        │
Gemalto    │              │          │                │                     │        │
(LunaHSM)  │              │          │                │                     │        │
           │              │          │                │                     │        │
MultiFacto authentication
Universal Second Factor (U2F)
- See also:

internet open auth. enabling users to securely access services
ºwith one single sec.key and with no drivers or client software neededº

u2f at
See also: Universal Authentication Framework (UAF) protocol
- vision: "take strong public key crypto to the mass market"
- Successfully deployed by Facebook, Gmail, Dropbox, GitHub,, the UK government,
and many more.
Smart Cards
DS/EN 14890-1 Standard

Part 1 of this series specifies the application interface to Smart Cards
during the usage phase,ºused as Secure Signature Creation Devices (SSCD) º
describing the mandatory services ... covering the
ºsigning functionº, storage of certificates, related user verification,
establishment and use of trusted path and channel, requirements for
key generation...
the functionality of CWA 14890-1 is enhanced in the following areas:
- ºDevice authentication with Elliptic Curves (ELC)º
  ºfor existing asymmetric authentication protocolsº
  º(RSA Transport, Privacy Protocol)               º
- Secure Messaging Tags
- Further hash algorithms (SHA2-family)
- Use of AES in auth protocols and secure messaging.
   Supporting Documents related to Smart Cards and similar devices
   Document number     Document title  Class
   2006-06-001         Rationale for Smart cards and similar devices
   CCDB-2010-03-001    Guidance for smartcard evaluation v2.0  Guidance
   CCDB-2014-04-001    Security Architecture requirements (ADV_ARC) for
                       smart cards and similar devices (Mandatory)
   CCDB-2009-03-002    Application of CC to Integrated Circuits v3.0  (Mandatory)
   CCDB-2012-04-001    Composite product evaluation for Smartcards    (Mandatory)
                       and similar devices
   CCDB-2007-09-02     ETR-template lite for composition Guidance
   CCDB-2012-04-004    Security Architecture requirements (ADV_ARC)   (Guidance)
                       for smart cards and similar devices - Appendix 1
   CCDB-2013-05-001    Minimum ITSEF Requirements for Security  (Mandatory)
                       Evaluations of Smart cards and similar devices
   CCDB-2013-05-002    Application of Attack Potential to Smartcards  (Mandatory)

- GNUPGP Smart Card specs

- Extracted from @[]
  """PGP SmartCard is the most widely used
  Crypto Commands include:
    - DigestInfo for RSA
      + Client/Server Authentication

- GPG SmartCard for SSH Authentication
  $ ssh-keygen ...    │ (Install GnuPG 2 first)
                      │   $ gpg –gen-key  # Generate a keypair:
                      │   $ gpg –edit-key # ← Add ºauthentication subkeyº
                      │   ˃ addkey        # ←
                      │   ˃ keytocard     # ← transfer private part of subkey to smart-card
                      │                   #   A stub referencing the subkey is left behind
                      │                   #   with your on disk keypair.
                      │ - Whenever you try to use that subkey, the system
                      │   will request that you insert the smart card.
  $ ssh-copy-id ...   │  ("gpgkey2ssh" utility is provided by the gnupg-agent package )
                      │  Alt 1:
                      │    $ gpgkey2ssh $gpgSubkeyID_for_sshAuth \
                      │      → output_ssh_formated_pubkey
                      │        ^^^^^^^^^^^^^^^^^^^^^^^^^^
                      │    C+P to remote "~/ssh/authorized_keys" file
                      │  Alt 2: (If the auth.subkey is on public gpg keyservers):
                      │    $ gpg --recv-key 0018461F
                      │    $ gpgkey2ssh 13990B29 ˃˃ ~/.ssh/authorized_keys

  (how do we get the OpenSSH client to use the smart card)

  (setup ssh-agent)   │ gpg-agent has been designed to speak
                      │ the same protocol as ssh-agent
                      │ - STEP 01:
                      │   stop ssh-agent process
                      │ - STEP 02:
                      │   add "enable-ssh-support" to
                      │   ~/.gnupg/gpg-agent.conf
                      │ ( OpenSSH client should start talking
                      │   to gpg-agent now )
                      │ - STEP 03:
                      │   $ ssh-add -l
                      │ ( You should see that the key you
                      │   generated previously is mentioned
                      │   only when the S.C. is inserted!!! )
                      │ you’re done!!
                      │ ssh'ing to a remote machine with your pubkey
                      │ will ask to type your pin on the smart-card
                      │ reader.

  (See original ref for Windows/Putty setup)

- List of Implementations of the OpenPGP application for smart cards

- @[]
  """Founded by the principal author of GnuPG ...
     we provide custom development, enhancements
     and audits of cryptographic software.
     An ongoing effort of ours is the development
     and maintenance of GnuPG and related software."""
  - OpenPGP (Smart)Card Specs:

  - @[]
  RºWARN: Does not include displayº
  - Hardware cryptocurrency wallet
  - OpenPGP smart card
  - U2F authenticator
  - One-time password generator
- Linux/Windows/Mac OS X tool to read the contents
  of ISO7816 smart cards. It features a GTK GUI to
  represent card data is a tree view, and is extensible
  with a scripting language (LUA).

- The goal of this project is to allow smart card owners to
  be better informed about what type of personal information
  is stored in these devices.

- As of version 0.8.2, this tool is capable of reading the contents
  of the following types of cards:

- EMV "chip and PIN" bank cards, including:
      VISA, MasterCard, CB and UK Post Office Account contact cards;
      PayWave (VISA) and PayPass (MasterCard) contactless cards;
- Electronic/Biometric passports, which have an embedded contactless chip;
- The Belgian eID card;
- Calypso transport cards including:
      Navigo transport cards used in Paris;
      MOBIB cards used in Brussels;
      RavKav cards used in Israel;
      VIVA cards used in Lisbon;
- GSM SIM cards (without USIM data used in recent cards);
- Vitale 2, the French health card.
- Moneo, the French electronic purse;
- Driver Tachograph cards;
- OpenPGP Cards (beta);

Some important card types are missing or need further development,
however, this application can be modified and extended easily to your
needs with the embedded LUA scripting language
(Speed Up JavaCard Dev)
- [Video] Unchaining the JavaCard Ecosystem (2018-02-22)
Project providing convinient libraries for JavaCard development
including Integers, Big Numbers, Elliptic Curves and Profilers.

Java Card Comparision
Security token
- Physical devices used to gain access to an
  electronically restricted resource
- Used in addition to or in place of a password like a
  wireless keycard to open/unlock doors,...
- All tokens contain some secret information used to
  prove identity
- There are four ways in which this info. can be used:
  - Static password: token containing a password
    transmitted for each authentication (vulnerable to
    replay attacks)
  - Syncrhonous dynamic password token, using a
    timer to rotate through various combinations. Need
    time synchronization with server
  - Asyncrhonous password token generating One-time
    password (no clock involved)
  - Challenge-response token using pub.key
Trusted Exec Env

Intel SGX
RºWARN: SGX was vulnerable to Meltdown and Spectre hardware bugsº
CPU instruction set allowing user-level code to allocate
private regions of memory (enclaves) protected from
processes running at higher privilege levels. (secure
remote computation, secure web browsing, DRM).

SGX is a set of instruction set extensions for CPUs
released in Fall 2015 and available on recent CPUs. The
key ability SGX provides is the notion of confidential,
private execution with integrity guarantees. In essence,
the chip has a special construct called an enclave. An
enclave is like an ordinary program, except that the
memory contents of an enclave are encrypted whenever they
are off-chip, and accessible only on-chip, and only while
the special enclave code is running. Further, the
decryption keys are available solely to code with a
certain hash: if you or a hacker were to hack the enclave
code and change its hash, that hacked code will no longer
have access to the encryption keys, repelling attacks. As
a result, this ingenious technology does not permit anyone
, even the owner of the machine who can modify the code
arbitrarily, to peek at the contents of the enclave or to
modify execution within an enclave. Further, the SGX
hardware enables remote attestation, that is, the ability
to prove to a remote computer that a given enclave is
running a particular software distribution. In essence,
the chip is able to issue a statement that says "I
guarantee to any remote party that I am running this code
with this particular hash," which is a critical
bootstrapping mechanism. Teechan is built on these two
underlying features, which, together, provide a trusted
execution environment (TEE).
Vault services&KMS
HashiCorp Vault Project
"""HashiCorp Vault secures, stores, and tightly controls
  access to tokens, passwords, certificates, API keys, and
  other secrets in modern computing. Vault handles leasing,
  key revocation, key rolling, and auditing. Through a
  unified API, users can access an encrypted Key/Value
  store and network encryption-as-a-service, or generate
  AWS IAM/STS credentials, SQL/NoSQL databases, X.509
  certificates, SSH credentials, and more. "



(in combination with with etcd or consul)
Key Mng.Serv.(KMS)
- Google Cloud KMS
- Amazon KMS
- Android Keysotre
- Apple iOS KeyChain
- ...?
Gemalto: Data protection AaS
- TresorSGX is a attempt to isolate and secure a operating system
  component of the Linux kernel. It outsources a functionality of a
  kernel module into a SGX container / enclave. TresorSGX provides a
  cryptographic algorithm for the Linux Crypto API which is executed in
  the secured container. The cryptographic key material is guarded from
  unauthorised access of unprivileged and privileged components at any
  time. This protects the disk-encryption system from cold-boot and DMA
  attacks on the key material.
Fuzzy Encryption

- A variant of a Fuzzy Vault cryptographic scheme, Bºdesigned forº
Bºencrypting secrets that can be more easily recovered by humans.º
KMIP: Key Mng.Interop.Prot.
KMIP: @[]
A KMIP server stores and controls Managed Objects such as symmetric
and asymmetric keys, certificates, and user defined objects. Clients
then use the protocol to access these objects subject to a security
model that is implemented by the servers. Operations are provided to
create, locate, retrieve and update managed objects.

Each managed object has an immutable Value such as a key block that
contains a cryptographic key. They also contain mutable Attributes
which can be used to store meta data about the keys. Some attributes
are derived directly from the Value, such as the cryptographic
algorithm and length of a key. Other attributes are defined in the
specification for the management of objects such as the Application
Specific Identifier which is usually derived from tape identification
data. Additional identifiers can be defined by the server or client
as need by the application.

Each object is identified by a unique and immutable object identifier
that is generated by the server and is used to Get object values.
Managed objects may also be given a number of mutable but globally
unique Name attribute which can be used to Locate objects.

The types of managed objects that are managed by KMIP include

- Symmetric Keys.
- Public and Private Keys.
- Certificates and PGP Keys.
- Split Keys.
- Secret Data (passwords).
- Opaque Data for client and server defined extensions.

The operations provided by KMIP include

- Create—to create a new managed object such as a symmetric key,
  and return the identifier.
- Get—to retrieve an object's value given its unique identifier.
- Register—to store an externally generated key value.
- Add Attributes, Get Attributes, and Modify Attributes—to
  manipulate the attributes of a managed object.
- Locate—to retrieve a list of objects based on a conjunction of
- Re-Key—to create a new key that can replace an existing key.
- Create Key Pair—create asymmetric keys.
- (Re-)Certify—to certify a certificate.
- Split and Join n of m keys.
- Encrypt, Decrypt, MAC etc. -- cryptographic operations performed on
  the key management server.
- Export and Import keys to other KMIP servers.
- Operations to implement the NIST key life cycle.
HashCat: Pass.Recovery

hashcat is the world's fastest and most advanced password recovery
utility, supporting five unique modes of attack for over 200
highly-optimized hashing algorithms. hashcat currently supports CPUs,
GPUs, and other hardware accelerators on Linux, Windows, and macOS,
and has facilities to help enable distributed password cracking.
Extract Key from Java Keystore
Toplip: Strong File encrypt

Titan: Cli pass.manager
AMD Sec.Processor: Mem.Encryption
Chiness Standards (SM? vs RSA...)
SM2, SM3, SM4 replace RSA, SHA , AES
Post Quantum Guide
BLS Signature Scheme
... Some prominent encryption schemes in literature and the fundamental
reasoning behind their formulation include:

- Boneh — Lynn — Shacham (BLS): Based on the existence of random
  oracles and the intractability of the computational Diffie-Hellman
  problem in a gap Diffie-Hellman group.
- ElGamal: Based on the hardness of the discrete logarithm problem.
- ECDSA: Based on the fact that given a point A on an elliptic curve
  and another point P = n*A, it is difficult to find n.
- Ring signature: Any non-empty subset of a group of n people can
  sign a message without the identity of any of the participants being
  leaked. It is a signature scheme built on other schemes.
- RSA: Factorization of numbers (semi-primes in particular) is hard.
- Schnorr Signature: Based on the hardness of the discrete logarithm problem.
Validate DNSSEC from cli
BitLocker full disk encryption
Pairing primitives
  Bilinear pairings have been used to design ingenious 
  protocols forsuch tasks as one-round three-party key agreement, 
  identity-based encryption,and aggregate signatures. Suitable bilinear 
  pairings can be constructed fromthe Tate pairing for specially chosen 
  elliptic curves.  Thisarticle gives anintroduction to the protocols, 
  Tate pairing computation, and curve selection.
Trusted Signature Pad
PostgreSQL pgcrypto
- Cryptographic functions for PostgreSQL.