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º
  he was not a cryptographer,
  but theºfounder of information theoryº
  ºon which "everything" is basedº
@[https://en.wikipedia.org/wiki/Claude_Shannon]
-ºCharles Babbageº
@[https://en.wikipedia.org/wiki/Charles_Babbage]
-ºAda Lovelaceº
@[https://en.wikipedia.org/wiki/Ada_Lovelace]
-ºRon Rivestº(the 'R' in the RSA)
@[http://theory.lcs.mit.edu:80/~rivest/]
-ºAdi Shamirº(the 'S' in the RSA)
@[http://www.wisdom.weizmann.ac.il/~shamir/]
- Leonard Adleman (the 'A' in the RSA) @[]
-ºWhitfiled Diffieº
  (Diffie-Hillman key exchange protocol)
@[https://en.wikipedia.org/wiki/Whitfield_Diffie]
- @[http://www.mi.informatik.uni-frankfurt.de/]  Claus-Peter Schnorr
  https://en.wikipedia.org/wiki/Claus_P._Schnorr
  Inventor of Shnorr signatures
- Eli Biham: Biham
 @[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
- Nick Szabo (Bitcoin "co?"inventor),
@[https://en.wikipedia.org/wiki/Nick_Szabo]
  came up with the idea of "bit gold" and developed
  the idea of smart contract
- @[http://www.weidai.com/] Wei Dai,
  create b-money, mentioned in the  second version
  of the Bitcoin paper
-ºHal Finneyº
@[https://en.wikipedia.org/wiki/Hal_Finney_(computer_scientist)]
 ºPGP Developerº Bitcoin co?inventor
- Paul Kocher
@[http://www.cryptography.com/about_pck.html]
- Moxie Marlinspike
  founder of secure messaging organization Signal
- Ross Anderson
  @[http://www.cl.cam.ac.uk/users/rja14/],
  University of Cambridge, Computer Lab.
- Martin Kleppmann
  Senior Research Associate and Affiliated Lecturer at 
  the University of Cambridge Department of Computer Science and Technology.
  https://martin.kleppmann.com/2020/11/18/distributed-systems-and-elliptic-curves.html
  Author of https://martin.kleppmann.com/papers/curve25519.pdf 

- Benny Chor, Shafi Goldwasser, Silvio Micali and Baruch Awerbuch.
  They demonstrated that Zero-knowledge proofs exist "outside the 
  domain of cryptography and numbe theory". Usin no assumptions, it is 
  shown that both graph isomorphism and graph non-isomorphism have 
  zero-knowledge interactive proofs.
  @[http://people.csail.mit.edu/silvio/Selected%20Scientific%20Papers/Zero%20Knowledge/Proofs_That_Yield_Nothing_But_Their_Validity_or_All_Languages_in_NP_Have_Zero-Knowledge_Proof_Systems.pdf]

  C⅋P from @[https://blog.cryptographyengineering.com/2017/01/21/zero-knowledge-proofs-an-illustrated-primer-part-2/]:
  "...  If there exists any decision problem (yes/no answer) whose witness
   (solution) can be verified in polynomial time, then:
    We can prove that said solution exists by 
   (1) translating the problem into an instance of the graph three-coloring
       problem, and
   (2) running the GMW protocol.
   This amazing result gives us interactive zero knowledge proofs for 
   every statement in NP. ..."
  
 @[http://theory.lcs.mit.edu/~shafi/] 
 @[http://www.cs.technion.ac.il/~biham/cgi-bin/faculty.cgi?Chor.Benny]


- Adam Back
@[https://en.wikipedia.org/wiki/Adam_Back]
 ºproof-of-workºsystem used by several anti-spam systems (and Bitcoin,..)
- Don Beaver
- Mihir Bellare
@[http://www-cse.ucsd.edu/users/mihir/] ,
  - professor at the University of California San Diego.
  - published several seminal papers in the cryp. field
    (notably in the area of provable security), many
    of which were co-written with Phillip Rogaway.
    and Format-Preserving Encryption.
-ºEran Tromerº@[http://www.cs.tau.ac.il/~tromer/] ,
  - ZCash Inventor and founding scientist
  @[https://z.cash]
    privacy-preserving cryptocurrency which implements our
    @[http://zerocash-project.org] Zerocash protocol.
   - RSA Key Extraction via Low-Bandwidth Acoustic Cryptanalysis
  @[http://www.cs.tau.ac.il/~tromer/acoustic/]
    """particularly interested in what happens when cryptographic
     systems meet real world offaulty and leaky computation."""
  -  heads the @[http://www.cs.tau.ac.il/~tromer/leisec] Laboratory
     for Experimental Information Security (LEISec) investigating side
     channel info leakage in computers through physical emanations
     electric and electromagnetic) and software (e.g.,
   @[http://www.cs.tau.ac.il/~tromer/papers/cache-joc-20090619.pdf]
  -  cache contention in local and cloud computing
     @[http://www.cs.tau.ac.il/~tromer/cloudsec/]
  -@[https://beautyburst.github.io]
     Remote Identification of Encrypted Video Streams
  -  cofoundedºSCIPR Labº@[http://scipr-lab.org]:
     cryptographic zero -knowledge SNARK proof systems-
  -  Interested in blockchain-based cryptographic protocols,
  -  Other research interests:
     - tamper resilience, homomorphic encryption,
  -@[http://www.cs.tau.ac.il/~tromer/cryptodev]
     special-purpose code-breaking hardware and various
     aspects of network and systems security.
  -  Publications: @[http://www.cs.tau.ac.il/~tromer/publications]
     publications for more information.

- @[https://en.wikipedia.org/wiki/Steven_M._Bellovin] Steve Bellovin,
   a researcher on computer networking and security.
   Professor in the Computer Science department at Columbia
   University,[1] having previously been a Fellow at AT⅋T Labs
   Research in Florham Park, New Jersey.[2][3]
   - In September 2012, Bellovin was appointed Chief
   Technologist for the United States Federal Trade Commission,
   replacing Edward W. Felten, who returned to Princeton University
- Philippe Béguin
- Josh Benaloh(formerly Cohen)
@[https://www.microsoft.com/en-us/research/people/benaloh/]
  - pioneered new technologies including:
    - "cast or spoil" paradigm that brings voters into
      the verification process with minimal burden.
- OºDaniel Julius Bernsteinº (@[http://cr.yp.to/djb.html])
 (@[https://en.wikipedia.org/wiki/Daniel_J._Bernstein] Wikipedia).
  critic of the leading email and DNS packages of the time,
  Sendmail and BIND. Bernstein attempted to address the situation
  by designing and implementing secure email and DNS services
  (qmail, ezmlm, djbdns, etc.)
  - sued the United States Government in 1995 (Bernstein
  v. United States).
  - His software received significant attention and no bugs
    were found in it for eight years.
  - Designer of theºSalsa20ºstream cipher
    in 2005 and submitted it to eSTREAM for
    review and possible standardization.
  - In 2008 published a closely related stream cipher,
    ºChaCha20º.
  - Heºalso proposed the elliptic curve Curve25519ºas a basis
    for public-key schemes in 2005, and worked as the lead
    researcher on the Ed25519 version of EdDSA.
- @[http://www.nlsde.buaa.edu.cn/~kexu/]  Ke Xu
- @[http://www.csie.ncu.edu.tw/~yensm/people/yensm/]  Sung-Ming Yen
- @[http://www.cs.hut.fi/~ylo/]  Tatu Ylönen
- @[http://www.cs.columbia.edu/~ayoung/]  Adam Young
- @[http://www.cs.columbia.edu/~moti/]  Moti Yung
- @[http://pscit-www.fcit.monash.edu.au/~yuliang/]  Yulian Zheng
- @[http://www.cs.ucdavis.edu/~rogaway/]  Phil Rogaway
- @[http://www.cs.nyu.edu/~rubin/]  Avi Rubin
- Steven Rudich
@[http://www.cs.cmu.edu/afs/cs.cmu.edu/user/rudich/www/home.html]
- @[http://tcslab.csce.kyushu-u.ac.jp/~sakurai/]  Kouichi Sakurai
- @[http://tsk-www.ss.titech.ac.jp/~tsato/index-e.html]  Takashi Satoh
- @[http://www.digicash.com/~berry/]  Berry Schoenmakers
- @[http://www.cs.uow.edu.au/people/jennie/]  Jennifer Seberry
- Joan Feigenbaum
@[http://www.cs.yale.edu/homes/jf/home.html]
- Niels Ferguson
@[http://niels.ferguson.net]
- Marc Fischlin
@[http://www.mi.informatik.uni-frankfurt.de/people/marc/marc.html]
- Yair Frankel
@[http://www.cs.sandia.gov/~yair]
- Matt Franklin
@[http://www.cs.ucdavis.edu/~franklin/]
- Peter Gemmell
@[http://www.cs.sandia.gov/~psgemme]
- Rosario Gennaro
@[http://www.research.ibm.com/people/r/rosario/]
- Ian Goldberg
@[http://www.cs.berkeley.edu/~iang/]
- Oded Goldreich
@[http://www.wisdom.weizmann.ac.il/~oded/]
- Li Gong
@[http://java.sun.com/people/gong/]
- Wei Dai (Crypto++)@[https://en.bitcoin.it/wiki/Wei_Dai']
- Mark Goresky
@[http://www.math.ias.edu/~goresky/home.html]
- Shai Halevi
@[http://theory.lcs.mit.edu/~shaih/]
- Helena Handschuh
@[http://www-inf.enst.fr/~research/theses/handschuh.gb.html]
- Carlo Harpes
@[http://www.isi.ee.ethz.ch/~harpes/]
- Martin Hellman (pubs only)
@[ftp://isl.stanford.edu/pub/hellman/reports/]
- Amir Herzberg
@[http://amir.herzberg.name/index.html]
- Frederic Huygens
@[http://www.ulb.ac.be/di/scsi/defscsi.html]
- Hideki Imai
@[http://imailab-www.iis.u-tokyo.ac.jp/Members/imai-e.html]
- Russell Impagliazzo
@[http://www-cse.ucsd.edu/users/russell/]
- David McGrew
@[http://www.mindspring.com/~dmcgrew/dam.htm]
- Alfred Menezes
@[http://cacr.math.uwaterloo.ca/~ajmeneze/]
- Ralph Merkle
@[http://merkle.com/merkle]
- Daniele Micciancio
@[http://theory.lcs.mit.edu/~miccianc/]
- Chris Mitchell
@[http://isg.rhbnc.ac.uk/cjm/Chris_Mitchell.htm]
- Shiho Moriai
@[http://info.isl.ntt.co.jp/~shiho/]
- Sean Murphy
@[http://www.cs.rhbnc.ac.uk/~sean/]
- Clifford Neumann
@[http://www.isi.edu/people/bcn/]
- Mats Näslund
@[http://www.nada.kth.se/~matsn/matsn_homepage/research.html]
- Moni Naor
@[http://www.wisdom.weizmann.ac.il/people/homepages/naor/index.html]
- Harald Niederreiter
@[http://www.iinform.oeaw.ac.at/Niederreiter.html]
- Valtteri Niemi
@[http://www.uwasa.fi/~vni/]
- Luke O'Connor
@[http://www.zurich.ibm.com/~oco/]
- Andrew Odlyzko
@[http://www.research.att.com/~amo/]
- Kazuo Ohta
@[http://www.ohta.is.uec.ac.jp/k_ohta/]
- Rafail Ostrovsky
@[http://www.cs.ucla.edu/~rafail/]
- Christof Paar
@[http://www.crypto.rub.de/en_paar.html]
- Torben Pryds Pedersen
@[http://cryptomathic.aau.dk/~tpp/]
- Rene Peralta
@[http://www.cs.uwm.edu/faculty/peralta/index.html]
- Giuseppe Persiano
@[http://www.dia.unisa.it/~giuper]
- Holger Petersen
@[http://www.dmi.ens.fr/~petersen/]
- Birgit Pfitzmann
@[http://www.semper.org/sirene/people/birgit/info.birgit.html]
- Josef Pieprzyk
@[http://www.cs.uow.edu.au/people/josef/homepage.html]
- Tom Berson, Advisory Board Member
@[http://www.anagram.com/berson/]
  and Chief Security Advisor at Saleforce.com since 1999 foundation
- Thomas Jakobsen
 @[http://www.mat.dtu.dk/persons/Jakobsen_Thomas/]
 - Markus Jakobsson
 @[http://www.markus-jakobsson.com/]
 - Stanislaw Jarecki
 @[http://theory.lcs.mit.edu/~stasio/]
 - Antoine Joux
 @[http://www.dmi.ens.fr/equipes/grecc/Membres/joux/pub.html]
 - Marc Joye
 @[http://www.geocities.com/MarcJoye/]
 - Ari Juels
 @[http://www.rsalabs.com/rsalabs/staff/ajuels/homepage.html]
 - Mike Just
 @[http://www.scs.carleton.ca/~just/]
 - Kwangjo Kim
 @[http://vega.icu.ac.kr/~kkj]
 - Seung-Joo Kim
 @[http://dosan.skku.ac.kr/~sjkim]
 - Andy Klapper
 @[http://al.cs.engr.uky.edu/~klapper/andy.html]
 - Lars Knudsen
 @[http://www.ii.uib.no/~larsr/]
 - François Koeune
 @[http://www.dice.ucl.ac.be/~fkoeune/koeune.html]
 - Kaoru Kurosawa
 @[http://kuro.cis.ibaraki.ac.jp/~kurosawa/]
 - Markus Kuhn
 @[http://www.cl.cam.ac.uk/~mgk25/]
 - Eyal Kushilevitz
 @[http://www.cs.technion.ac.il/~eyalk/]
 - Lam Kwok-Yan
 @[http://www.comp.nus.edu.sg/~lamky/]
 - Pil Joong Lee
 @[http://wooly.postech.ac.kr/user/pjl/]
 - Reynald Lercier
 @[http://lix.polytechnique.fr/~lercier/]
 - Helger Lipmaa
 @[http://home.cyber.ee/helger/]
 - Mark Lomas
 @[http://www.cl.cam.ac.uk/users/tmal/]
 - Mike Luby
 @[http://www.icsi.berkeley.edu/~luby/]
 - Philip MacKenzie
 @[http://cm.bell-labs.com/who/philmac/]
 - Spyros Magliveras
 @[http://zeus.math.fau.edu/spyros/]
 -
 @[http://www-ir.inf.ethz.ch/research/elek/signalverarbeitung/massey.proj_overview]
 - Gilles Brassard
 @[http://www.iro.umontreal.ca/~brassard/]
 - Lawrie Brown
 @[http://mnementh.cs.adfa.oz.au/Lawrie_Brown.html]
 - Johannes Buchmann
 @[http://www.informatik.th-darmstadt.de/TI/Mitarbeiter/buchmann.html]
 - Mike Burmester
 @[http://www.cs.fsu.edu/~burmester/]
 - Christian Cachin
 @[http://theory.lcs.mit.edu/~cc/]
 - Jan Camenisch
 @[http://www.inf.ethz.ch/personal/camenisc/]
 - Ran Canetti
 @[http://theory.lcs.mit.edu/~canetti/]
 - Anne Canteaut
 @[http://www-rocq.inria.fr/codes/Anne.Canteaut/]
 - Florent Chabaud
 @[http://www.ens.fr/~chabaud/]
 - Che-Hao (Albert) Chang
 @[http://www.cl.cam.ac.uk/~chc1001/]
 - David Chaum
 @[http://www.digicash.com/digicash/people/david.html]
 - Andy Clark
 @[http://www.primarykey.co.uk/Andy/ajcmain.HTM]
 - Lorrie Cranor
 @[http://www.research.att.com/~lorrie/]
 - Claude Crépeau
 @[http://www.cs.mcgill.ca/~crepeau/]
 - Ivan Damgård
 @[http://www.daimi.aau.dk/DAIMI/ScientificStaffProfiles/ivan.html]
 - George Davida
 @[http://www.cs.uwm.edu/faculty/davida/]
 - Alfredo de Santis
 @[http://www.unisa.it/ads.dir/index.htm]
 - Giovanni Di Crescenzo
 @[http://www-cse.ucsd.edu/users/giovanni/]
 - Don Davis
 @[http://world.std.com/~dtd/]
 - Dorothy Denning
 @[http://www.cosc.georgetown.edu/~denning/]
 - Yvo Desmedt
 @[http://www.cs.fsu.edu/~desmedt/]
 - Cunsheng Ding
 @[http://www.comp.nus.edu.sg/~dingcs]
 - Hans Dobbertin
 @[http://www.ruhr-uni-bochum.de/itsc/englisch/index.html]
 - Carl Ellison
 @[http://www.clark.net/pub/cme/home.html]
 - Paul Fahn
 @[http://www-isl.stanford.edu/people/fahn/crypto.html]
 - Jean-François Dhem
 @[http://www.dice.ucl.ac.be/~dhem/]
 @[http://www.bell-labs.com/user/sgwetzel/]
 -  Ted Wobber
 @[http://www.research.digital.com/SRC/staff/wobber/bib.html]
 -  Stefan Wolf
 @[http://www.inf.ethz.ch/personal/wolf/]
 -  Dong-Ho Won
 @[http://dosan.skku.ac.kr/~dhwon/]
 -  Avishai Wool
 @[http://research.lumeta.com/yash]
 -  Dongho Won
 @[http://dosan.skku.ac.kr/~dhwon/]
 -  Rebecca Wright
 @[http://www.research.att.com/info/rwright/]

 - Ueli Maurer
 @[http://www.inf.ethz.ch/personal/maurer/]
 - Kevin McCurley
 @[http://www.swcp.com/~mccurley/index.html]
 - Robert J. McEliece
 @[http://www.systems.caltech.edu/EE/Faculty/rjm/]
 - Benny Pinkas
 @[http://www.wisdom.weizmann.ac.il/~bennyp/]
 - David Pointcheval
 @[http://www.dmi.ens.fr/~pointche/]
 - Thomas Pornin
 @[http://www.dmi.ens.fr/~pornin/index.html.en]
 - Guillaume Poupard
 @[http://www.dmi.ens.fr/~poupard/]
 - Bart Preneel
 @[http://www.esat.kuleuven.ac.be/~preneel/]
 - Jean-Jacques Quisquater
 @[http://www.dice.ucl.ac.be/crypto/jjq.html]
 - Tal Rabin
 @[http://theory.lcs.mit.edu/~talr/]
 -  Omer Reingold
 @[http://www.wisdom.weizmann.ac.il/~reingold/]
 -  Mike Reiter
 @[http://www.research.att.com/~reiter/]
 -  Ali Aydin Selcuk
 @[http://www.csee.umbc.edu/~aselcu1/]
 -  Alan Sherman
 @[http://www.cs.umbc.edu/~sherman/]
 -  English
 @[http://www.ecip.tohoku.ac.jp/Shizuya-Lab/index.html]
 -  Adam Shostack
 @[http://www.homeport.org/~adam/]
 -  Victor Shoup
 @[http://www.cs.wisc.edu/~shoup/]
 -  Tom Shrimpton
 @[http://www.ece.ucdavis.edu/~teshrim/]
 -  Alice Silverberg
 @[http://www.math.ohio-state.edu/~silver/]
 -  Joseph H. Silverman
 @[http://www.math.brown.edu/~jhs]
   by the NSA, who evidently knew about it as well.
 - John R. Black
 @[http://www.cs.colorado.edu/~jrblack/papers.html]
 - Simon Blackburn
 @[http://www.cs.rhbnc.ac.uk/~simonb/]
 - Matt Blaze
 @[ftp://ftp.research.att.com/dist/mab/]
   (corporate @[http://www.research.att.com/info/mab/] here)
 - Daniel Bleichenbacher
 @[http://www.bell-labs.com/user/bleichen/]
 - Manuel Blum
 @[http://http.cs.berkeley.edu/~blum/]
 - Carlo Blundo
 @[http://www.unisa.it/carblu.dir/start.html]
 - Dan Boneh
 @[http://www.cs.princeton.edu/~dabo/]
 - Antoon Bosselaers
 @[http://www.esat.kuleuven.ac.be/~bosselae/]
 - Joan F. Boyar (formerly Joan Plumstead)
 @[http://www.imada.sdu.dk/~joan/]
 - Colid Boyd
 @[http://www.fit.qut.edu.au/~boyd/]
 - Stefan Brands,
 @[https://en.wikipedia.org/wiki/Stefan_Brandr]
   - cryptographer specialized in electronic cash and digital identity.
   - best known for designing Microsoft's U-Prove protocols .
 -  Markus Stadler
 @[http://www.ubs.com/cgi-bin/framer.pl?/webclub/ubilab/e_index.htm/]
 -  Frank Stajano
 @[http://www.cl.cam.ac.uk/~fms27/]
 -  Jacques Stern
 @[http://www.dmi.ens.fr/~stern/index.html]
 -  Anton Stiglic
 @[http://crypto.cs.mcgill.ca/~stiglic]
 -  Doug Stinson
 @[http://cacr.math.uwaterloo.ca/~dstinson/index.html]
 -  Yuriy Tarannikov
 @[http://liapunov.inria.msu.ru/PERSONAL/Taran/index.html]
 -  Stafford Tavares
 @[http://http.ee.queensu.ca:8000/www/dept/facpages/set.html]
 -  Yiannis Tsiounis
 @[http://www.ccs.neu.edu/home/yiannis/]
 -  Jeroen van de Graaf
 @[http://www.iro.umontreal.ca/people/jeroen/index.htm]
 -  Joos Vandewalle
 @[http://www.esat.kuleuven.ac.be/cosic/vdwalle.html]
 -  in English
 @[http://www.ens.fr/dmi/equipes_dmi/grecc/vaudenay/index_en.html]
 -  David Wagner
 @[http://www.cs.berkeley.edu/~daw/]
 -  Susanne Wetzel
 - Thomas Beth
   Albrecht Beutelspacher,
 @[http://www.beutelspacher.info/]
   mathematic "broadcaster"
External Links
•@[https://en.wikipedia.org/wiki/Index_of_cryptography_articles]
•@[https://cryptography.io/en/latest/]
•@[https://crypto.stackexchange.com]
•@[https://www.rsaconference.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:
@[https://en.wikipedia.org/wiki/Outline_of_cryptography]
• The Bouncy Castle FIPS Java API in 100 Examples:
@[https://www.bouncycastle.org/fips-java/BCFipsIn100.pdf]
• Ronald L.Rivest List of Links!!!
@[http://people.csail.mit.edu/rivest/crypto-security.html]
• Kevin McCurley's links:
@[http://www.swcp.com/~mccurley/cryptographers/cryptographers.html]
• University of Southern California (Information Sciences Institute; 
  Global Operating Systems Technology (GOST) Group)
@[http://nii.isi.edu/gost-group/]
• Rootshell.be articles on exploits, security alerts, ...:
@[http://https://blog.rootshell.be/]
• Electronic Colloquium on Computational Complexity:
@[https://eccc.weizmann.ac.il/]
• ACM Special Interest Group on Security, Audit and Control (SIGSAC):
@[http://www.sigsac.org/]
• NSA Playset (OOSS ANT catalog):
@[https://en.wikipedia.org/wiki/NSA_Playset]

• Cryptology ePrint Archive:
  @[https://eprint.iacr.org/]
  - rapid access to recent research in cryptology.
  - Papers have been placed here by the authors and did 
    not undergo any refereeing process other than verifying
    that the work seems to be within the scope of cryptology
    and meets some minimal acceptance criteria and publishing 
    conditions. 

• SCIPR Lab:
@[http://www.scipr-lab.org/]
@[https://github.com/scipr-lab]
  multi-institutional academic collaboration of researchers
  seeking to bring to practice cryptographic proof systems that
  provide succinct integrity and privacy.

Bº#################º
Bº# Number Theory #º
Bº#################º
• 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]
- 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]
 @[https://en.wikipedia.org/wiki/List_of_important_publications_in_cryptography]
- "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

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

• Symmetric crypto. broadly splits in two categories:
  ·ºStream cipherº:                                                [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, ...

    -Rº"BUTS":º
      · Generate a safe (non predictive) KEY for the stream cipher is "difficult"

  ·ºBlock  cipherº:                                                [block_cipher]
    - inputs must be divided into chunks of same size
    - Hide plaintext transformation to ciphertext through:
      - ºconfusionº: mapping input to output hard to predict (not linear and parts of keys)
      - ºdiffusionº: permutate bits

    - Most block ciphers are based onºSP-Networksºcomposed of:
      - Subtitution box : "map˂byte, byte˃"   (replace bytes with bytes )
      - Permutation box :  moves bits around
      - Some substitution plus permutation are combined into a single round
      - Rounds are then repeated enough times to ensure the algorithm is secure
      - SP-Networks alone are not enought. An extra º(secret)KEYº is used like:

                         ROUND1                ROUND2       ...

        Plain →ºXORº→ │Subsitution│ → XOR → │Subsitution│ → ... → C
               ºKEYº  │Permutation│   KEY   │Permutation│

    - Block ciphers have one or more block size(s), but during transformation
      the block size is always fixed.

    - Block cipher operation modes:
      - A block cipher alone can only encrypt a single block of N-bits.
      - The operation mode describes how to repeatedly apply a
        cipher's single-block operation to securely transform N blocks.
      - Most modes require an initialization vector (IV) for each new encrypt.  [IV]
        -ºIV must be non-repeating and, for some modes, random as well.º
        - IV ensure distinct ciphertexts are produced even for the same plaintext.
          when reusing the same (private and symmetric) key.
      - Operation modes include:
        ·RºElectronic code block (ECB):º
           M1 → |E_k| → C1  ← RºWARN:ºDon't use it, if different messages share 
           M2 → |E_k| → C2            same data information leaks cans rise
           M3 → |E_k| → C3
        ·BºCipher block chaining (CBC):º
          IV: Initialization vector                                            [IV]
                                         Rº"BUTs":º
          M1 → |XOR(IV)| → |E_k| → C1       - Not paralelizable.
             → |XOR(M2)| → |E_k| → C2       - can not seek randomnly
             → |XOR(M3)| → C3               - Needs an IV (Difficult to generate)
            
        ·BºCounter Mode (CT):º (Can be paralellized)
          Nonce + 0 → |E_k| → XOR(M1) → C1  ← ºNoces are used onceº        [comparative]
          Nonce + 1 → |E_k| → XOR(M2) → C2    ºIVs must be unpredictableº  [nonce]
          Nonce + 2 → |E_k| → XOR(M3) → C3

    -Rº"BUTS":
      ·Rºblock chipers require Paddingº when the message does NOT exactly
        match a multiple of key size. This can introduce security bugs if not
        implemented properly.
      @[https://en.wikipedia.org/wiki/Padding_(cryptography)]

        (There are block chiper operation modes that do NOT require padding
         because they effectively use a block cipher as a stream cipher).
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)

RºTODO:º What every Software Engineer should know about AES
       @[https://proandroiddev.com/security-best-practices-symmetric-encryption-with-aes-in-java-7616beaaade9]
       @[https://proandroiddev.com/security-best-practices-symmetric-encryption-with-aes-in-java-and-android-part-2-b3b80e99ad36]
       ...In this article I will bring you up to speed on the Advanced
       Encryption Standard (AES), common block modes, why you need padding
       and initialization vectors and how to protect your data against
       modification. Finally I will show you how to easily implement this
       with Java avoiding most security issues.
Asymmetric cryptography
Asymmetric primitives
- 4 keys are need for bidirectional communication.
  - 1 Public  key (known to everyone) is used for encryption by sender   Alice
  - 1 Private key (known to owner   ) is used for decryption by receiver Bob
  (and two extra keys for Bob to Alice communication)

- PEER 1  ·                                              ·   PEER 2
          ·                                              ·
          │ Encrypt with │                │ Decrypt with │           ← Asymmetrically encrypted msg.
  Plain → │    Peer 2's  │ → CypherText → │   Peer 2's   │ → Plain     PEER 1 → PEER 2
  text    │ public  key  │                │ºprivate  keyº│   text
          ·                                              ·       
          ·                                              ·
          ·                                              ·
          │ Decrypt with │                │ Encrypt with │           ← Asymmetrically encrypted msg.
  Plain ← │    Peer 1's  │ ← CypherText ← │   Peer 1's   │ ← Plain     PEER 2 → PEER 1
  text    │ºprivate  keyº│                │ public   key │   text


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

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

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


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


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

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


-GºProves authenticity of senderº← Only sender owning priv.key
                                   could have created the signature
-BºNon-repudiationº               ← 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. """

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

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

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

1978: Jacques Vélu, publish
      "Courbes elliptiques munies d'un sous-group Z/nZxmu_n"
      Société Mathématique de France, 57, 1-152, Paris, 1978.
      @[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.
      (REF: "Applied Cryptography", Bruce Schneier, ISBN 0-471-11709-9)

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

1989  Schnorr patents its signature method
      https://patents.google.com/patent/US4995082
      Patent expired in 2008.
      As of 2013+ software companies tend to
      replace ECDSA with Schnorr.
      2014: C&P 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] )

1991: Phil Zimmermann developes PGP

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

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

1995: FIPS 180-1, Secure Hash Standard

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

1999: NIST recommends 15 elliptic curves.

2000: ESIGN Act makes online signatures legally binding

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

2005: Elliptic Curve DSA
    @[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.
      SSH decided to Rº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]

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


BºDSA SIGNATURE:º
  ┌─────────┐            ┌──────┐  ┌───────┐
  │(M)essage│───────────→│CONCAT│─→│Message│─────┐
  └─────────┘            └──────┘  │       │  ┌──v─────┐
    │                       ^      ├───────┤  │Verifier│─┐
    │  ┌────┐      ┌──────┐ │      │s(sign)│─→└───^────┘ │
    └─→│HASH│─→h1─→│Sign  │─┘      ├───────┤      │  ┌───v───┐
       └────┘      └─^──^─┘        │r(sign)│─┬────┘  │Compare│
                     │  │          └───────┘ │       └───^───┘
               PrivKey  K(Non secret)        └───────────┘
  └──────────────────────┬─────────────────┘└──────┬──────────┘
                        Sign                     Verify

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

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

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

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

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

- compatible with integer prime number              - variant of the ElGamal adding secondary
  factorization                                       160-bit modulus(q) to speed up execution
-RºIn-compatible with not with                        and reduce the size of final signature.
  elliptic curvesº                                  -RºCan NOT be used for encryptionº
- computationally more expensive                    - DSA Key Generation
-BºDoes not require a source of randomnessº           1) shared global pub.key values (p,q,g)
   Prefered of embedded systems/smartcards/....          are chosen (DSA public parameters):
- RSA provides us with Public (e,n) and                 ºpº= 2 power L "Large prime"
  Private (d)                                                        ^
 ºeºis usally a small number                                       L := 512/1024 bits
 ºdºis a much large number                                              multiple of 64
- n=p.q (very large) semi-prime number                  ºqº= a 160 bit prime factor of p-1
- given an RSA scheme {(e,R), (d,p,q)}                  ºgº= h power (p-1)/q
- RSA Schema: Sign a message:                          - for any h1
  Compute:                                            2) Each user chooses a priv.key and
OºSº= M power d (mod R)                                  computes their public key:
- RSA Schema: Verify a message:                          - choose x compute y =ºgºpower x(modºpº)
  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 vs ECDSA "secp256k1" Digital Signatures compared

Extracted from @[https://tools.ietf.org/html/rfc6979]
" (ed25519-curve based?) 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 "

• secp256k1 has a linear private-key space:
    prv.key1            → public key of (prv.key1)
    prv.key2            → public key of (prv.key2)
    prv.key1 + prv.key2 → public key of (prv.key1 + prv.key2)
                          └─────────────┬───────────────────┘
                          equal to (due to linearity) sum of
                              public key of (prv.key1)
                            + public key of (prv.key2)

• Ed25519 private-key space is NOT linear. 
  It uses a twisted Edwards curve bi-rationally equivalent 
  to the Montgomery curve Curve25519, since public-key is 
  generated from private key by first hashing the  private key 
  with SHA-512.
    prv.key1            → pub.key of sha512(prv.key1)             
    prv.key2            → pub.key of sha512(prv.key2)
    prv.key1 + prv.key2 → pub.key of sha512(prv.key1 + prv.key2)

  This creates some sort of problems, for example to create 
  HD Wallets as explained in:
@[https://www.jelurida.com/sites/default/files/kcdsa.pdf]
                             
Bº#######################################º
Bº# Schnorr("ed25519 version od EdDSA") #º
Bº#######################################º
@[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
• elliptic curve implementation more optimal and secure than equivalent 
  design schemes based on secp256k1 (Bitcoin/Ethereum/...)
• Summary of advantages versus secp256k1 curve:
  - 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 signature schemas:
  - 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.
Elliptic curves intro:
@[https://blog.cloudflare.com/a-relatively-easy-to-understand-primer-on-elliptic-curve-cryptography/]

@[https://andrea.corbellini.name/2015/05/17/elliptic-curve-cryptography-a-gentle-introduction/]
Elliptic Curves Comparative
- ¿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]
Ed25519 JS Signature
@[https://github.com/transmute-industries/Ed25519Signature2018]

- Minimal implementation of Ed25519Signature2018 in JavaScript.

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

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

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

CipherText + HASH(KEY+CipherText)
- Q: Why the "5381"/"33"/... constant in hash?:
@[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
BLAKE3: CPU Parallelizable Hash
- BLAKE3 Is an Extremely Fast, Parallel Cryptographic Hash
@[https://www.infoq.com/news/2020/01/blake3-fast-crypto-hash/]
  - BLAKE3 is the most recent evolution of the BLAKE cryptographic hash
    function. Created by Jack O'Connor, Jean-Philippe Aumasson, Samuel
    Neves, and Zooko Wilcox-O'Hearn, BLAKE3 combines general purpose
    cryptographic tree hash bao with BLAKE2 to provide a big performance
    improvement over SHA-1, SHA-2, SHA-3, and BLAKE2.
HMAC primitives: "secret-shared signature"
- Allows for authentication of the signer of a given "frozen" file/data
  (vs authentication in session establishment of a network protocol).
- 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(-Merkle)
Diffie-Hellman Key "exchange"
- 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.
      Key is not actually "exchanged" but calculated by both parties simultaneously.
    - 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.
IVs,nonces,Salt
• Randomness of secret keys is not enough in most scenarios due to 
  the attacks by replication or repeated XORs of different messages 
  encoded with the same private shared-by-peers keys. 
  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 cryptographically randomº.

 º#####################################º
•º# Salt (encryption, oneway Hashing) #º
 º#####################################º
@[https://en.wikipedia.org/wiki/Salt_(cryptography)]
  Salt: random data used as additional input to a one-way
        function that "hashes" data (ussually password).
  · primary use are: 
    - KEY DERIVATION FUNCTIONS:  
    - DEFENSE AGAINST TABLE ATTACKS:
      If an atacker can compute/store billions of combinations
      of dictionary hashes, the salt will force to repeat the 
      computation/duplicate the storage for each possible salt.

  ·ºclosely related to 'nonce':º
    · Nonce must not be repeated but can be predictable.
      Salts can be repeated, and ºalso they must be º
     ºcryptographically random.º
    · Nonce protect 'network/onfly' data against replays.
    · Salts protect 'disk/stored'   data against dict. attacks.
    · Nonce do not need to be secret. Once a "nonce" is consumed
      it is "useless", even for attackers. Salts must be secret
      (and separated from secret keys) when using for symmetric 
      encryption, but can be public when used in one-way hash
      functions. 

 º#############################################º
•º# Nonce (protection against message replay) #º
 º#############################################º
@[https://en.wikipedia.org/wiki/Cryptographic_nonce]
  · arbitrary number that ºcan only be used onceº
  · It can be public or predictable
  · ºissued in network protocols to protect against replay attacks:º
    - An attacker, for example, replays encrypted session
      message (raw data) impersonating the client hopping to
      obtain a server session token. Since the nonce has already
      been used/wasted/consumed by the original client,
      the session establishment will fail.
Advanced Primitives
Fernet sym. encrypt
- Fernet guarantees that a message encrypted using it
  cannot be manipulated or read without the key.
- Fernet also has support for implementing key rotation via MultiFernet.
Key Derivation Function
- @[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
- (cite from Crypto101): Useful, for example, when a cryptographic protocol
  starts with a single secret value, such as a shared password or a secret
  derived using Diffie-Hellman-Merkle key exchange, but requires multiple
  secret values to operate, such as encryption and MAC keys.

- Two main categories, depending on the entropy content of the secret value
  which determines how many differnet possible values the secret value can
  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.
Verifiable Secret Sharing
• @[https://en.wikipedia.org/wiki/Verifiable_secret_sharing]
In cryptography, a secret sharing scheme is verifiable if auxiliary
information is included that allows players to verify their shares as
consistent. More formally, verifiable secret sharing ensures that
even if the dealer is malicious there is a well-defined secret that
the players can later reconstruct. (In standard secret sharing, the
dealer is assumed to be honest.) The concept of verifiable secret
sharing (VSS) was first introduced in 1985 by Benny Chor, Shafi
Goldwasser, Silvio Micali and Baruch Awerbuch. (Same authors 
working of ZKPs)
In a VSS protocol a distinguished player who wants to share the
secret is referred to as the dealer. The protocol consists of two
phases: a sharing phase and a reconstruction phase.

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

2017 @[https://patents.google.com/patent/US9634836]
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
- introducced in 1993 by Benaloh and de Mare.
- 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.

- They are the cryptographic counterpart of Bloom Filters data structure:
  @[https://hal.archives-ouvertes.fr/hal-00999432/document]
  - A Bloom filter is a space-efficient probabilistic data structure, 
    used to test whether an element is a member of a set.
    Bloom filter setup)
                          bloom-filter0 = 000000000000...........0
      Element1 → hash1 →  bloom-filter1 = bloom-filter 0   || hash1 
      Element2 → hash2 →  bloom-filter2 = bloom-filter 1      hash2
      ...                 ...                                           
      ElementN → hashN →  bloom-filterN = bloom-filter N-1    hashN

    Bloom filter Ussage)
      Q: ElementI belongs to Set?
      A: ElementI → hashI
         if (hashI && bloom-filterN == hashI ) "maybe" (false positives are possible)
         else                                  "definetly no"

  - Crypto Accumulator Ex:
    large composite number 
    CP01 = P1 x P2 x P3 x ... PN
           └────────┬──────────┘
    New members may be added or subtracted to the set of
    factors simply by multiplying or factoring out the number respectively.

    Q: Does P2 "belongs" to CP01?
    A: Yes, but we still don't known P1, P3, ... PN

-  Use case include: time-stamping schemes , search on encrypteddata ,
   data aggregation in sensor networks [19] and distillation codes.
-ºSanderet al. use RSA accumulator to designblind and auditablea
 ºmembership proof scheme in the context of e-cash. The ideais that an º
 ºaccumulator of all the valid electronic coins is created andº
 ºpublished.During coins transfer, anyone can verify the validity of º
 ºthe exchange thanks tothe accumulator.º

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.


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

• Brief summary from: 
@[https://blog.cryptographyengineering.com/2014/11/27/zero-knowledge-proofs-illustrated-primer/]
@[https://blog.cryptographyengineering.com/2017/01/21/zero-knowledge-proofs-an-illustrated-primer-part-2/]
WARN: Original source contains many more interesting and important info.

• zero knowledge proof actors(probabilistic Turing machines in practice):
  - Prover  : works to generate a proof about some mathematical
              statement being true. 
              (e.g. a given graph possesses a three-coloring)
  - Verifier: Verifies the proof through a well known and public
              (interactive/non-interactive) protocol/procedure.

  The proof generated by the prover must have next properties: 
  • Completeness: An honest Prover will eventually convince (any) Verifier.
  • Soundness   : Prover can only convince Verifier if statement is true.
  • Zero-knowledge(ness): Verifier learns no information other than statement
                          is true.

  • General ZKP impose "lot of computing effort" on Prover, but not in verifier.
    (vs related Signature schemas, a particular case of ZKP where signer can 
     probe to known the secret key without revealing it, that impose
     few computing efforts in both the prover-signer- and verifier but
     that can not probe any ARBITRARY decision YES/NO NP statement,
     other than the fact the prover knowns /owns the secret signature key).

• (Claus-Peter) Schnorr identification proof-of-knowledge protocol:
  It forms the basis of many of our modern signature schemes even if author
  was concerned with identity, not signature.

  PRE-SETUP)
  · Alice has published her public key to the world.
  · p : "big" prime number.
    g : generator of a cyclic group of prime-order q.

                             ┌ priv.key             ┌ q = (prime) order of 
                             · ("random")           ·     generator.
        1      2      3      4      5       6       7
    ···g······g······g······g······g·······g·······g··· ← order 7 (prime)
    ^                                                 ^
    0                                                 p ("big" prime number)

  · prv.key = random integer between 1 and q ← private key
  · pub.key = g^a mod p = "PK_A"

   PROTOCOL-Execution) probe to Bob knowledge of private key
                       corresponding to public key without revealing 
                       any information

   participant Alice // prober
   participant Bob   // Verifier

   Alice → Alice: k = random[1,q]
   Alice → Bob  : h = g^k mod p
   Bob   → Alice: c = random[1,q], c stands for "challenge"
   Alice → Bob  : s = ( a·c + k ) mod q *1
   Bob   → Bob  : Check ( PK_A^c · h ) mod p == g^s 

     ┌─────┐                    ┌───┐                                
     │Alice│                    │Bob│                                
     └──┬──┘                    └─┬─┘                                
        ──┐ k = random[1,q]       │
        ←─┘                       │
        │──── h = g^k mod p ─────→│
        │←── c = random[1,q] ─────│  ← Replace random by HashOf( g^k || M )
        │                         │    for non-interactive mode. *3
        │s = ( a·c + k ) mod q *1 │
        │────────────────────────→│
        │                         │
        │                         ──┐ Check:
        │                         ←─┘ ( PK_A^c · h ) mod p == g^s
        │                         │   └─────┬──────┘ 
     ┌──┴──┐                    ┌─┴─┐       = PK_A = g^a mod p, h = g^k mod p
     │Alice│                    │Bob│ ( (g^a)^c · g^k ) mod p
     └─────┘                    └───┘      └─┬┘ └┬──┘
                                            ┌┴┐ ┌┴┐ 
                                        ( g^a·c + k ) mod p
   *1: WARN: mod q, not p
       k, a, c are all in "mod q namespace" (using IT parlance)
       PK_A, h are in the "mod p namespace"
  
   *2: Note if "Extractor" can trick Alice into REUSING THE SAME RANDOM K 
       then he can solve the following simple equation to recover Alice’s secret:
       RUN 1) challenge c1 ---˃ s1 = a·c1 + k  mod q
       RUN 2) challenge c2 ---˃ s2 = a·c2 + k  mod q
        ==                s1 - s2  / (c1 - c2) mod q
        == (a·c1 + k) - (a·c2 + k) / (c1 - c2) mod q
        ==            a·( c1 - c2) / (c1 - c2) mod q
        ==            a                        mod q 
        ==            a

       REAL ATTACK ON SYSTEMS WITH BAD RANDOM NUMBER GENERATORS.

  *3: M is an optional arbitary message string
      The method also can be used as signature schema since only
      secret holder can produce a signature.
      The resulting protocol is called SCHNORR SIGNATURE SCHEME,
      and it's the BASIS OF PROTOCOLS LIKE EdDSA.

ZKP compared
• While other privacy techniques like bulletproofs, ring
  signatures and stealth addresses, etc. mask the identities of the
  entities involved in a business transaction, ZKP techniques allow to
  prove logical statements without divulging any information and yet
  proving the validity of such proofs. 


zk-SNARK • zk-SNARK stands for: (Z)ero (K)nowledge (S)uccinct (N)on-Inter(a)ctive A(r)gument of (K)nowledge" Succinct == Low resources needed on prober / verifier. • zk-SNARK convert logical statements to arithmetic circuits, that are then leveraged to generate proofs.
zk-Stark • Improves over zk-SNARK by not requiring a trusted pre-setup. - Transparent: public randomness, no "trusted setup" - Argument of Knowledge - post-quantum secure. C⅋P From: https://www.youtube.com/watch?v=_6TqUNVLChc Proof Size Prover Verification Time Time SNARKs 288 bytes 2.3s 10ms (+Rºtrusted setupº) STARKs 45KB-200KB 1.6s 16ms Bulletproofs ~1.3KB 30s 1100ms Implementations: - SNARKs: - Zokrates: DSL to generate proofs and validate them on Ethereum - Bellman: Rust implementation - Snarky: OCalm implementation (DSL) - Libsnark: C++ - Iden3's Circum (DLS) + SnarkJS js implementation - Republic Protocol's zksnark.rs (DSL) Rust impl. - DIZK java distributed system - STARKs: Go/C++ implemntation - Bulletproofs: Ristretto Rust imple. with GREAT documentation Ext. Links • Awesome ZKP: @[https://github.com/matter-labs/awesome-zero-knowledge-proofPurpose] • Tjaden Hess Github: @[https://github.com/tjade273?tab=repositories&q=&type=source&language=]
Homomorphic Encryption
@[https://en.wikipedia.org/wiki/Homomorphic_encryption]
@[http://enigma.media.mit.edu/]

Fully homomorphic Encrypt.
@[https://www.infoq.com/news/2020/06/ibm-fully-homomorphic-encryption/]

•RºWARN:º rather young field which attracts with lot of research.
• Broadly classifiable within secure multi-party computation,
   Homomorphic Encryption is an approach to secure
   computation that does not require decrypting your data in order to
   process them. It enables processing ciphertexts with the guarantee
   that encrypted results match those that would be produced by
   first decrypting input data, processing them, and re-encrypting.

• List of SDKs:
  └ IBM Fully Homomorphic Encryption Toolkit, based on open source HELibº.
    providing a number of low-level routines such set, add, multiply, shift,
    ... along with higher-level features for automatic noise management, 
    multi-threading, and so on.  @[https://github.com/homenc/HElib]
  └ Microsoft SEAL (Simple Encrypted Arithmetic Library)º
  @[https://www.microsoft.com/en-us/research/project/microsoft-seal/]
  └ Google "Private Join and Compute" tool:
  @[https://github.com/google/private-join-and-compute]
Data integrity
BºHash chainº
@[https://en.wikipedia.org/wiki/Hash_chain]
  - non-repudiation 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..."


Shamir Secret sharing (SSS)
@[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. For example 
  "any 2 out of 3" shared pieces will reproduce the key.
   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
- Use Cases:
  - Password/Passphrase protection management
(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 with associated data(AEAD)
@[https://en.wikipedia.org/wiki/Authenticated_encryption]
- 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)
WebApp. Crypto
JWT intro
TODO:
- (Very Good) Introduction to JWT!!!
  @[https://jwt.io/introduction/]
- online JWT debugger to decode, verify and generate JWT,
  detailed list of libraries (Java, Python, C#, Rust,...)
  and other useful info.
@[https://jwt.io/#debugger]

@[https://github.com/tldr-pages/tldr/blob/master/pages/common/jwt.md]

$º$ jwt decode {{jwt_string}}    º  ←  Decode a JWT. 
                                       -j to decode as JSON string

$º$ jwt encode --alg {{HS256}} \ º ← Encode a JSON string → JWT
$º --secret {{1234567890}}     \ º
$º '{{json_string}}'             º

$º$ jwt encode --alg {{HS256}} \ º ← Encode key pair payload to JWT
$º  --secret {{1234567890}}    \ º
$º -P key=value                  º

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. JOSE · JOSE == JSON Object Signing and Encryption == JWS + JWE + JWK + JWA Following is a decoded JSON payload representing an example of JOSE protected header parameters as defined by the JWS JSON Serialization syntax. { "name": "identityKey",← extension 1 "alg" : "ES256K", ← ECDSA using secp256k1 curve + SHA-256 "typ" : "JOSE+JSON", ← media type of complete JWS "b64" : false, ← extension 2 true ⇒ payload=ASCII(BASE64URL(JWS Payload)) "crit": ["b64"], ← Critical extensions that must be accepted "jwk" : { ← pub.key used to sign JOSE header+JWS payload. "kty": "EC", represented as JSON Web Key "use": "sig", ← Intended user "crv": "secp256k1", "x" : "0", ← X-coordinate of corresponding pub key. "y" : "0", ← Y-coordinate of the corresponding pub key. }, } 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/]
GoTrue OAuth
@[https://github.com/netlify/gotrue]

• lightweight open-source and self-standing API for handling
  user registration (signup) and authentication and custom user data.
• based on OAuth2 and JWT. 

• Configuration through ".env" config file or 
  environment variables (GOTRUE_*)

  Config. include options to set (request) rate limits,
  multi-instance (multi-tenant?), DB backend (mysql only as 2021-06),
  logging, tracing, RºJWT and other cryptographic secretsº,
  WEBHOOK_URL (called upon validate/signup/login events),
  WEBHOOK_RETRIES,...

  JWT tokens can also be managed by:
  • Audience (group of users)
  • admin groups 

• External Authentication supported for:
  ✓ bitbucket ✓ gitlab
  ✓ github    ✓ google

  Ex. github external config: 
  GOTRUE_EXTERNAL_GITHUB_CLIENT_ID=my_app_client_id
  GOTRUE_EXTERNAL_GITHUB_SECRET=client_secret_values_sssh

• Support for password recovery through email.
  SMTP config summary:
  GOTRUE_SMTP_HOST=smtp.mandrillapp.com
  GOTRUE_SMTP_USER=smtp-delivery@example.com
  GOTRUE_SMTP_PASS=...
  GOTRUE_SMTP_MAX_FREQUENCY=... ºmin secs to waitºbefore re-sending  
                                 signup confirm/pass reset
  (+ e-mail template file)

• Exposed REST-API endpoints:
  GET /settings: 
  POST /signup  (email + password)
  POST /invite  (email)
  POST /verify  (type:=singup|recovery, token, ...)
                returns access_token + refresh_token
  POST /recover (email)
  POST /token   (OAuth2 endpoint implementing pass/refresh_token/
                 and authorization_code grant types)
  PUT /user     (Update a user).
  POST /logout  (revoke all refresh tokens for user).
       RºWARNº: JWT tokens will still be valid for stateless auth 
                until expiration (1hour by default)

• Alternatives to Gotrue (in some contexts) can be:
  · Keycloak, very complete but "heavy" (Java based) Identity solution.
    Actually gotrue can be seen service provider (SP) connected to Keycloak:
    → keycloak admin console
      → create client:
        ID "https://example.com/.netlify/identity/saml" ← gotrue API endpoint. 
   (@[https://yyhh.org/blog/2020/04/how-to-enable-saml-sso-with-self-hosted-gotrue-and-git-gateway/])
  · Kratos: https://www.ory.sh/kratos/

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

º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 also, 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.509v3 
- X.509 v3:  ←·········· ITU_T standard for Certificate Storage and Serialization
  =========              Used, amongst others, by Internet TLS/SSL protocols.
  Version#               
  Serial Number
  Signature algorithm
  Issuer name
  Validity period
  ---------------
  Subject Name
  Subject PK Info
  Issuer  ID
  Subject ID#
  Extended attributes (Used by different services)
  ──────────────────
  CA3 Signature    ← The signature is the non-repudiable claim made by the CA that
                      X.509 certificate data is valid (from its point of view):

  The ºcertification path validation algorithmº allows
  delegation of signatured to an associative list of "trusted-by" CAs.
  CA1 → trust for   → CA2 → trust for   → CA3 → CA3 Signed Certificate
  └┬┘   certificate   └┬┘   certificate   └┬┘
   ·    issuance       ·    issuance       ·
   ·                   ·                   ·
   ·                   └─ intermediate CAs ┘
  DIRECT TRUST            ASSOCAITVE TRUST

openSSL
• Ext. Refs:
@[https://ciphersuite.info/cs/]:  DDBB about different chipher-suites strenghts
@[https://en.wikipedia.org/wiki/X.509]
@[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 openssl opts:
  · -in   : path for input certificate being examined. Many times 
            STDIN from previous 'openssl s_client ...' is preferred.
            $ openssl s_client ... | openssl ...
  · -noout: prevents encoded version output (of request/response)
  · -text : Show OUTPUT in human readable text (vs hex formated binary)
  · -nodes: flag: ºDO NOTº pass-phrase-encrypt Pub.Key

• Commonly used script/batch ENV.VARs:
  export DOMAIN="mydomain.com"
  export SUBJ="/C=ES/ST=Aragon/L=Zaragoza/O=MyOrganization/CN=${DOMAIN}"
  export NUM_OF_DAYS="999"

  ######################################################
• # Request→create→install new Server Certificate Flow #
  ######################################################
  admin→admin: Create Private Key ← Pub.Key autogenerated from Priv.Key
  alt                                
    admin→admin : Sign self-Cert  ← Dev. Purposes
  else:                              
    admin→admin: Create CSR       ← CSR: Cert. Signing Request with Pub.key
┌→  admin→CA    : CSR                
│   CA←→admin   : Validate KYC,...← KYC: "Know Your Customer"
│   CA→CA       : Create Cert     ← Happy path. CSR approved.  
│   CA→amdin    : Cert.          
│   admin→server: Cert.           ← Server: Apache, Nginx, ...
│ 
└─ $ openssl req º-newº -nodes              ← Create key + CSR.
   -newkey rsa:2048 -keyout ${DOMAIN}.key \   ← Replace -newkey ... -keyout ...
   -out ${DOMAIN}.csr -subj "${SUBJ}" \         by -key ${DOMAIN}.key to reuse
                                                already existing private key
   -addext "subjectAltName = DNS:foo.co.uk" \ 
   -addext "certificatePolicies = 1.2.3.4" \  ← Can Sign? Can 


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


Bº#######################º
Bº# Certificate Formats #º
Bº#######################º
  
• X.509 v3+ ENCODINGS:
  · DER: (Binary) DER == ASN.1 (D)istinguised -vs Basic/Canonical- (E)ncoding (R)ules 
  · PEM: (Base64) PEM == (P)rivacy (E)nhanced (M)ail, prefixed with "—– BEGIN ..."
        ºDefault encoding in OpenSSL/ssh/.... Easier to C⅋Pº
• Common FILE-EXTENSIONS:
  · *.CRT: Certificates encoded as binary DER/PEM.
  · *.CER: Mostly similar to .CRT, recognized by some Micrsooft apps.
  · *.KEY: used for private PKCS#8 keys encoded as DER/PEM.
 
• RELATED STANDARDS: PKCS #7, PCKS #12  @[#PKCS_summary]
            P7B ASCII files which can contain (non-secret) Certs. and CA certificates.
 
 - PKCS#12: FILE FORMAT commonly used for (PRIVATE)KEYSTORES, protected with 
            password-based symmetric key. Used by:
            - Java key store
            - client auth. certs in Firefox, Apache Tomcat, ...
            - "PFX" files.
                                                                       # CONVERTING TO/FROM
 $ openssl x509 -inform pem -in ${DOMAIN}.crt \                        # PEM   → DER
   -outform der -out ${DOMAIN}.der
 $ openssl x509 -inform der -in ${DOMAIN}.der \                        # DER   → PEM
-outform pem -out ${DOMAIN}.crt
 $ openssl crl2pkcs7 -nocrl -certfile ${DOMAIN}.crt \                  # PEM   → PKCS7
   -certfile ca-chain.crt -out ${DOMAIN}.p7b
 $ openssl pkcs7 -in ${DOMAIN}.p7b -print_certs -out ${DOMAIN}.crt     # PKCS7 → PEM
 $ openssl pkcs12 -inkey ${DOMAIN}.key \                               # PEM   → PKCS12
    -in ${DOMAIN}.crt -export -out ${DOMAIN}.pfx
 $ openssl pkcs12 -in ${DOMAIN}.pfx -nodes -out ${DOMAIN}.combined.crt # PKCS12 → PEM
 $ openssl x509 -in ${DOMAIN}.cer -outform PEM -out ${DOMAIN}.pem      # x509 → PEM

Bº##################º
Bº# Random Recipes #º
Bº##################º

 $ openssl x509 -in ${DOMAIN}.crt \ ← GenerateºFINGERPRINTºfrom TLS certificate.
   -noout -fingerprint -sha256        CRYPTOG_HASH(public_key) used as ID of pub.keys
  fa:23:a4:48:............:56

 ºFETCH 1ST-IN-CHAIN WEB CERT.º                 ºcheck 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


 ºLIST SUPPORTED CIPHERSº
│$ openssl ciphers -s -tls1_3 ← -s -tls1_1: filter for sepcific TLS version  
 → TLS_AES      _256_GCM_SHA384:TLS_AES      _128_GCM_SHA256:...

 ºtest cipher-suite against serverº
│ $ openssl s_client \              Ex:  
│   -connect domain.com:443 \      Using weak (128bit) cipher will probably fail
│   -cipher PSK-AES128-CBC-SHA \ ← or -tls1_1 to test TLS supported version.
│   -quiet -no_tls1_3           

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


Bº#############################
Bº# Examine Cert. Extension/s #
Bº#############################
$ openssl x509 \               checkºSubject Alternative Name(SAN) extensionº,
  -in ... -noout \             used to associate 1+ values (FQDNs,...) to 1 Cert. 
  -ext subjectAltName       ←  Also used as alternative to deprecated common name.
→ X509v3 Subject Alt. Name:    NOTE: Use commas to separate 2+ extensions:
→   DNS:*.domi01.com, DNS:...  OTHER WIDELY USED X509 EXTENSIONS INCLUDE:
                               ·º'basicConstraints'º
                               ·º'keyUsage'º (Can Sign?, Can Sign CRL?...)
                               (leave -ext alone to show all extensions in Cert)


Bº##########################º RºWARN:º Some companies/apps have deprecated CRLs in
Bº# CRL how-to with OpenSSL #º favor of ºOnline Certificate Status Protocol (OCSP)º
Bº##########################º CRL == Cert. list of ALREADY revoked Certs.

 $ edit .../intermediate/openssl.cnf PRE-SETUP) Set crl_day check period:
  [ CA_default ]                     ====================================
  ...
 ºdefault_crl_days = 30º         ← periodic checking ...                     
  [ server_cert ]
  # ... snipped ...
 *crlDistributionPoints = URI:http...  ← See man for + crl options
 
 
 $ export CLR_OUTPUT=intermediate/crl/intermediate.crl.pem
 
 $ cd ~/ca                           STEP 2: Periodically recreate CLR
 $ openssl ca \                      =================================
   -config intermediate/openssl.cnf \ (perioadically according to 
  º-gencrlº \                           default_crl_days defined in STEP 1)
   -out ${CLR_OUTPUT}
 
 $ openssl crl \                     STEP 3: Verify output of STEP 2:
   -in ${CLR_OUTPUT} \               ================================
   -noout -text
 → ... No Revoked Certificates
  (No certificates have been revoked yet)
 
 STEP 4: make CLR_OUTPUT accessible through HTTP URL indicated in STEP 1
 =======================================================================
 
 NOTE: For servers authenticating clients through X.509 certs,
       copy the generated crl file to a path indicated by the server config
       ('SSLCARevocationPath' in Apache HTTP, 'crl-verify' in OpenVPN,...)
 
 $ cd ~/ca                            REVOKE A CERTIFICATE:
 $ openssl ca \                       =====================
   -config intermediate/openssl.cnf \
  º-revokeº \
   intermediate/certs/bob@example.com.cert.pem
 
 NOTE: CRL distribution points in X.509 Certs visible in X509v3 details.
       # openssl x509 -in ${DOMAIN}.cert.pem -noout -text
       ...
       º X509v3 CRL Distribution Points: º
       
             Full Name:
       º       URI:http://domain1.com/intermediate.crl.pem º
       ...

Bº#############################º
Bº# check TLS cert.expiration #º [monitoring]
Bº#############################º
@[https://www.cyberciti.biz/faq/find-check-tls-ssl-certificate-expiry-date-from-linux-unix/]
  $ export server="www.nixcraft.com"
  $ export port="443"
                                 Show validity/expiration dates for CERT
                                 =======================================
  $ echo | \                   ← Avoid pressing CTRL+C
    openssl s_client \         ← implements generic TLS network client 
    -servername $server \      ← Set TLS Ser.NameIndication(SNI)@ClientHello msg 
    -connect $server:$port  | \
    openssl x509 \             ← Run certificate display and signing utility.
                                 Use '-in file_input.pem' if no STDIN is present.
        -noout \               ← Prevent encoded version output
       º-datesº                ← show also start+expiry dates
  (Output will be similar to...)
  depth=2 C = US, O = Inet Sec...Group, CN = ISRG Root X1
  verify return:1
  depth=1 C = US, O = Let's Encrypt, CN = R3
  verify return:1
  depth=0 CN = www.nixcraft.com
  verify return:1
  DONE
 ºnotBefore=Nov 11 01:15:45 2021 GMTº
 ºnotAfter=Feb  9 01:15:44 2022 GMT º

                                 Check: expiration date before 4 months?
                                 =======================================
  $ echo | \                   ← Avoid pressing CTRL+C
   ºopenssl s_clientº\         ← implements generic TLS network client 
    -servername $server \      ← Set TLS Ser.NameIndication(SNI)@ClientHello msg 
    -connect $server:$port  | \
   ºopenssl x509º\             ← Run certificate display and signing utility.
                                 Use '-in file_input.pem' if no STDIN is present.
        -noout \               ← Prevent encoded version output
        -enddate \
        -checkend 10540800     ← == 4months x 30.5days/m x 24hour/d x 3600 secs/h
  (Output will be similar to...)
  ... 
  DONE
  notAfter=Feb  9 01:15:44 2022 GMT
 ºCertificate will expireº     ← $? will return 1 (it will expire!)


# Email settings 
# See https://www.cyberciti.biz/mobile-devices/android/how-to-push-send-message-to-ios-and-android-from-linux-cli/ #
source ~/bin/cli_app.sh
push_to_mobile "$0" "$_sub. See $_to email for detailed log. -- $HOSTNAME " >/dev/null
fi
Validate DNSSEC from cli
@[https://www.cyberciti.biz/faq/unix-linux-test-and-validate-dnssec-using-dig-command-line/]
Caddy HTTPS server
@[https://caddyserver.com/]

- Caddy simplifies your infrastructure. It takes care of TLS
  certificate renewals, OCSP stapling, static file serving, reverse
  proxying, Kubernetes ingress, and more.

- Its modular architecture means you can do more with a single, static
  binary that compiles for any platform.

- Caddy runs great in containers because it has no dependencies—not
  even libc. Run Caddy practically anywhere.

https://github.com/AmadeusITGroup/AutoSSL
Automated SSL certificates monitoring, renewal and deployment from blueprint.
module for Python 2.7+/3.5+ that can be used to to automate SSL certificate monitoring, renewal and deployment.

This module can be customized with plugins mechanism to support any type of:
- server: where the certificate is deployed, can be 1 or more server,
  potentially of different types
- storage: where to store your artifacts (private key, public
  certificate, ...)
- tracking mechanism: how to track renewal process (ticket creation)
- renewal method: how to get a new certificate (local CA, ACME
  protocol, ....)

AutoSSL in OpenLiberty https://developers.redhat.com/blog/2020/10/07/install-a-signed-certificate-with-open-liberty-20-0-0-10s-automatic-certificate-management-environment-support-2-0/ - Red Hat Runtimes now supports the new Open Liberty 20.0.0.10 Java runtime. Open Liberty 20.0.0.10 features support for the Automatic Certificate Management Environment (ACME) protocol, which automates the process of obtaining a certificate signed by a certificate authority (CA). The Open Liberty 20.0.0.10 release also includes many bug fixes.
Portecle: Cert+Keystore GUI
@[https://www.sslsupportdesk.com/portecle-advanced-keystore-creation-and-manipulation-tool/]
• user friendly Java GUI: import/create/manage/examine/convert keystores, key-pairs,
  certificates, certificate signing requests, CRL, ...
• Scenario 1: server lacking the capability of generating a CSR keypair on its own.
• Scenario 2: large networks of servers faced with a CSR keypair on one system
              environment that needs key store conversions to it into a different
              environment (ussually very time consuming and frustrating).

• Use Cases examples:  
  - Create, load, save, and convert keystores.
  - Generate DSA and RSA key-pair entries with self-signed X.509 certificates.
  - Import X.509 certificate files as trusted certificates.
  - Import key pairs from PKCS#12.
  - Clone and change the password of key pair entries and keystores.
  - View the details of certificates contained within keystore entries.
    certificate files, and SSL/TLS connections.
  - Export keystore entries in a variety of formats.
  - Generate and view certification requests (CSRs).
  - Import Certificate Authority (CA) replies.
  - Change the password of key pair entries and keystores.
  - Delete, clone, and rename keystore entries.
  - View the details of certificate revocation list (CRL) files.
RFC 8555: PKI using X.509
@[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.
IETF ACME
@[https://tools.ietf.org/html/rfc8555]
- ACME stands for Automatic Certificate Management Environment (ACME) protocol.
- Public Key Infrastructure using X.509 (PKIX) certificates are used
  for a number of purposes, the most significant of which is the
  authentication of domain names.  Thus, certification authorities
  (CAs) in the Web PKI are trusted to verify that an applicant for a
  certificate legitimately represents the domain name(s) in the
  certificate.  As of this writing, this verification is done through a
  collection of ad hoc mechanisms.  This document describes a protocol
  that a CA and an applicant can use to automate the process of
  verification and certificate issuance.  The protocol also provides
  facilities for other certificate management functions, such as
  certificate revocation.
Certs Transparency
@[https://www.certificate-transparency.org/]
• Context: No efficient method/protocol was in place before to allows fetching a 
  FULL LIST OF ISSUED CERTIFICATES FOR A GIVEN DOMAIN. Any byzantine CA could 
  issue malicious certificates to cheat users and spy their (supposely secure) 
  encrypted traffic.

• Cert. Transparency is an Open framework for Cert. Auditing. 
  Admins and security teams can use it to supervise wrong issues certificates. 

• Starting 2018, Google Chrome (and others) will not trust any certificate not 
  passing Cert. Transparency requirements.

• Main objectives:
  • Minimize the possibility for a CA to issue a new TLS Cert. for a given domain, 
    without domain owner being aware of it.
  • Provide an open auditing system for any domain owner/CA to query if some 
    given certificate has been issued by error or maliciously in nearly real time.
  • Protect users from maliciously issued certs.
  • Identify byzantine/maliciously-behaving Certificate Authorities (CAs).

• Definition:
  •ºCertificate LOGSº: Simple network services  keeping CRYPTOGRAPHICALLY
    SECURE AND PUBLICLY AUDITABLE, APPEND-ONLY RECORDS OF CERTIFICATES.
    · Anyone (most probably CAs)  can submit certificates to a log.
  •ºMonitorsº: 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:
    1) verify that logs behave correctly and are cryptographically consistent.
       IF THAT'S NOT THE CASE, THE LOG WILL NEED TO EXPLAIN ITSELF OR RISK BEING
       SHUT DOWN.
    2) verify that a particular certificate appears in a log. 
       Particularly important auditing function because the Cert.Transp. framework
       requires that all SSL certificates be registered in a log. If a Cert. 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.

• Trillian: implementation of concepts described in VerifiableDataStructures.pdf
  white paper, which in turn is an extension and generalisation of the ideas
  which underpines @[https://certificate-transparency.org]


SASL
https://en.wikipedia.org/wiki/Simple_Authentication_and_Security_Layer

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

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


As of 2012 protocols currently supporting SASL include:
- Application Configuration Access Protocol
- Advanced Message Queuing Protocol
- Blocks Extensible Exchange Protocol
- Internet Message Access Protocol
- Internet Message Support Protocol
- Internet Relay Chat (with IRCX or the IRCv3 SASL extension)
- Lightweight Directory Access Protocol
- libvirt
- ManageSieve (RFC 5804)
- memcached
- Post Office Protocol
- Remote framebuffer protocol[8] used by VNC
- Simple Mail Transfer Protocol
- Subversion svn protocol
- Extensible Messaging and Presence Protocol
Cert.Authorities (CAs)
Let's Encrypt
@[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"""
- OCSP lookups can be performed on transaction or authorization level,
  but CRLs must be updated at intervals.

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

Alice wishes to perform a transaction with Bob.
Alice → Bob: Alice pub.key Certificate
Bob   → Bob:(concerned that Alice's priv.key is compromised)
             creates an 'OCSP-request'
                        --------------
                        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

- See also: 
- ldapsearch:  CLI utility for querying an LDAP directory.
@[https://github.com/tldr-pages/tldr/blob/master/pages/common/ldapsearch.md]
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
OpenPGP
Summary
  PGP: Pretty Good Privacy: encryption program (1991 Phil Zimmermann)
       Used for signing, encrypting, and decrypting texts, e-mails,
       files, directories, disks, e-mails.
  
  OpenPGP: Open Standard around PGP software (RFC 4880)

  GPG: Gnu Privacy Guard implementation

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


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

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

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

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

   -ºSAFE CLEAN-UPº:
    $º$ shred -n 2 -z -v secrets.txtº  ← safe/secure deletion. Standard
                                         "rm" leaves original bytes in the 
                                         hard-disk

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

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

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

- cli Ussage example:
  - Sign a json document:
  $ openpgpsignature2019 sign -u "3AF00854CF8D9237" \
    $(pwd)/src/__tests__/__fixtures__/documents/example.json \
    did:btcr:xxcl-lzpq-q83a-0d5#yubikey
  - Verify a document:
  $ openpgpsignature2019 verify $(pwd)/src/__tests__/__fixtures_\
    _/documents/exampleSigned.json

- library ussage example:
  const keys = await OpenPgpSignature2019.generateKey({....})
  const signedData = await OpenPgpSignature2019.sign(
      { data: jsonDoc,
        privateKey: keys.privateKey,
        proof: {
          verificationMethod: "https://example.com/i/alice/keys/1",
          proofPurpose: "assertionMethod"
        }
      });

  const verified = await OpenPgpSignature2019.verify({
    data: signedData,
    options: ...
  });
Keybase ("GPG++")
@[https://julien.ponge.org/blog/simpler-gnupg-with-another-look-at-keybase/]
- Keybase essentially introduced a modern way to build trust networks, because
  people can check that user123 on Keybase is also user123_coder on GitHub,
  user123 on Twitter, and that the user owns the iamuser123.org domain. One can
  do so by posting Keybase-signed messages to these social networks and places.
  This is a good idea, because from social networks and Keybase accounts linked
  to those social networks, you can build a trust network on Keybase.

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

@[https://github.com/tldr-pages/tldr/blob/master/pages/common/keybase.md]  [TODO]
  More info at: @[https://keybase.io/docs/command_line]
guncat
@[https://fbb-git.gitlab.io/guncat/]

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

Guncat  acts like cat, but unencrypts encrypted sections encountered in
the files processed by guncat, copying the unencrypted  information  to
guncat's  standard  output  stream, which may thereupon be processed by
other tools.
OpenPGP.js
@[https://github.com/openpgpjs/openpgpjs]
JavaScript implementation of the OpenPGP protocol defined in RFC 4880.
- a/symmetric (En/de)crypt Uint8Array with PGP key/password.
- Encrypt with compression
- Data Streaming support.
- key pair generation / revocation.
- "Push"/"pull"  public keys from HKP server
- Sign/verify cleartext/Uint8Array stream messages
  (detach signature support)
Standard Protocols
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: protocol protecting integrity and authenticity of email.
• It is the result of combining several components, including:
  • Sender Policy Framework (SPF) + Domain Keys Identified Email (DKIM):
    to help verify email authenticity. 
• There are also different levels of DMARC policies:
  • "p=none"   policy: enables organizations to monitor their email systems
                       for senders,
  • "p=reject" policy: block non-compliant messages completely. 
• BOD 18-01 mandates the use of the p=reject policy by Oct.16.    [compliance]
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) @:
          @[https://en.wikipedia.org/wiki/Cryptographic_Message_Syntax]
• ºPKCS #8 º to protect priv.cert Key (and its 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         [standards.hardware]
             ("Cryptoki") API defining a generic interface 
             https://en.wikipedia.org/wiki/PKCS_11"
- º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]
WebCrypto API
BºWebCrypto API providesº;
  "relatively" new browser API helping efficient and secure delivery
  of cryptographic primitives.
  - low-level ciphers.
  - hashes
  - "other" encryption components.

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

   See also: Trusted web code at @[/WebTechnologies/map.html?query=trusted.web.code]
OASIS STANDARDS
XAdES
@[https://www.w3.org/TR/XAdES/]
XML Advanced Electronic Signatures (XAdES)
DSS
OASIS XML Digital Signature Services (DSS) TC
(Not to be confused with Digital Signature Standard DSS)
@[https://www.oasis-open.org/committees/tc_home.php?wg_abbrev=dss]

https://ec.europa.eu/cefdigital/wiki/display/CEFDIGITAL/Start+using+Digital+Signature+Services+-+DSS
ºopen-source software libraryº for ºelectronic signature creation and
validationº. DSS supports the creation and verification of interoperable
and secure electronic signatures in line with European legislation.
In particular, DSS aims to follow the eIDAS Regulation and related standards closely.

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

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

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

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

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.
JaDES vs EADES
Why do we want to support AdES formats using x509 certificates? JAdES
may be the only one worth considering if it can be used e.g. in a VC
proof and under certain conditions... I'd even argue that JAdES could
be just the adoption of a VC with a well defined proof format, but
I'm not sure this is the plan of ETSI ESI TC.

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

I agree with Oscar BURGOS in that the only one worth considering is
JAdES, and even so I do not think that EBSI should do anything. They
were put in the document as a reminder, because AdES formats are the
ones widely legally accepted for business transactions, eg.
eInvoincing. But as Oscar says, ideally (using the axample of a
eInvoice), the eInvoice could be represented as a VC.
However, I would like to check that we are not doing something
"incompatible" or that makes somewhat difficult that representation
(I have no idea of what can it be, just it may be woth checking).
The JAdES standard is ongoing work in ETSI
(https://portal.etsi.org/webapp/WorkProgram/Report_WorkItem.asp?WKI_ID
=52897), and they want to publish in March this year.
Anyway, I will try to talk with Juan Carlos Cruellas, who is the
person more active driving the drafts, just to see if they are aware
and check.
X.509 TimeStamp Protocol
@[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
Quality Assurance
Project Everest
@[https://project-everest.github.io/]

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

- introduced in @[https://eprint.iacr.org/2020/572]
- Using F* (@[https://www.fstar-lang.org/])formally probed language
  for implementation of cryptographic primitives (otherwise
  extremely difficult and error prone to implement in C/Rust/...).
- formally-verified Curve25519, ChaCha20, Poly1305,
  P256 elliptic curve for ECDSA and ECDH, GCM, P384/P521 elliptic
  curves, ECDSA signature scheme,...
- Performance close to native assembler manual implementation
- Fiat-Crypto project:
  @[http://adam.chlipala.net/papers/FiatCryptoSP19/FiatCryptoSP19.pdf]


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

- See also:
- Formally Verified Cryptographic Web Applications in WebAssembly
https://www.computer.org/csdl/proceedings-article/sp/2019/666000b002/19skg8v5fZS
Software Development
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.

Ursa library
@[https://www.hyperledger.org/use/ursa]
- Hyperledger Ursa is a shared cryptographic library, it enables
  implementations to avoid duplicating other cryptographic work and
  hopefully increase security in the process. The library is an opt-in
  repository (for Hyperledger and non Hyperledger projects) to place
  and use crypto. Hyperledger Ursa consists of sub-projects, which are
  cohesive implementations of cryptographic code or interfaces to
  cryptographic code.
WARN: ☞ CRYPTOGRAPHY IS HARD, PROTECTING SECRETS IS (MUCH) HARDER!!!☜


Wallets
Wallet vs KeyStore vs Vault
- In a KeyStore, secrets are kept safe until needed by an application.
  At that moment the secret becomes vulnerable to any virus/warm/attacker on 
  the Operating System.
- Keystores are generic for any type of app.

- Vaults are mostly the same that Keystores. In clouds, vaults ussually
  provide access policies (that probably are not available in local
  key-stores).

- In hardware wallets secrets 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", ...
  Software wallets offer the same functionality as hardware wallets, or 
  even more, but are exposed to the underlying security leaks of the OS 
  (virus, warms, software leaking secrets, ...)
  - A wallet makes use of a keystore.
  - Wallets are mostly used for blockchain-like applications or digital 
    signature applications.
  - HD wallets stand for Hierarchical deterministic wallets, and allow 
    to deterministically generate a tree of new secrets from an initial
    "seed" secret. Note that public addresses are mathematically 
    determined from the diferent secrets.

  NOTE: Vaults, being a "cloud marketing" biased nomenclature, can 
    include wallet-like functionality allowing to sign input and get
    signed output from the vault, with no intervention from the original
    ("unsecure") app. For example Parity considers vaults to be """
    an additional privacy feature on top of wallets to lock away accounts
    behind a second layer of protection encrypting the meta-data
    (public addresses,...) """.
HD Wallets
• HD stands for Hierachical Deterministic.
• HD wallets (BIP-32, by Pieter Wuille) allow to create N safe private keys
  from a single root "master" key (and its associated N public keys/addresses).
• Also, it is possible to generate the public keys of these
  key-pairs even without access to the private keys, allowing generation
  of new (receive) addresses even when the wallet is encrypted or the
  private keys are stored on a separate device.

  SEED → MASTER     CHILD          GRANDCHILD
         KEY        KEYS           KEYS
         ======     =====          ==========
         k_m ┬····→ k_m[0]·┬····→  k_m[0][0]
             │             ├─···→  k_m[0][1]
             │             ├─···→  k_m[0][2]
             │             ├─···   ...
             │
             ├····→ k_m[1]·┬····→  k_m[1][0]
             │             ├─···→  k_m[1][1]
             │             ├─···   ...
             │
             ├····→ k_m[2]·┬····→  k_m[2][0]               
             ...           ├─···→  ...

• Use-cases:
  - Preserve anonymity by using many receive addresses.
  - Protect against key-lost      (theorical advantage only?)
  - Allow for easier key rotation (theorical advantage only?)

@[https://medium.com/@robbiehanson15/the-math-behind-bip-32-child-key-derivation-7d85f61a6681]
Robbie Hanson
 ┌ extending parent PRIVATE key to create child PRIVATE key ──┐
 │                                                            │
 │ INPUT                                      OUTPUT          │
 │ =====                                      ======          │
 │ k=parent   ·····························→  a=k+h,child[0]  │
 │ priv.key                  h=left    ┌···→  priv.key        │       
 │ (256bits)                   256bits ·      (256bits)       │
 │  ·                                  ·       │              │
 │  v                                  ·       v              │
 │ K=parent ······→ HMAC─SHA512        ·        child[0]      │
 │ pub.key     ┌··→ (512bits)    ······┤      pub.key         │
 │ (264bits)   · ┌→ one─way func       ·      (264bits)       │
 │ K=G·k       · ·                     ·      A =G·(k+h)      │
 │             · ·                     ·                      │
 │ Parent      · ·                     └···→  child[0]        │
 │ Chain Code ·┘ ·                   rigth   Chain Code       │
 │ (256bits)     ·                   256bits (256bits)        │
 │               ·                                            │
 │ Idx Number    ·                                            │
 │ (32 bits)   ··┘                                            │
 │ e.g. [0])                                                  │
 └────────────────────────────────────────────────────────────┘

 ┌ extending parent PUBLIC  key to create child PUBLIC  key ──┐
 │                                                            │
 │ INPUT                                      OUTPUT          │
 │ =====                                      ======          │
 │ k = parent ← Not really needed!!!                          │
 │ priv.key                                                   │
 │ (256bits)                                                  │
 │   ·                               left                     │
 │   v                               256bits                  │
 │ K=parent                            ┌···→  child[0]        │          
 │ pub.key     ┌··→ (512bits)    ······┤      pub.key         │
 │ (264bits)   · ┌→ one─way func       │      (264bits)       │
 │ (K=G x k)   · ·                     │      A=  K + G·h     │
 │             · ·                     │       =G·k + G.h     │
 │             · ·                     │                      │
 │ Parent      · ·                     └···→  child[0]        │
 │ Chain Code ·┘ ·                   rigth    Chain Code      │
 │ (256bits)     ·                   256bits  (256bits)       │
 │               ·                                            │
 │               ·                                            │
 │ Index Number  ·                                            │
 │ (32 bits)   ··┘                                            │
 │ e.g. [0]                                                   │
 └────────────────────────────────────────────────────────────┘

- See also. Andrea Corbellini Online tools: 
  ECC mul: @[https://andrea.corbellini.name/ecc/interactive/modk-mul.html]
  ECC add: @[https://andrea.corbellini.name/ecc/interactive/modk-add.html]

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://github.com/GridPlus]
@[https://blog.gridplus.io/lattice1-sdk-and-generalized-signatures-e17da7cf65d7]
- Generalized remote (WiFi, Bluetooth?,...) transaction signer.
  Private key is never transmited outside the hardware.

- Update 2020-10-22: First pre-orders available:
@[https://blog.gridplus.io/from-idea-to-reality-the-first-lattice1-hardware-wallets-have-shipped-5e9672e89c32]

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



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

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

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

BºSECURING COMPONENTS AND SEPARATING CONCERNSº
- robust and secure connection between application
  ("wallet GUI") and TX builder/signer components.

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

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

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

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

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

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


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

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

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

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

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

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

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

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

    sdk.createAutomaticPermission(req, (err, res) =˃ {
      ... do stuff ...
    })
Azure Sphere Pluton
@[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.
"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/]         [standards.hardware]

- 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] [TODO]
  º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
- ...?
Gemalto: Data protection AaS
@[https://safenet.gemalto.com/resources/data-protection/data-protection-as-a-service-suite-solution-brief/]
TresorSGX
- TresorSGX is a attempt to isolate and secure a operating system
  component of the Linux kernel. It outsources a functionality of a
  kernel module into a SGX container / enclave. TresorSGX provides a
  cryptographic algorithm for the Linux Crypto API which is executed in
  the secured container. The cryptographic key material is guarded from
  unauthorised access of unprivileged and privileged components at any
  time. This protects the disk-encryption system from cold-boot and DMA
  attacks on the key material.
Others
Fuzzy Encryption
@[https://github.com/decentralized-identity/fuzzy-encryption]

- A variant of a Fuzzy Vault cryptographic scheme, Bºdesigned forº
Bºencrypting secrets that can be more easily recovered by humans.º
KMIP: Key Mng.Interop.Prot. PKCS#11 

KMIP: @[https://en.wikipedia.org/wiki/Key_Management_Interoperability_Protocol_(KMIP)]
A KMIP server stores and controls Managed Objects such as symmetric
and asymmetric keys, certificates, and user defined objects. Clients
then use the protocol to access these objects subject to a security
model that is implemented by the servers. Operations are provided to
create, locate, retrieve and update managed objects.

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

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

The types of managed objects that are managed by KMIP include

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

The operations provided by KMIP include

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

hashcat is the world's fastest and most advanced password recovery
utility, supporting five unique modes of attack for over 200
highly-optimized hashing algorithms. hashcat currently supports CPUs,
GPUs, and other hardware accelerators on Linux, Windows, and macOS,
and has facilities to help enable distributed password cracking.
Extract Key from Java Keystore
https://dzone.com/articles/extracting-a-private-key-from-java-keystore-jks
https://medium.com/java-user-group-malta/importing-existing-certificates-into-a-keystore-using-openssl-905d9e0b7175
Toplip: Strong File encrypt
@[https://www.ostechnix.com/toplip-strong-file-encryption-decryption-cli-utility/]

Titan: Cli pass.manager https://www.ostechnix.com/titan-command-line-password-manager-linux/
AMD Sec.Processor: Mem.Encryption
https://www.techpowerup.com/review/amd-epyc-server-architecture/3.html
Non-Classified/TODO/Backlog
Chiness Standards (SM? vs RSA...)
SM2, SM3, SM4 replace RSA, SHA , AES
Post Quantum Guide
https://hackernoon.com/a-guide-to-post-quantum-cryptography-d785a70ea04b
BLS Signature Scheme
@[https://medium.com/@srikarv/the-bls-signature-scheme-a-short-intro-801c723afffa]
... Some prominent encryption schemes in literature and the fundamental
reasoning behind their formulation include:

- Boneh — Lynn — Shacham (BLS): Based on the existence of random
  oracles and the intractability of the computational Diffie-Hellman
  problem in a gap Diffie-Hellman group.
- ElGamal: Based on the hardness of the discrete logarithm problem.
- ECDSA: Based on the fact that given a point A on an elliptic curve
  and another point P = n*A, it is difficult to find n.
- Ring signature: Any non-empty subset of a group of n people can
  sign a message without the identity of any of the participants being
  leaked. It is a signature scheme built on other schemes.
- RSA: Factorization of numbers (semi-primes in particular) is hard.
- Schnorr Signature: Based on the hardness of the discrete logarithm problem.
Pairing primitives
@[https://www.math.uwaterloo.ca/~ajmeneze/publications/pairings.pdf]
  Bilinear pairings have been used to design ingenious 
  protocols forsuch tasks as one-round three-party key agreement, 
  identity-based encryption,and aggregate signatures. Suitable bilinear 
  pairings can be constructed fromthe Tate pairing for specially chosen 
  elliptic curves.  Thisarticle gives anintroduction to the protocols, 
  Tate pairing computation, and curve selection.
Trusted Signature Pad
https://www.google.com/search?q=trusted+signature+pad
OKKA ASA: Ssh + PKI
@[https://dzone.com/articles/ssh-is-dead-long-live-ssh-one-million-ssh-logins-w]

·Bº...more of our customers have come to the realization that server º
 Bºaccess is an identity problem first and foremost.... º
 BºThe more you can unify access with identity, the better.º

· "...Our customers use Okta Advanced Server Access  (Okta ASA) to 
  securely automate identity and access controls for their teams to use 
  SSH safely. And we've just reached a significant adoption milestone 
  by registering over 1 million SSH logins per month... and growing!..."
 ºWith Okta ASA, SSH logins now follow a familiar Single Sign-On experience,º

· SSH transport protocol is inherently secure; however, the backing    [secret_mng]
  credential mechanism is prone to human error-with potentially 
  catastrophic results....  companies have traditionally been forced 
  to do one of the following:
  - Implement a security policy forcing users to rotate their personal SSH Keys (easiest, least secure).
  - Operate a secure vault service storing SSH Keys, checked out on demand (harder, more secure).
  - Purchase and deploy a privileged access management product to act as a gateway for remote access (hardest, most secure).

· traditional Public Key Infrastructure backing SSH was built for a 
  different time, where a key exchange meant enough to grant trust. 

· OpenSSH introduced in 2011 the capability to authenticate using a
  Client Certificate (vs SSH Key). Client Certs. metadata carry 
  cryptographically verifiable metadata to store usernames, roles, ... 
  and an ºexpiration dateº.
Aggregated Signatures

REF: @[https://arxiv.org/pdf/1911.04698.pdf]
Aggregate Signature protocols:
.... CoSi protocol is based on SCHNORR SIGNATURE AGGREGATION,
     which is an INTERACTIVE protocol: 
     aggregated Schnorr-signature for a single message
     requires all  the  singers  collaboration to generate
     1) shared challenge-string in the "Challenge" phase of CoSi-protocol.
     2) challenge-string of 1) as input for each signer to
        generate its SIGNATURE SHARE.
     Hence:
     - A LEADER IS REQUIRED TO ORCHESTRATE THE WHOLE PROCESS.
     - protocol  needs  to  take  multiple  rounds.

 ...  our  aggregated  signature  gossip  protocol is based on
      NON-INTERACTIVE BLS SIGNATURE AGGREGATION SCHEME. 
     Hence:
     - coordination  among nodes is eliminated.
     - instead  of communication tree, gossip protocol is 
       used to propagate the aggregated signatures.
     These lead to simple+robust design which could be easier
     to implement in practice.
Fully Homomorphic Encryption (FHE) SDK
IBM Launches Fully Homomorphic Encryption (FHE) Toolkit for Linux - 9to5Linux
@[https://9to5linux.com/ibm-launches-fully-homomorphic-encryption-fhe-toolkit-for-linux]
Trusted Data Format (TDF)
@[https://github.com/virtru/tdf-spec]

• Trusted Data Format (TDF) is an Open, Interoperable, JSON encoded 
   data format for implementing Data Centric Security for objects (such 
   as files or emails). This repository specifies the protocols and 
   schemas required for TDF operation. 

• manifest.json  ── (references) ─→ encrypted payload file/s

• HTML+css , manifest.json ── (references) ─→ Encrypted payload/s

• There are three principle element-types within a TDF's manifest.json:
  - Encryption Information: for encrypting, signing, or integrity 
    binding of Payloads and Assertions.
  - Payload Reference(s): reference(s) to the encrypted payload.
  - Assertion(s): statement(s) about payload(s); this is optional and 
    not shown below.
(Quantum)Lamport Sign.
- quantum-proof cryptographic signatureS
- Quantum Safe Ethereum proxy with
  Winternitz One-Time signatures
  @[https://github.com/tjade273/QEth]