BUILDING BLOCKS
Who is Who
(Forcibly incomplete but still quite pertinent list of core cryptographers)
REFS:
-@[https://en.wikipedia.org/wiki/List_of_cryptographers] REF 1: Wikipedia list of Cryptographers
-@[http://pages.swcp.com/~mccurley/cryptographers/cryptographers.html] REF 2: Mc Curley list
- Carl Friedrich Gauss
 @[https://es.wikipedia.org/wiki/Carl_Friedrich_Gauss]
 Developed the modern approach to Modular Arithmetic, the core pilar of cryptography.
 @[https://en.wikipedia.org/wiki/Modular_arithmetic#Computational_complexity]

-ºClaude Shannonº                                                        | - Thomas Jakobsen
  he was not a cryptographer,                                            | @[http://www.mat.dtu.dk/persons/Jakobsen_Thomas/]
  but theºfounder of information theoryº                                 | - Markus Jakobsson
  ºon which "everything" is basedº                                       | @[http://www.markus-jakobsson.com/]
@[https://en.wikipedia.org/wiki/Claude_Shannon]                          | - Stanislaw Jarecki
-ºCharles Babbageº                                                       | @[http://theory.lcs.mit.edu/~stasio/]
@[https://en.wikipedia.org/wiki/Charles_Babbage]                         | - Antoine Joux
-ºAda Lovelaceº                                                          | @[http://www.dmi.ens.fr/equipes/grecc/Membres/joux/pub.html]
@[https://en.wikipedia.org/wiki/Ada_Lovelace]                            | - Marc Joye
-ºRon Rivestº(the 'R' in the RSA)                                        | @[http://www.geocities.com/MarcJoye/]
@[http://theory.lcs.mit.edu:80/~rivest/]                                 | - Ari Juels
-ºAdi Shamirº(the 'S' in the RSA)                                        | @[http://www.rsalabs.com/rsalabs/staff/ajuels/homepage.html]
@[http://www.wisdom.weizmann.ac.il/~shamir/]                             | - Mike Just
- Leonard Adleman (the 'A' in the RSA) @[]                               | @[http://www.scs.carleton.ca/~just/]
-ºWhitfiled Diffieº                                                      | - Kwangjo Kim
  (Diffie-Hillman key exchange protocol)                                 | @[http://vega.icu.ac.kr/~kkj]
@[https://en.wikipedia.org/wiki/Whitfield_Diffie]                        | - Seung-Joo Kim
- Nick Szabo (Bitcoin "co?"inventor),                                    | @[http://dosan.skku.ac.kr/~sjkim]
@[https://en.wikipedia.org/wiki/Nick_Szabo]                              | - Andy Klapper
  came up with the idea of "bit gold" and developed                      | @[http://al.cs.engr.uky.edu/~klapper/andy.html]
  the idea of smart contract                                             | - Lars Knudsen
- @[http://www.weidai.com/] Wei Dai,                                     | @[http://www.ii.uib.no/~larsr/]
  create b-money, mentioned in the  second version                       | - François Koeune
  of the Bitcoin paper                                                   | @[http://www.dice.ucl.ac.be/~fkoeune/koeune.html]
-ºHal Finneyº                                                            | - Kaoru Kurosawa
@[https://en.wikipedia.org/wiki/Hal_Finney_(computer_scientist)]         | @[http://kuro.cis.ibaraki.ac.jp/~kurosawa/]
 ºPGP Developerº Bitcoin co?inventor                                     | - Markus Kuhn
- Paul Kocher                                                            | @[http://www.cl.cam.ac.uk/~mgk25/]
@[http://www.cryptography.com/about_pck.html]                            | - Eyal Kushilevitz
- Moxie Marlinspike                                                      | @[http://www.cs.technion.ac.il/~eyalk/]
  founder of secure messaging organization Signal                        | - Lam Kwok-Yan
- Ross Anderson                                                          | @[http://www.comp.nus.edu.sg/~lamky/]
  @[http://www.cl.cam.ac.uk/users/rja14/],                               | - Pil Joong Lee
  University of Cambridge, Computer Lab.                                 | @[http://wooly.postech.ac.kr/user/pjl/]
- Adam Back                                                              | - Reynald Lercier
@[https://en.wikipedia.org/wiki/Adam_Back]                               | @[http://lix.polytechnique.fr/~lercier/]
 ºproof-of-workºsystem used by several anti-spam systems (and Bitcoin,..)| - Helger Lipmaa
- Don Beaver                                                             | @[http://home.cyber.ee/helger/]
- Mihir Bellare                                                          | - Mark Lomas
@[http://www-cse.ucsd.edu/users/mihir/] ,                                | @[http://www.cl.cam.ac.uk/users/tmal/]
  - professor at the University of California San Diego.                 | - Mike Luby
  - published several seminal papers in the cryp. field                  | @[http://www.icsi.berkeley.edu/~luby/]
    (notably in the area of provable security), many                     | - Philip MacKenzie
    of which were co-written with Phillip Rogaway.                       | @[http://cm.bell-labs.com/who/philmac/]
    and Format-Preserving Encryption.                                    | - Spyros Magliveras
-ºEran Tromerº@[http://www.cs.tau.ac.il/~tromer/] ,                      | @[http://zeus.math.fau.edu/spyros/]
  - ZCash Inventor and founding scientist                                | -
  @[https://z.cash]                                                      | @[http://www-ir.inf.ethz.ch/research/elek/signalverarbeitung/massey.proj_overview]
    privacy-preserving cryptocurrency which implements our               | - Gilles Brassard
    @[http://zerocash-project.org] Zerocash protocol.                    | @[http://www.iro.umontreal.ca/~brassard/]
   - RSA Key Extraction via Low-Bandwidth Acoustic Cryptanalysis         | - Lawrie Brown
  @[http://www.cs.tau.ac.il/~tromer/acoustic/]                           | @[http://mnementh.cs.adfa.oz.au/Lawrie_Brown.html]
    """particularly interested in what happens when cryptographic        | - Johannes Buchmann
     systems meet real world offaulty and leaky computation."""          | @[http://www.informatik.th-darmstadt.de/TI/Mitarbeiter/buchmann.html]
  -  heads the @[http://www.cs.tau.ac.il/~tromer/leisec] Laboratory      | - Mike Burmester
     for Experimental Information Security (LEISec) investigating side   | @[http://www.cs.fsu.edu/~burmester/]
     channel info leakage in computers through physical emanations       | - Christian Cachin
     electric and electromagnetic) and software (e.g.,                   | @[http://theory.lcs.mit.edu/~cc/]
   @[http://www.cs.tau.ac.il/~tromer/papers/cache-joc-20090619.pdf]      | - Jan Camenisch
  -  cache contention in local and cloud computing                       | @[http://www.inf.ethz.ch/personal/camenisc/]
     @[http://www.cs.tau.ac.il/~tromer/cloudsec/]                        | - Ran Canetti
  -@[https://beautyburst.github.io]                                      | @[http://theory.lcs.mit.edu/~canetti/]
     Remote Identification of Encrypted Video Streams                    | - Anne Canteaut
  -  cofoundedºSCIPR Labº@[http://scipr-lab.org]:                   | @[http://www-rocq.inria.fr/codes/Anne.Canteaut/]
     cryptographic zero -knowledge SNARK proof systems-                  | - Florent Chabaud
  -  Interested in blockchain-based cryptographic protocols,             | @[http://www.ens.fr/~chabaud/]
  -  Other research interests:                                           | - Che-Hao (Albert) Chang
     - tamper resilience, homomorphic encryption,                        | @[http://www.cl.cam.ac.uk/~chc1001/]
  -@[http://www.cs.tau.ac.il/~tromer/cryptodev]                          | - David Chaum
     special-purpose code-breaking hardware and various                  | @[http://www.digicash.com/digicash/people/david.html]
     aspects of network and systems security.                            | - Benny Chor
  -  Publications: @[http://www.cs.tau.ac.il/~tromer/publications]       | @[http://www.cs.technion.ac.il/~biham/cgi-bin/faculty.cgi?Chor.Benny]
     publications for more information.                                  | - Andy Clark
                                                                         | @[http://www.primarykey.co.uk/Andy/ajcmain.HTM]
- @[https://en.wikipedia.org/wiki/Steven_M._Bellovin] Steve Bellovin,    | - Lorrie Cranor
   a researcher on computer networking and security.                     | @[http://www.research.att.com/~lorrie/]
   Professor in the Computer Science department at Columbia              | - Claude Crépeau
   University,[1] having previously been a Fellow at AT⅋T Labs           | @[http://www.cs.mcgill.ca/~crepeau/]
   Research in Florham Park, New Jersey.[2][3]                           | - Ivan Damgård
   - In September 2012, Bellovin was appointed Chief                     | @[http://www.daimi.aau.dk/DAIMI/ScientificStaffProfiles/ivan.html]
   Technologist for the United States Federal Trade Commission,          | - George Davida
   replacing Edward W. Felten, who returned to Princeton University      | @[http://www.cs.uwm.edu/faculty/davida/]
- Philippe Béguin                                                        | - Alfredo de Santis
- Josh Benaloh(formerly Cohen)                                           | @[http://www.unisa.it/ads.dir/index.htm]
@[https://www.microsoft.com/en-us/research/people/benaloh/]              | - Giovanni Di Crescenzo
  - pioneered new technologies including:                                | @[http://www-cse.ucsd.edu/users/giovanni/]
    - "cast or spoil" paradigm that brings voters into                   | - Don Davis
      the verification process with minimal burden.                      | @[http://world.std.com/~dtd/]
- OºDaniel Julius Bernsteinº (@[http://cr.yp.to/djb.html])               | - Dorothy Denning
 (@[https://en.wikipedia.org/wiki/Daniel_J._Bernstein] Wikipedia).       | @[http://www.cosc.georgetown.edu/~denning/]
  critic of the leading email and DNS packages of the time,              | - Yvo Desmedt
  Sendmail and BIND. Bernstein attempted to address the situation        | @[http://www.cs.fsu.edu/~desmedt/]
  by designing and implementing secure email and DNS services            | - Cunsheng Ding
  (qmail, ezmlm, djbdns, etc.)                                           | @[http://www.comp.nus.edu.sg/~dingcs]
  - sued the United States Government in 1995 (Bernstein                 | - Hans Dobbertin
  v. United States).                                                     | @[http://www.ruhr-uni-bochum.de/itsc/englisch/index.html]
  - His software received significant attention and no bugs              | - Carl Ellison
    were found in it for eight years.                                    | @[http://www.clark.net/pub/cme/home.html]
  - Designer of theºSalsa20ºstream cipher                                | - Paul Fahn
    in 2005 and submitted it to eSTREAM for                              | @[http://www-isl.stanford.edu/people/fahn/crypto.html]
    review and possible standardization.                                 | - Jean-François Dhem
  - In 2008 published a closely related stream cipher,                   | @[http://www.dice.ucl.ac.be/~dhem/]
    ºChaCha20º.                                                          | @[http://www.bell-labs.com/user/sgwetzel/]
  - Heºalso proposed the elliptic curve Curve25519ºas a basis            | -  Ted Wobber
    for public-key schemes in 2005, and worked as the lead               | @[http://www.research.digital.com/SRC/staff/wobber/bib.html]
    researcher on the Ed25519 version of EdDSA.                          | -  Stefan Wolf
- @[http://www.nlsde.buaa.edu.cn/~kexu/]  Ke Xu                          | @[http://www.inf.ethz.ch/personal/wolf/]
- @[http://www.csie.ncu.edu.tw/~yensm/people/yensm/]  Sung-Ming Yen      | -  Dong-Ho Won
- @[http://www.cs.hut.fi/~ylo/]  Tatu Ylönen                             | @[http://dosan.skku.ac.kr/~dhwon/]
- @[http://www.cs.columbia.edu/~ayoung/]  Adam Young                     | -  Avishai Wool
- @[http://www.cs.columbia.edu/~moti/]  Moti Yung                        | @[http://research.lumeta.com/yash]
- @[http://pscit-www.fcit.monash.edu.au/~yuliang/]  Yulian Zheng         | -  Dongho Won
- @[http://www.cs.ucdavis.edu/~rogaway/]  Phil Rogaway                   | @[http://dosan.skku.ac.kr/~dhwon/]
- @[http://www.cs.nyu.edu/~rubin/]  Avi Rubin                            | -  Rebecca Wright
- Steven Rudich                                                          | @[http://www.research.att.com/info/rwright/]
@[http://www.cs.cmu.edu/afs/cs.cmu.edu/user/rudich/www/home.html]        |
- @[http://tcslab.csce.kyushu-u.ac.jp/~sakurai/]  Kouichi Sakurai        | - Ueli Maurer
- @[http://tsk-www.ss.titech.ac.jp/~tsato/index-e.html]  Takashi Satoh   | @[http://www.inf.ethz.ch/personal/maurer/]
- @[http://www.mi.informatik.uni-frankfurt.de/]  Claus-Peter Schnorr     | - Kevin McCurley
- @[http://www.digicash.com/~berry/]  Berry Schoenmakers                 | @[http://www.swcp.com/~mccurley/index.html]
- @[http://www.cs.uow.edu.au/people/jennie/]  Jennifer Seberry           | - Robert J. McEliece
                                                                         | @[http://www.systems.caltech.edu/EE/Faculty/rjm/]
                                                                         | - Benny Pinkas
| - Joan Feigenbaum                                                      | @[http://www.wisdom.weizmann.ac.il/~bennyp/]
| @[http://www.cs.yale.edu/homes/jf/home.html]                           | - David Pointcheval
| - Niels Ferguson                                                       | @[http://www.dmi.ens.fr/~pointche/]
| @[http://niels.ferguson.net]                                           | - Thomas Pornin
| - Marc Fischlin                                                        | @[http://www.dmi.ens.fr/~pornin/index.html.en]
| @[http://www.mi.informatik.uni-frankfurt.de/people/marc/marc.html]     | - Guillaume Poupard
| - Yair Frankel                                                         | @[http://www.dmi.ens.fr/~poupard/]
| @[http://www.cs.sandia.gov/~yair]                                      | - Bart Preneel
| - Matt Franklin                                                        | @[http://www.esat.kuleuven.ac.be/~preneel/]
| @[http://www.cs.ucdavis.edu/~franklin/]                                | - Jean-Jacques Quisquater
| - Peter Gemmell                                                        | @[http://www.dice.ucl.ac.be/crypto/jjq.html]
| @[http://www.cs.sandia.gov/~psgemme]                                   | - Tal Rabin
| - Rosario Gennaro                                                      | @[http://theory.lcs.mit.edu/~talr/]
| @[http://www.research.ibm.com/people/r/rosario/]                       | -  Omer Reingold
| - Ian Goldberg                                                         | @[http://www.wisdom.weizmann.ac.il/~reingold/]
| @[http://www.cs.berkeley.edu/~iang/]                                   | -  Mike Reiter
| - Oded Goldreich                                                       | @[http://www.research.att.com/~reiter/]
| @[http://www.wisdom.weizmann.ac.il/~oded/]                             | -  Ali Aydin Selcuk
| - Shafi Goldwasser                                                     | @[http://www.csee.umbc.edu/~aselcu1/]
| @[http://theory.lcs.mit.edu/~shafi/]                                   | -  Alan Sherman
| - Li Gong                                                              | @[http://www.cs.umbc.edu/~sherman/]
| @[http://java.sun.com/people/gong/]                                    | -  English
| - Wei Dai (Crypto++)@[https://en.bitcoin.it/wiki/Wei_Dai']             | @[http://www.ecip.tohoku.ac.jp/Shizuya-Lab/index.html]
| - Mark Goresky                                                         | -  Adam Shostack
| @[http://www.math.ias.edu/~goresky/home.html]                          | @[http://www.homeport.org/~adam/]
| - Shai Halevi                                                          | -  Victor Shoup
| @[http://theory.lcs.mit.edu/~shaih/]                                   | @[http://www.cs.wisc.edu/~shoup/]
| - Helena Handschuh                                                     | -  Tom Shrimpton
| @[http://www-inf.enst.fr/~research/theses/handschuh.gb.html]           | @[http://www.ece.ucdavis.edu/~teshrim/]
| - Carlo Harpes                                                         | -  Alice Silverberg
| @[http://www.isi.ee.ethz.ch/~harpes/]                                  | @[http://www.math.ohio-state.edu/~silver/]
| - Martin Hellman (pubs only)                                           | -  Joseph H. Silverman
| @[ftp://isl.stanford.edu/pub/hellman/reports/]                         | @[http://www.math.brown.edu/~jhs]
| - Amir Herzberg                                                        |   by the NSA, who evidently knew about it as well.
| @[http://amir.herzberg.name/index.html]                                | - John R. Black
| - Frederic Huygens                                                     | @[http://www.cs.colorado.edu/~jrblack/papers.html]
| @[http://www.ulb.ac.be/di/scsi/defscsi.html]                           | - Simon Blackburn
| - Hideki Imai                                                          | @[http://www.cs.rhbnc.ac.uk/~simonb/]
| @[http://imailab-www.iis.u-tokyo.ac.jp/Members/imai-e.html]            | - Matt Blaze
| - Russell Impagliazzo                                                  | @[ftp://ftp.research.att.com/dist/mab/]
| @[http://www-cse.ucsd.edu/users/russell/]                              |   (corporate @[http://www.research.att.com/info/mab/] here)
| - David McGrew                                                         | - Daniel Bleichenbacher
| @[http://www.mindspring.com/~dmcgrew/dam.htm]                          | @[http://www.bell-labs.com/user/bleichen/]
| - Alfred Menezes                                                       | - Manuel Blum
| @[http://cacr.math.uwaterloo.ca/~ajmeneze/]                            | @[http://http.cs.berkeley.edu/~blum/]
| - Ralph Merkle                                                         | - Carlo Blundo
| @[http://merkle.com/merkle]                                            | @[http://www.unisa.it/carblu.dir/start.html]
| - Daniele Micciancio                                                   | - Dan Boneh
| @[http://theory.lcs.mit.edu/~miccianc/]                                | @[http://www.cs.princeton.edu/~dabo/]
| - Chris Mitchell                                                       | - Antoon Bosselaers
| @[http://isg.rhbnc.ac.uk/cjm/Chris_Mitchell.htm]                       | @[http://www.esat.kuleuven.ac.be/~bosselae/]
| - Shiho Moriai                                                         | - Joan F. Boyar (formerly Joan Plumstead)
| @[http://info.isl.ntt.co.jp/~shiho/]                                   | @[http://www.imada.sdu.dk/~joan/]
| - Sean Murphy                                                          | - Colid Boyd
| @[http://www.cs.rhbnc.ac.uk/~sean/]                                    | @[http://www.fit.qut.edu.au/~boyd/]
| - Clifford Neumann                                                     | - Stefan Brands,
| @[http://www.isi.edu/people/bcn/]                                      | @[https://en.wikipedia.org/wiki/Stefan_Brandr]
| - Mats Näslund                                                         |   - cryptographer specialized in electronic cash and digital identity.
| @[http://www.nada.kth.se/~matsn/matsn_homepage/research.html]          |   - best known for designing Microsoft's U-Prove protocols .
| - Moni Naor                                                            | -  Markus Stadler
| @[http://www.wisdom.weizmann.ac.il/people/homepages/naor/index.html]   | @[http://www.ubs.com/cgi-bin/framer.pl?/webclub/ubilab/e_index.htm/]
| - Harald Niederreiter                                                  | -  Frank Stajano
| @[http://www.iinform.oeaw.ac.at/Niederreiter.html]                     | @[http://www.cl.cam.ac.uk/~fms27/]
| - Valtteri Niemi                                                       | -  Jacques Stern
| @[http://www.uwasa.fi/~vni/]                                           | @[http://www.dmi.ens.fr/~stern/index.html]
| - Luke O'Connor                                                        | -  Anton Stiglic
| @[http://www.zurich.ibm.com/~oco/]                                     | @[http://crypto.cs.mcgill.ca/~stiglic]
| - Andrew Odlyzko                                                       | -  Doug Stinson
| @[http://www.research.att.com/~amo/]                                   | @[http://cacr.math.uwaterloo.ca/~dstinson/index.html]
| - Kazuo Ohta                                                           | -  Yuriy Tarannikov
| @[http://www.ohta.is.uec.ac.jp/k_ohta/]                                | @[http://liapunov.inria.msu.ru/PERSONAL/Taran/index.html]
| - Rafail Ostrovsky                                                     | -  Stafford Tavares
| @[http://www.cs.ucla.edu/~rafail/]                                     | @[http://http.ee.queensu.ca:8000/www/dept/facpages/set.html]
| - Christof Paar                                                        | -  Yiannis Tsiounis
| @[http://www.crypto.rub.de/en_paar.html]                               | @[http://www.ccs.neu.edu/home/yiannis/]
| - Torben Pryds Pedersen                                                | -  Jeroen van de Graaf
| @[http://cryptomathic.aau.dk/~tpp/]                                    | @[http://www.iro.umontreal.ca/people/jeroen/index.htm]
| - Rene Peralta                                                         | -  Joos Vandewalle
| @[http://www.cs.uwm.edu/faculty/peralta/index.html]                    | @[http://www.esat.kuleuven.ac.be/cosic/vdwalle.html]
| - Giuseppe Persiano                                                    | -  in English
| @[http://www.dia.unisa.it/~giuper]                                     | @[http://www.ens.fr/dmi/equipes_dmi/grecc/vaudenay/index_en.html]
| - Holger Petersen                                                      | -  David Wagner
| @[http://www.dmi.ens.fr/~petersen/]                                    | @[http://www.cs.berkeley.edu/~daw/]
| - Birgit Pfitzmann                                                     | -  Susanne Wetzel
| @[http://www.semper.org/sirene/people/birgit/info.birgit.html]         | - Thomas Beth
| - Josef Pieprzyk                                                       |   Albrecht Beutelspacher,
| @[http://www.cs.uow.edu.au/people/josef/homepage.html]                 | @[http://www.beutelspacher.info/]
| - Tom Berson, Advisory Board Member                                    |   mathematic "broadcaster"
| @[http://www.anagram.com/berson/]                                      | - Eli Biham: Biham
|   and Chief Security Advisor at Saleforce.com since 1999 foundation    | @[http://www.cs.technion.ac.il/~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
External Links
@[https://en.wikipedia.org/wiki/Index_of_cryptography_articles]
@[https://www.crypto101.io/]
@[https://cryptography.io/en/latest/]
@[https://crypto.stackexchange.com]
@[https://iancoleman.io/]
 Ian Coleman JS Tools for:
   - BIP39 Mnemonic Code Converter
   - Blockchain Blocksize/SAFE Network Attack/...
   - Group Size Calculator
   -  Cost Benefit Calculator
   - Multisig Tool
   - ...
-@[https://keccak.team/index.html]
  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)
- rootshell.be: 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:
@[http://www.scipr-lab.org/]
@[https://github.com/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º
- NumberTheory.org Web
@[http://numbertheory.org]
- Number Theory and its History
@[https://archive.org/stream/NumberTheoryItsHistory/Ore-NumberTheoryItsHistory]
- The Prime Pages
@[http://primes.utm.edu]
- NTL: A Library for Doing Number Theory
@[http://www.shoup.net/ntl]

Bibliography/Books
- Crypto101
@[https://www.crypto101.io/]
- Encyclopedia of Cryptography and Security
@[https://www.springer.com/us/book/9781441959058]
-
@[https://en.wikipedia.org/wiki/List_of_important_publications_in_cryptography]
- Handbook of Applied Cryptography, by Menezes, van Oorschot, and Vanstone.
@[http://www.cacr.math.uwaterloo.ca/hac/]
- Intro to Crypto.
@[https://www.cs.umd.edu/~waa/414-F11/IntroToCrypto.pdf]
- "Applied Cryptography", Bruce Schneier, ISBN 0-471-11709-9
Concepts
- º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
@[https://twitter.com/fermatslibrary/status/969935429712666625]
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
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
ºSP-Networksº:
 - 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|

Padding:
@[https://en.wikipedia.org/wiki/Padding_(cryptography)]
- 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
  "BUTs":
   - 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º
AES
-ºº: 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
    @[https://calomel.org/aesni_ssl_performance.html] 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

  ºResults:º
  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, ...)

  REAL-WORLD:
    - 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)
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
            ENCRYPTION FROM PEER 1 TO PEER 2
            --------------------------------
        | Encrypt with |                | Decrypt with |
Plain → |    Peer 2    | → CypherText → |   Peer 2     | → Plain
text    | public  key  |                | private  key |   text


            ENCRYPTION FROM PEER 2 TO PEER 1
            --------------------------------

        | 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
UUID: c00e87d4-ec8e-42fc-9954-34e919d01d59
- 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º

-ºTHE TUPLE (SIGNING ALGORITHM, VERIFICATION ALGORITHM, KEY GENERATION ALGORITHM)   º
 ºIS KNOWN AS THE DIGITAL SIGNATURE SCHEMA                                          º
 º(THE SET OF "ARROWS" IN THE NEXT SCHEMA PLUS THE NON-DISPLAYED PROCEDURE TO       º
 º 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"
      @[https://arxiv.org/abs/1501.00447]
      """... 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. """

- DSA:
  -ºcryptographic algorithmº that generates keys, signs data,
  and verifies signatures.
  - based on the mathematical concept of modular exponentiation and the
    discrete logarithm problem.
  @[https://en.wikipedia.org/wiki/Digital_Signature_Algorithm]
  - DSS/DSA:
    - DSA can use lot of "tunable switches" like the hash-funcs,
      (L, N)-param-length,... whileº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),...
    - US government standard for authentication of electronic documents.
      - It is a variant of the Schnorr and ElGamal signature schemes.
       (REF: "Applied Cryptography", Bruce Schneier, ISBN 0-471-11709-9)
    - 1994 Approbed by the US National Institute of Standards and Tech(NIST)
      and specified in Federal Information Processing Standard (FIPS) 186.
    - 2013 FIPS-4: @[https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf]
  RºWARN:ºSSH decided to drop DSS/DSA keys in favor of RSA due to "inherit weakness"º
  @[https://www.gentoo.org/support/news-items/2015-08-13-openssh-weak-keys.html]
    - See also critics to DSS @:
    @[http://groups.csail.mit.edu/mac/classes/6.805/articles/froomkin-metaphor/partIAB.html]

- ECDSA: DSA based on Eliptic curves (vs modular exponentiation)

- RSA:
  - RSA refers to the initials of
    Ron Rivest, Adi Shamir, and Leonard Adleman.
  - DSA was designed as an encryption algorithm while RSA looks at the
    difficulty of factoring numbers as the main aspect of its development.

DSA/ECDSA/RSA compared
@[https://stackoverflow.com/questions/2841094/what-is-the-difference-between-dsa-and-rsa]
@[https://web.archive.org/web/20140212143556/http://courses.cs.tamu.edu:80/pooch/665_spring2008/Australian-sec-2006/less19.html]

º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º)
  Compute:
  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
ECDSA
- Used, amongst many others, by Bitcoin/Ethereum/... to sign TXs

See also:
@[https://tools.ietf.org/html/rfc6979]
Deterministic Usage of the Digital Signature Algorithm (DSA) and
Elliptic Curve Digital Signature Algorithm (ECDSA)
- 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

ºSchnorr("ed25519") vs ECDSAº
@[http://ed25519.cr.yp.to/]
@[http://blog.siphos.be/2015/08/switching-openssh-to-ed25519-keys/]
@[http://chneukirchen.org/blog/archive/2014/02/the-road-to-openssh-bliss-ed25519-and-the-identitypersist-patch.html]
- designed by prominent cryptographer Daniel J. Bernstein
- cryptosystem powering Bitcoin, Ethereum, ...
- elliptic curve implementation
- more optimal and secure design schemes
- Extracted from @[https://ripple.com/dev-blog/curves-with-a-twist/]
  ...  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
  @[http://www.secg.org/collateral/sec2_final.pdf]

- 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|
@[http://safecurves.cr.yp.to/disc.html]
- 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.
  Benchmarking:
  - Raw test results
  - Benchmark source code

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

- Extracted from @[https://www.mail-archive.com/cypherpunks@cpunks.org/msg02419.html]
  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
    @[http://nakedsecurity.sophos.com/2012/10/25/sony-ps3-hacked-for-good-master-keys-revealed/]
    ...  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
  @[http://ieeexplore.ieee.org/xpl/articleDetails.jsp?reload=true&arnumber=4908440]
    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.
  @[http://www.cs.bris.ac.uk/Publications/pub_master.jsp?id=2001023]

  - Independent verification and combining:
    Another advantage of Schnorr is related to threshold signatures
  - ECDSA can create threshold signatures, but requires multi-party computation
   @[http://en.wikipedia.org/wiki/Secure_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.
Dig.Sig.History

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.
      @[http://archive.numdam.org/item/MSMF_1978__57__1_0/]

1985: ElGamal signature scheme by Taher Elgamal,
      later adopted by the DSS/DSA standard by
      US Guvernamental agencies.

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 @[https://link.springer.com/chapter/10.1007%2F3-540-39799-X_31]
      1987 @[https://www.jstor.org/stable/2007884?seq=1] 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


1994: First DSA schema approved by DSS (FIPS 186-1)
      DSA is based on elGamal.

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
    @[https://www.ietf.org/rfc/rfc4050.txt]


2009: PAdES: PDF Advanced Electronic Signatures
    @[https://en.wikipedia.org/wiki/PAdES]

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: secg.org SEC 1: Elliptic Curve Cryptography
    @[http://www.secg.org/sec1-v2.pdf]
2010: secg.org SEC 2: Recommended Elliptic Curve Domain Parameters
    @[http://www.secg.org/sec2-v2.pdf]
2013: secg.org 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.
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?:
@[https://stackoverflow.com/questions/10696223/reason-for-5381-number-in-djb-hash-function]
  A: """ 5381 is just a number that, in testing, resulted in
  fewer collisions (@[http://en.wikipedia.org/wiki/Collision_%28computer_science%29] and
  better avalanching(@[http://en.wikipedia.org/wiki/Avalanche_effect]).
  You'll find "magic constants" in just about every hash algo.
SHA-3
@[https://en.wikipedia.org/wiki/SHA-3]
SHA-3 is a subset of the broader cryptographic primitive family Keccak
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

message
    → 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
Diffie-Hellman
Diffie-Hellman
ºº: 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)
@[https://en.wikipedia.org/wiki/Initialization_vector]
- 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)
@[https://en.wikipedia.org/wiki/Salt_(cryptography)]
- 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 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 must not be repeated, 
  andº ºalso they must be cryptographically random to be secure.º

Nonce (session establishment)
@[https://en.wikipedia.org/wiki/Cryptographic_nonce]
- 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
- @[https://en.wikipedia.org/wiki/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
- Two main categories, depending on the entropy content of the secret value
  which determines how many differnet possible values the secret value can
  take:
  - input secret is user-supplied (low entropy): Key d.f will require lot
    of computing resources to avoid attackers to just compute all possible
    (scrypt)
  - 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, @[http://eprint.iacr.org/2010/264] requires high entropy initial
  input key.
- Argon2Id(@[https://en.wikipedia.org/wiki/Argon2] 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.
MultiSig vs threshold Signature Schemes
NOTE:
- 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º│                                                   │
├────────────────┘                                                               │ ├────────────────────────┘                                                   │
│@[https://en.wikipedia.org/wiki/Multisignature]                                 │ │@[http://en.wikipedia.org/wiki/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         │
│    @[https://www.blockstream.com/2015/08/24/treesignatures/]                   │ │  "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º│                                                           │
├─────────────────┘                                                           │
│@[https://en.wikipedia.org/wiki/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º│                                                          │
├────────────────┘                                                          │
│@[https://en.wikipedia.org/wiki/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º*│                                              │
├─────────────────────────────┘                                              │
│@[https://en.wikipedia.org/wiki/Blind_signature]                            │
│- Blind signature schemes exist for many public key signing protocols       │
│  Blind RSA signatures, Blind ECDSA signatures,                             │
│- Java implementation:                                                      │
│  @[https://archive.is/20130416090835/http://www.maniora.pl/?p=101"]        │
│                                                                            │
│- 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º│                              │
├─────────────────────────────────────┘                              │
│@[https://link.springer.com/chapter/10.1007/11745853_17]            │
│ 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:
@[https://medium.com/@aurelcode/cryptographic-accumulators-da3aa4561d77]
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.

Zero Probe Knowledge
@[https://blog.plan99.net/vntinyram-7b9d5b299097]
@[https://medium.com/@VitalikButerin/quadratic-arithmetic-programs-from-zero-to-hero-f6d558cea649]
- 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
@[https://en.wikipedia.org/wiki/Homomorphic_encryption]
-http://enigma.media.mit.edu/
-http://www.xataka.com/privacidad/enigma-renace-el-cifrado-homomorfico-y-el-blockchain-como-base-de-una-internet-mas-privada
Data integrity
BºHash chainº
@[https://en.wikipedia.org/wiki/Hash_chain]
  - non-repudiable probe of data chronology
    doc1 → hash → has1 ─┬→ hash → has2 ─┬→ hash → has3 ─┬→ hash
                   doc2─┘         doc3 ─┘         doc4 ─┘
BºMerkle treeº
@[https://en.wikipedia.org/wiki/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,...)
   @[https://blog.ethereum.org/2019/12/30/eth1x-files-state-of-stateless-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
@[https://en.wikipedia.org/wiki/Shamir%27s_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
(Remote)Authentication
Challenge-response
- 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
  challenge.
Authenticated Encryption (AE)
AE 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:

 Encryption
     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).
 Decryption
     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)
JS?
See also: @[https://jwt.io/]
- online JWT debugger to decode, verify and generate JWT,
  detailed list of libraries (Java, Python, C#, Rust,...)
  and other useful info

ºJWT online Debuggerº
- decode, verify, and generate JWTs.
@[https://jwt.io/#debugger]


JSON Web Token (JWT)
@[https://tools.ietf.org/html/rfc7519]
- 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)
  │  │
  │  │
  │ ºPAYLOADº
  │  - 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
  │
 ºHEADERº
  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
  encrypted.

- 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.


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



JSON Web Signature (JWS)
@[https://tools.ietf.org/html/rfc7515]
   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)
@[https://tools.ietf.org/html/rfc7516]
   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)
@[https://tools.ietf.org/html/rfc7517]
   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)
@[https://tools.ietf.org/html/rfc7518]
   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.

Implementations
- @[https://www.npmjs.com/package/node-jose]
  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" });
OAuth
@[https://tools.ietf.org/html/rfc6749]
@[https://alexbilbie.com/guide-to-oauth-2-grants/]

º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
          @[tools.ietf.org/html/rfc6479#section-3.3]

ºINITIAL (only-once) PRESETUP:º
  Register server app to OAuth2 Service provider.
  Write down Gº'client.id' 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º
                            Gºclient.secretº
   App Dev ← App Dev      : write in safe place

ºOAuth GRANTS TYPESº
┌───────────────────────────────────────────────────┐┌──────────────────────────────────────┐┌──────────────────────────────────┐
│º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. Def.to 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:
-@[https://oauth.net/2/]
OpenID
OpenID
@[https://stackoverflow.com/questions/1087031/whats-the-difference-between-openid-and-oauth]
@[https://security.stackexchange.com/questions/44611/difference-between-oauth-openid-and-openid-connect-in-very-simple-term/130411#130411]
@[https://en.wikipedia.org/wiki/OpenID#OpenID_vs._pseudo-authentication_using_OAuth]
    """
    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
@[https://github.com/dexidp/dex]
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
REF:
@[https://spin.atomicobject.com/2016/05/30/openid-oauth-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
  reuse.

- 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.
ºOpenIDº
- 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.

OpenID FLOW:
user → id_provider01: request OpenID account
user ← id_provider01: OpenID account
                      ^^^^^^^^^^^^^^
                      technically it's a URL
                      (e.g. alice2016.myIDprovider.org)

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
                              id_provider01
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)

ºOAuth2º
- 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.

ºSAMLº
- 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)
                                response_url
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
(assertion)

Authorization?      Yes                No                  Yes

Authentication?     Pseudo-auth        Yes                 Yes

Year created        2005               2006                2001

Current version     OAuth2             OpenID              SAML 2.0
                                       Connect

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


SECURITY RISKS      Phishing[1]        Phishing[1]         XML Signature
                                                           Wrapping to
                                                           impersonate
                                                           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
X.509_Format
@[https://en.wikipedia.org/wiki/X.509]

(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
  valid,
- º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:
  Version#
  Serial Number
  Signature algorithm
  Issuer name
  Validity period
  Subject name
  Subject PK Info
  Issuer ID#
  Subject ID#
  Extensions
  ──────────────────
  CA Signature
- "Extended attributes" (Used by different services)
ºView x509 contents:º
$ openssl x509 -text -in myCert.pem
                                (P)rivacy (E)nhanced (M)ail
openSSL
│ºExternal Refsº
│@[https://www.openssl.org/docs/manmaster/man1/]
│@[https://www.ietf.org/rfc/rfc5280.txt] X.509 PKI
│- The Most Dangerous Code in the World: Validating SSL Certs ...:
│@[https://www.cs.utexas.edu/~shmat/shmat_ccs12.pdf]


│º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="mydomain.com"
│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.
│ºVERIFY PRIVATE KEY:º
│$ 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


│ºSelf-Signed-Certº
│ºworking on Chrome/Java/...º
│REF:
│- chrome deprecates subject cn matching]
│@[https://textslashplain.com/2017/03/10/chrome-deprecates-subject-cn-matching/]
│- Fixing Fixing Chrome 58+ [missing_subjectAltName] with openssl&S.S.certs
│@[https://alexanderzeitler.com/articles/Fixing-Chrome-missing_subjectAltName-selfsigned-cert-openssl/]
│- getting-chrome-to-accept-self-signed-localhost-certificate
│@[https://stackoverflow.com/questions/7580508/getting-chrome-to-accept-self-signed-localhost-certificate/43666288#43666288]
│ºcreate_root_cert_and_key.shº
│ |#!/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

│ºcreate_certificate_for_domain.shº
│ |#!/usr/bin/env bash
│ |
│ |if [ -z "$1" ]; then
│ |  echo "Ussage: $0 myDomain.com"
│ |  echo "           ^^^^^^^^^^^^"
│ |  echo "    # alt1     wildcard"
│ |  echo "        $0 www.myDomain.com"
│ |  echo "           ^^^^^^^^^^^^^^^^"
│ |  echo "    # alt2 non-wildcard"
│ |  exit 1;
│ |fi
│ |if [ ! -f rootCA.pem ]; then echo 'no rootCA.pem detected. Please, run create_root_cert_and_key.sh 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]
│ |DNS.1 = $COMMON_NAME
│ |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
│
│ºUssage:º
│$ ./create_root_cert_and_key.sh        # ← STEP 01: create root Auth cert
│
│$ ./create_certificate_for_domain.sh \ # ← STEP 02
│   mysite.com                          #   Alt 1
│   www.mysite.com www.mysite.com       #   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
│
│PER ←→ DER
│$ 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º
│- 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 www.mywebsite.com:443 \
│   -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 www.mywebsite.com -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:http://example.com/intermediate.c
│ ^^^^^^^^^^^^^^^^^^^^^
│ 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,...)
│
│REVOKE A CERTIFICATE:
│$ cd ~/ca
│$ openssl ca -config intermediate/openssl.cnf \
│ º-revokeº \
│  intermediate/certs/bob@example.com.cert.pem
│
│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:http://domain1.com/intermediate.crl.pem
│→ ...

Related projects:
@[https://jamielinux.com/docs/openssl-certificate-authority/index.html]
Certs Transparency
@[https://www.certificate-transparency.org/]
(See also Trillian
- 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.
Cert.Authorities (CAs)
Let's Encrypt
@[https://letsencrypt.org/]
- free, automated, and open Certificate Authority.

@[https://certbot.eff.org/about/]
- 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.
cacert.org
@[http://www.cacert.org]
- Mission Statement: create a Non-Profit Certificate Authority;
                     alternative to the commercial CAs.
 make-ca
(KISS CA)
@[https://github.com/djlucas/make-ca/blob/master/make-ca]
-  Simple scripts around OpenSSL to create a local certificat authority
TLS Related
OCSP
@[https://en.wikipedia.org/wiki/Online_Certificate_Status_Protocol]

- 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"""

º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'
                        --------------
                        Alice_cert.serial_number
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.
rigi


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
@[https://en.wikipedia.org/wiki/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º
  Rºrepresentationº
  - 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
  GCM@[https://en.wikipedia.org/wiki/Galois/Counter_Mode]
  - 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
@[https://en.wikipedia.org/wiki/Kerberos_(protocol)]
@[https://web.mit.edu/Kerberos/]
- 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
LDAP
@[https://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol]

- 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, ...

ºHistoryº
- 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
                       └───────────┘
                        Relative
                        Distinguished
                        Name
            └───────────────────────┘
             Distinguished Name (DN)

      Example entry in LDIF format
      (LDAP Data Interchange Format)
                                           (Mentally)
   ┌─→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: john@example.com                         │      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.

ºUsageº
- two common styles of naming:
  - top level objects are the c= (country) object
    Ex:
                    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
    Ex:
    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:
- @[https://www.ietf.org/rfc/rfc2247.txt]
    This document defines an algorithm by which a name registered with
    the Internet DNS can be represented as an LDAP distinguished name.

    subdomain.com  ←→  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

- @[https://www.ietf.org/rfc/rfc1779.txt]
    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

GPG
Gnu Privacy Guard
Sym file
encrypt
ºEncrypt/Decrypt from/to fileº
$ gpg --symmetric plainTextFile --output myEncFile.gpg  # ← Encrypt
$ gpg --decrypt -o -                                    # ← Decrypt to STDOUT
$ shred -n 2 -z -v plainTextFile                        # ← Safe delete

ºEncrypt/Decrypt from/to STDIN/STDOUTº
$ echo "MySecret Text" | gpg -c --batch --passphrase 1234 | base64 -w 0                    # ← Encrypt from STDIN
jA0EBw...u+8ykK
$ echo "jA0EBw...u+8ykK" | base64 -d | gpg -d --batch --passphrase 1234 2˃/dev/null
MySecret Text


- multi-level
example script:
TMP_LEVEL1=/tmp/level1Ciphered.base64 ; DECODE_LEVEL1=decodedlevel1  ; PASS_LEVEL1=/tmp/myPassLevel1
TMP_LEVEL2=/tmp/level2Ciphered.base64 ; DECODE_LEVEL2=decodedlevel2  ; PASS_LEVEL2=/tmp/myPassLevel2
TMP_LEVEL3=/tmp/level3Ciphered.base64 ; DECODE_LEVEL3=decodedlevel3  ; PASS_LEVEL3=/tmp/myPassLevel3
(
cat ˂˂ EOF
 secrets level 1
EOF
) | gpg -c --batch  --passphrase ${PASS_LEVEL1} | base64 ˃ ${TMP_LEVEL1}


(
cat ${TMP_LEVEL1}

cat ˂˂ EOF
 secrets level 2
EOF
) | gpg -c --batch  --passphrase ${PASS_LEVEL2} | base64 ˃ ${TMP_LEVEL2}


(
cat ${TMP_LEVEL2}

cat ˂˂ EOF
 secrets level 3
EOF
) | gpg -c --batch  --passphrase ${PASS_LEVEL3} | base64 ˃ ${TMP_LEVEL3}

cat ${TMP_LEVEL3}  | base64 -d | gpg -d --batch --passphrase ${PASS_LEVEL3} ˃ $DECODE_LEVEL3
cat $DECODE_LEVEL3 | base64 -d | gpg -d --batch --passphrase ${PASS_LEVEL2} ˃ $DECODE_LEVEL2
cat $DECODE_LEVEL2 | base64 -d | gpg -d --batch --passphrase ${PASS_LEVEL1} ˃ $DECODE_LEVEL1

echo "---- DECODED LEVEL 3 ------"
cat $DECODE_LEVEL3
echo "---- DECODED LEVEL 2 ------"
cat $DECODE_LEVEL2
echo "---- DECODED LEVEL 1 ------"
cat $DECODE_LEVEL1

-Priv.key mng
REF:
ºNEW KEYPAIRº
$ gpg --gen-key       # 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 PUBLIC KEYSº
/home/juven/.gnupg/pubring.gpg
------------------------------
pub   1024D/C6EED57A 2010-01-13
uid                  OldMcDonalds˂old.mcdonalds@farm.com˃
sub   2048g/D704745C 2010-01-13
      ^^^^  ^^^^^^^^
     length   keyid

$ gpg2 --list-secret-keys #      ← ºLIST  KEYSº
/home/juven/.gnupg/secring.gpg
------------------------------
sec   1024D/C6EED57A 2010-01-13
uid                  OldMcDonalds
ssb   2048g/D704745C 2010-01-13


$ gpg2 -ab temp.java #            ← ºSIGNING A FILEº
           ^^^^^^^^^                -a create ASCII armored output
           output to temp.java.asc  -b make detached signature

$ gpg2 --verify temp.java.asc #   ← ºVerify new signatureº


KEYSERVER="hkp://pool.sks-keyservers.net"
$ gpg2 --keyserver ${KEYSERVER}   ← º"PUSH" PUB.KEYº
  \ --send-keys C6EED57A
$ gpg2 --keyserver ${KEYSERVER}   ← º"PULL" PUB.KEYº
  \ --recv-keys C6EED57A

ºEXPIRE A KEYº
$ gpg2 --edit-key A6BAB25C
... Secret key is available.
pub  2048R/A6BAB25C  created: ...  expires: ...
     trust: ultimate      validity: ultimate
sub  2048R/DD289F64  created: ...  expires: ...
     Juven Xu (for testing) ˂test@juvenxu.com˃
...
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) ˂test@juvenxu.com˃

gpg˃ Oºexpireº
→ ...
→ Please specify how long the key should be valid.
        0 = key does not expire
      ˂n˃ = key expires in n days
     ...
gpg> Oºsaveº
(push again to publick hkp serser)

ºMaven problem with Signature SUBKEYsº
- Some PGP tools generate a sub-signing priv.key
  splited from the primary key (seed key).
- Maven and other only recognise the primary key,
  not subkeys. Deleting Singing subkey will force
  GPG to use the primary key.
$ gpg2 --edit-key A6BAB25C
...
pub  2048R/A6BAB25C  created:... usage: SC
                   trust: ultimate      validity: ultimate
sub  2048R/DD289F64  created:... ºusage: E  # E:Encryptionº
sub  2048R/8738EC86  created:... ºusage: S  # S: Signing  º

gpg> Oºkey 2º (index start at 0)
...
gpg> Oºdelkeyº  # (or ºrevokeº if already published)
gpg> Oºsaveº
S/MIME:
- Uses Crypto.Message (PKCS#7) and pub.key infraestructure for encryption and signing
- PGP/SMIME EFail vulneravility
Off-The-Record
 Messaging(OTR)
@[https://en.wikipedia.org/wiki/Off-the-Record_Messaging]
- 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
@[http://www.eweek.com/security/dmarc-email-security-adoption-soars-as-us-government-deadline-hits]]
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
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.
    @[https://en.wikipedia.org/wiki/ISO/IEC_7816]
OASIS STANDARDS
XAdES
@[https://www.w3.org/TR/XAdES/]
XML Advanced Electronic Signatures (XAdES)

DSS
OASIS Digital Signature Services (DSS)
@[https://ec.europa.eu/cefdigital/wiki/pages/viewpage.action?pageId=46992515]
DSS (Digital Signature Services) is an º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.


AES
@[https://en.wikipedia.org/wiki/Advanced_electronic_signature]
-PAdES(PDF)_format
@[https://en.wikipedia.org/wiki/PAdES]
-XAdES(XML)_format
@[https://en.wikipedia.org/wiki/XAdES]
  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.
-CAdES(CMS)_format
@[https://en.wikipedia.org/wiki/CAdES_(computing)]
@[https://en.wikipedia.org/wiki/Cryptographic_Message_Syntax]
  Extensions to 'Cryptographic Message Syntax'
- ASiC_format
@[https://en.wikipedia.org/wiki/Advanced_electronic_signature]
  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.
X.509 TimeStamp Protocol
@[https://tools.ietf.org/html/rfc3161]

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

- 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
         --------
         type:TimeStampReq

TSA → A: response1
         ---------
         TimeStampResp
           TimeStampToken(TST)

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
Think lib
crypto for
non-experts
@[https://www.infoq.com/news/2018/09/google-tink-cryto-ios-android]
- 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.


WARN: ☞ CRYPTOGRAPHY IS HARD, PROTECTING SECRETS IS (MUCH) HARDER!!!☜

Wallets
Wallet vs Vault
In Vaults, secrets are kept safe until needed by an application.

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 vault. (A vault is a "layer down the stack")

Vaults are generic for any type of app.

Wallets are mostly used for blockchain-like applications.
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
@[https://en.bitcoin.it/wiki/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
@[https://en.bitcoin.it/wiki/CarbonWallet]

- 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
Keepass
@[https://keepass.info/]
- 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
@[https://blog.gridplus.io/lattice1-sdk-and-generalized-signatures-e17da7cf65d7]
Lattice 1:
  generalized "remote ("WiFi",...) signer" for
  cryptocurrencies, digital identity, and more.
  (The priv.key is never transmited outside the hardware,
   unsigned docs come in and signed docs come out)

ºREMOTE SIGNINGº                                     | ºSEPARATING THE SIGNER:º
wallet application technical components:             | STEP 1:
ºUSER INTERFACEº: It interfaces with both            | - let's consider moving TX signer to cloud machine.
  - persisted user data: addresses, TX history,...   |   =˃ you have to store your private key on the cloud
  - network nodes: allow to display account info     | STEP 2:
ºTX BUILDERº    : Applies the network protocol       | -Move TX builder in the cloud too
  to convert parameters (amount, recipient address   |
  , ...) into one or more hashes that make up a TX.  | """In Lattice1 we have separated the protocol and
   Note: in Ethereum, each TX is represented by a    | cryptographic functionality away from the application
     single hash, whereas in Bitcoin each consumed   | layer ... Of course keys are in a secure chip within
     input has its own hash to sign,  there can be   | the Lattice1."""
     one or many inputs per Bitcoin transaction.
ºTX SIGNERº     : sign TX hashes with private key.


ºSECURING COMPONENTS AND SEPARATING CONCERNSº
- The Lattice1 introduces a more usable, 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
- Lattice1 addition:                            and each Safe Card
  - facilitates (wireless) communication app←→Sec.Chip

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


     _       _ _
  __| | __ _(_) |_   _     _   _ ___ ___  __ _  __ _  ___
 / _` |/ _` | | | | | |   | | | / __/ __|/ _` |/ _` |/ _ \
| (_| | (_| | | | |_| |   | |_| \__ \__ \ (_| | (_| |  __/
 \__,_|\__,_|_|_|\__, |    \__,_|___/___/\__,_|\__, |\___|
                 |___/                         |___/

""app wants to pair with a user’s Lattice1 device.""

ºSTEP 1º: Find device by serial number
- find the user's agent based on a serial number.
  (not needed if Lattice1 can connect with the app
   on a local area network).

ºSTEP 2º: Transfer a Secret Code (Out of Band)
Once the app can talk (insecurely) to the Lattice1,
- app generates secret code, signs hash with that code
  using a secp256k1 private key (is different to the EC25519
  used for encryption/decription)
- User presses "Pair" button:
- Appt sends a message to Lattice1 device ºrequesting pairingº start
- Lattice1 displays a place for the user to enter
  the same code that is displayed on the application.

- With correct code lattice1 can recover secp256k1 public key
  used to sign the hash and stores both that and the curve25519
  public key, which is also sent in the payload.

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

ºFINAL STATE OF A PAIRINGº

APP:                     LATTICE1 Dev:
32-byte priv.key

Pairing registry:
- app1.pub_secp256k1 (used to  check future request signatures)
- app1.pub_EC25519   (sed to decrypt future request payloads  )

(App has now established a secure connection)

some complex details avoided (using 1-time keys for future requests,
  separate pairing code generated by the Lattice1).

ºREMOTE SIGNINGº
Now app can be used as a generalized TX Signer, just like any other hardware wallet. Unlike other
hardware wallets, however, the paired application is capable of communicating with the device
wirelessly.

We are now able to request a signature on some piece of data, which is of course parameterized
and built in the CHip 1 (TX  Builder)

ºMANUAL REMOTE SIGNINGº
As mentioned above, the pairing process also creates a minimal "permission". The application may request a
signature using this permission in a way similar to existing hardware wallet TXs:

- the Lattice1 device displays transactional data to the user
  and must wait for the user to hit “accept” on the touch
  screen.

However, there are 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)

AUTOMATIC REMOTE SIGNING: (Ex. ecurring 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 ]

. In this case, the requester can only send a request once every 10,000 seconds. One second (or more) too early and the request will be denied.
Application SDK

All of the previously discussed functionality is made possible through a Grid
+ Software Development Kit (SDK); this SDK will be released as an open source
node.js module. We hope that developers wanting to build applications with a
separated, internet-connected, secure signing service will experiment with
the SDK and integrate with the Lattice1 device. Although Grid+ is building a
mobile wallet application, this too will be open sourced as an example of how
to leverage the Grid+ SDK.

Although the API is not finalized yet, the below Javascript snippet is an
example of what using the SDK may look like:

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 ...
})

Keeping it General

Although this article mostly discusses the Lattice1 remote signing
functionality in the context of cryptocurrency transfers, it is important to
highlight that using an abstracted “signer” allows applications to request
signatures on any data that is parametrizable. One can imagine, for example,
a data schema that represents parameters of a legal contract:
"Top" hard.Wallets
(Updated to 2018)

ºLedger Nanoº
@[https://shop.ledger.com/products/ledger-nano-s]
- securised key store system:
  - WYSIWYS/BOLOS:
  - 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.

ºKeepKeyº
- Controlled through Google Chrome.
@[https://shapeshift.io/keepkey/]
- RºRecovery method?º

ºSafe T-Mini (Archos)º
 Notre avis complet sur le Safe T-mini
@[https://shop.archos.com/es/hardware-wallet/588-archos-safe-t-mini.html]
- RºRecovery method?º


ºLedger Blueº
@[https://shop.ledger.com/products/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º
@[https://www.coolwallet.io/]
- Credit Card format
- RºRecovery method?º

Trezor Wallet
@[https://en.bitcoin.it/wiki/TREZOR]
- 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,...)
PROTOCOL/APIs SCHEMA
        ┃  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 │
                              ┃       └─────────────┘  └───┘  └──────────────────┘

Ex:
- Securosys HSM, used by R3 Corda to encrypt and sign offline.
  - REF:
  @[https://www.securosys.com/en/products/primus-hardware-security-modules-hsm]
  @[https://www.youtube.com/watch?v=ydMMb1wcCT0&list=PLi1PppB3-YrVeHKIhNxm3_4NvO0AFSvWr] (~8min:00)

Arch.considerations
for cryptanalytic hardware
@[https://people.eecs.berkeley.edu/~daw/papers/hwkeysearch96-www/chap-10_local.html]
yubikey
@[https://www.yubico.com/products/yubikey-hardware/]
@[https://github.com/drduh/YubiKey-Guide]
""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
@[https://inversepath.com/usbarmory]
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
@[https://safenet.gemalto.com/data-encryption/hardware-security-modules-hsms/protectserver-security-module/]

             SECP256K1                      Crytographic APIs
           │              ┌──────────┬────────────────┬─────────────────────┬────────┐
           │              │ PKCS#11  │ Java (JCA/JCE) │ Microsoft CAPI  CNG │ OpenSSL│
───────────│──────────────┼──────────┼────────────────┼─────────────────────┼────────┤
nChiper    │              │          │                │                     │        │
           │              │          │                │                     │        │
Gemalto    │              │          │                │                     │        │
(LunaHSM)  │              │          │                │                     │        │
           │              │          │                │                     │        │
....
MultiFacto authentication
Universal 
Second Factor
(U2F)
- See also:
@[https://en.wikipedia.org/wiki/Multi-factor_authentication]




@[https://www.yubico.com/solutions/fido-u2f/]
internet open auth. enabling users to securely access services
ºwith one single sec.key and with no drivers or client software neededº

u2f at github.com/google
See also: Universal Authentication Framework (UAF) protocol
- vision: "take strong public key crypto to the mass market"
- Successfully deployed by Facebook, Gmail, Dropbox, GitHub, Salesforce.com, the UK government,
and many more.
Smart Cards
DS/EN 14890-1 Standard
@[https://standards.globalspec.com/std/1167872/DS/EN%2014890-1]

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.
GNUPGP SC
-@[https://www.commoncriteriaportal.org/cc/]
   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
@[https://gnupg.org/ftp/specs/]
@[http://cardwerk.com/iso-7816-smart-card-standard/]

- Extracted from @[https://en.wikipedia.org/wiki/Smart_card]
  """PGP SmartCard is the most widely used
  Crypto Commands include:
    - PSO: COMPUTE DIGITAL SIGNATURE
    - HASH ALGORITHMS
    - DigestInfo for RSA
    - PSO: DECIPHER
    - PSO: ENCIPHER
    - INTERNAL AUTHENTICATE
      + Client/Server Authentication
    - GENERATE ASYMMETRIC KEY PAIR
    - GET CHALLENGE
    - TERMINATE DF
  """

Related:
- GPG SmartCard for SSH Authentication
@[https://www.grepular.com/Smart_Cards_and_SSH_Authentication]
  ºSSH KEY SETUPº
  ────────────────────┬──────────────────────────────────────
  STANDARD(SOFTWARE)  │ PGP (HARDWARE)
  SSH KEYGEN          │ SMART-CARD:
  ────────────────────┼──────────────────────────────────────
            GENERATING THE KEYS
  ────────────────────┼──────────────────────────────────────
  $ 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.
                      │
  ────────────────────┼──────────────────────────────────────
            ADDING AUTH.SUBKEY TO SSH LIST OF AUTHORIZED KEYS
  ────────────────────┼──────────────────────────────────────
  $ 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
  ────────────────────┴──────────────────────────────────────

  AUTHENTICATING USING THE SMART CARD
  (how do we get the OpenSSH client to use the smart card)

  ────────────────────┬──────────────────────────────────────
  STANDARD(SOFTWARE)  │ PGP (HARDWARE)
  SSH KEYGEN          │ 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
@[https://incenp.org/notes/2016/openpgp-card-implementations.html]

- @[https://g10code.com/]
  """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:
  @[https://g10code.com/p-card.html]

  - @[https://openpgpcard.net/]
  RºWARN: Does not include displayº
  - Hardware cryptocurrency wallet
  - OpenPGP smart card
  - U2F authenticator
  - One-time password generator
CardPeek
@[http://pannetrat.com/Cardpeek]
- 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
OpenCryptoJC.org
@[http://opencryptojc.org/]
(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
@[https://en.wikipedia.org/wiki/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
    cryptography
Trusted Exec Env
@[https://en.wikipedia.org/wiki/Trusted_execution_environment]
@[https://en.wikipedia.org/wiki/Trusted_Platform_Module]

Intel SGX
@[https://software.intel.com/en-us/blogs/2013/09/26/protecting-application-secrets-with-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. "

  Vault@Github

Keywhiz
@[https://square.github.io/keywhiz/]

Crypt
@[https://xordataexchange.github.io/crypt/]
(in combination with with etcd or consul)
Key Mng.Serv.(KMS)
- Google Cloud KMS
- Amazon KMS
- Android Keysotre
- Apple iOS KeyChain
- ...?


Technology Radar
Trillian "Big"MerkleTree
Trillian is an implementation of the concepts described in the
Verifiable Data Structures white paper, which in turn is an extension and
generalisation of the ideas which underpin Certificate Transparency
BitLocker full disk encryption
RSA Conference
Lamport signatures
- quantum-proof cryptographic signatures
- Quantum Safe Ethereum proxy with
  Winternitz One-Time signatures
  @[https://github.com/tjade273/QEth]
Azure Sphere Pluton
@[https://azure.microsoft.com/en-us/services/azure-sphere/]
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.
Elliptic Curves
- ¿Safe?Curves:
@[http://safecurves.cr.yp.to/]
- Browser support
@[https://security.stackexchange.com/questions/31772/what-elliptic-curves-are-supported-by-browsers]


- TLS-RSA cert. with elliptic curve
@[https://crypto.stackexchange.com/questions/30503/tls-rsa-certificate-with-elliptic-curve-negotiation]

Comparisions of secp256r1-vs-secp256k1 Elliptic Curves:
@[https://crypto.stackexchange.com/questions/18965/is-secp256r1-more-secure-than-secp256k1]


Pairing primitives
@[https://www.math.uwaterloo.ca/~ajmeneze/publications/pairings.pdf]
RFC 8555
@[https://tools.ietf.org/html/rfc8555]
Published on 2015-05-22 according to
@[https://datatracker.ietf.org/doc/rfc8555/]
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.
Key Shadowing
@[https://patents.google.com/patent/US9634836]