diff options
author | Peter Dettman <peter.dettman@bouncycastle.org> | 2018-04-08 17:48:02 +0700 |
---|---|---|
committer | Peter Dettman <peter.dettman@bouncycastle.org> | 2018-04-08 17:48:02 +0700 |
commit | 79055149405e986176bbb177a8897770e1777974 (patch) | |
tree | fc167830f416ebc3b3df4b769cc46be73cc4337d | |
parent | Latest scrypt updates from bc-java (diff) | |
download | BouncyCastle.NET-ed25519-79055149405e986176bbb177a8897770e1777974.tar.xz |
Port of BLAKE2B/2S digests from bc-java
- also some misc. changes for other digests
-rw-r--r-- | crypto/BouncyCastle.Android.csproj | 3 | ||||
-rw-r--r-- | crypto/BouncyCastle.csproj | 3 | ||||
-rw-r--r-- | crypto/BouncyCastle.iOS.csproj | 3 | ||||
-rw-r--r-- | crypto/crypto.csproj | 25 | ||||
-rw-r--r-- | crypto/src/asn1/misc/MiscObjectIdentifiers.cs | 9 | ||||
-rw-r--r-- | crypto/src/asn1/ua/UAObjectIdentifiers.cs | 107 | ||||
-rw-r--r-- | crypto/src/crypto/digests/Blake2bDigest.cs | 531 | ||||
-rw-r--r-- | crypto/src/crypto/digests/Blake2sDigest.cs | 552 | ||||
-rw-r--r-- | crypto/src/security/DigestUtilities.cs | 111 | ||||
-rw-r--r-- | crypto/test/UnitTests.csproj | 2 | ||||
-rw-r--r-- | crypto/test/src/crypto/test/Blake2bDigestTest.cs | 251 | ||||
-rw-r--r-- | crypto/test/src/crypto/test/Blake2sDigestTest.cs | 243 | ||||
-rw-r--r-- | crypto/test/src/crypto/test/RegressionTest.cs | 2 | ||||
-rw-r--r-- | crypto/test/src/test/DigestTest.cs | 41 |
14 files changed, 1854 insertions, 29 deletions
diff --git a/crypto/BouncyCastle.Android.csproj b/crypto/BouncyCastle.Android.csproj index 7a69c92cb..59674d676 100644 --- a/crypto/BouncyCastle.Android.csproj +++ b/crypto/BouncyCastle.Android.csproj @@ -388,6 +388,7 @@ <Compile Include="src\asn1\tsp\TSTInfo.cs" /> <Compile Include="src\asn1\tsp\TimeStampReq.cs" /> <Compile Include="src\asn1\tsp\TimeStampResp.cs" /> + <Compile Include="src\asn1\ua\UAObjectIdentifiers.cs" /> <Compile Include="src\asn1\util\Asn1Dump.cs" /> <Compile Include="src\asn1\util\Dump.cs" /> <Compile Include="src\asn1\util\FilterStream.cs" /> @@ -714,6 +715,8 @@ <Compile Include="src\crypto\agreement\srp\SRP6StandardGroups.cs" /> <Compile Include="src\crypto\agreement\srp\SRP6Utilities.cs" /> <Compile Include="src\crypto\agreement\srp\SRP6VerifierGenerator.cs" /> + <Compile Include="src\crypto\digests\Blake2bDigest.cs" /> + <Compile Include="src\crypto\digests\Blake2sDigest.cs" /> <Compile Include="src\crypto\digests\DSTU7564Digest.cs" /> <Compile Include="src\crypto\digests\GeneralDigest.cs" /> <Compile Include="src\crypto\digests\GOST3411Digest.cs" /> diff --git a/crypto/BouncyCastle.csproj b/crypto/BouncyCastle.csproj index a5f149620..004e35e78 100644 --- a/crypto/BouncyCastle.csproj +++ b/crypto/BouncyCastle.csproj @@ -382,6 +382,7 @@ <Compile Include="src\asn1\tsp\TSTInfo.cs" /> <Compile Include="src\asn1\tsp\TimeStampReq.cs" /> <Compile Include="src\asn1\tsp\TimeStampResp.cs" /> + <Compile Include="src\asn1\ua\UAObjectIdentifiers.cs" /> <Compile Include="src\asn1\util\Asn1Dump.cs" /> <Compile Include="src\asn1\util\Dump.cs" /> <Compile Include="src\asn1\util\FilterStream.cs" /> @@ -708,6 +709,8 @@ <Compile Include="src\crypto\agreement\srp\SRP6StandardGroups.cs" /> <Compile Include="src\crypto\agreement\srp\SRP6Utilities.cs" /> <Compile Include="src\crypto\agreement\srp\SRP6VerifierGenerator.cs" /> + <Compile Include="src\crypto\digests\Blake2bDigest.cs" /> + <Compile Include="src\crypto\digests\Blake2sDigest.cs" /> <Compile Include="src\crypto\digests\DSTU7564Digest.cs" /> <Compile Include="src\crypto\digests\GeneralDigest.cs" /> <Compile Include="src\crypto\digests\GOST3411Digest.cs" /> diff --git a/crypto/BouncyCastle.iOS.csproj b/crypto/BouncyCastle.iOS.csproj index 56dd59ea7..61c28f64d 100644 --- a/crypto/BouncyCastle.iOS.csproj +++ b/crypto/BouncyCastle.iOS.csproj @@ -383,6 +383,7 @@ <Compile Include="src\asn1\tsp\TSTInfo.cs" /> <Compile Include="src\asn1\tsp\TimeStampReq.cs" /> <Compile Include="src\asn1\tsp\TimeStampResp.cs" /> + <Compile Include="src\asn1\ua\UAObjectIdentifiers.cs" /> <Compile Include="src\asn1\util\Asn1Dump.cs" /> <Compile Include="src\asn1\util\Dump.cs" /> <Compile Include="src\asn1\util\FilterStream.cs" /> @@ -709,6 +710,8 @@ <Compile Include="src\crypto\agreement\srp\SRP6StandardGroups.cs" /> <Compile Include="src\crypto\agreement\srp\SRP6Utilities.cs" /> <Compile Include="src\crypto\agreement\srp\SRP6VerifierGenerator.cs" /> + <Compile Include="src\crypto\digests\Blake2bDigest.cs" /> + <Compile Include="src\crypto\digests\Blake2sDigest.cs" /> <Compile Include="src\crypto\digests\DSTU7564Digest.cs" /> <Compile Include="src\crypto\digests\GeneralDigest.cs" /> <Compile Include="src\crypto\digests\GOST3411Digest.cs" /> diff --git a/crypto/crypto.csproj b/crypto/crypto.csproj index e2ad3ea69..4115560c4 100644 --- a/crypto/crypto.csproj +++ b/crypto/crypto.csproj @@ -1799,6 +1799,11 @@ BuildAction = "Compile" /> <File + RelPath = "src\asn1\ua\UAObjectIdentifiers.cs" + SubType = "Code" + BuildAction = "Compile" + /> + <File RelPath = "src\asn1\util\ASN1Dump.cs" SubType = "Code" BuildAction = "Compile" @@ -3324,6 +3329,16 @@ BuildAction = "Compile" /> <File + RelPath = "src\crypto\digests\Blake2bDigest.cs" + SubType = "Code" + BuildAction = "Compile" + /> + <File + RelPath = "src\crypto\digests\Blake2sDigest.cs" + SubType = "Code" + BuildAction = "Compile" + /> + <File RelPath = "src\crypto\digests\DSTU7564Digest.cs" SubType = "Code" BuildAction = "Compile" @@ -11445,6 +11460,16 @@ BuildAction = "Compile" /> <File + RelPath = "test\src\crypto\test\Blake2bDigestTest.cs" + SubType = "Code" + BuildAction = "Compile" + /> + <File + RelPath = "test\src\crypto\test\Blake2sDigestTest.cs" + SubType = "Code" + BuildAction = "Compile" + /> + <File RelPath = "test\src\crypto\test\BlockCipherMonteCarloTest.cs" SubType = "Code" BuildAction = "Compile" diff --git a/crypto/src/asn1/misc/MiscObjectIdentifiers.cs b/crypto/src/asn1/misc/MiscObjectIdentifiers.cs index 8128b6952..d344393dd 100644 --- a/crypto/src/asn1/misc/MiscObjectIdentifiers.cs +++ b/crypto/src/asn1/misc/MiscObjectIdentifiers.cs @@ -75,5 +75,14 @@ namespace Org.BouncyCastle.Asn1.Misc public static readonly DerObjectIdentifier id_blake2b256 = blake2.Branch("1.8"); public static readonly DerObjectIdentifier id_blake2b384 = blake2.Branch("1.12"); public static readonly DerObjectIdentifier id_blake2b512 = blake2.Branch("1.16"); + + public static readonly DerObjectIdentifier id_blake2s128 = blake2.Branch("2.4"); + public static readonly DerObjectIdentifier id_blake2s160 = blake2.Branch("2.5"); + public static readonly DerObjectIdentifier id_blake2s224 = blake2.Branch("2.7"); + public static readonly DerObjectIdentifier id_blake2s256 = blake2.Branch("2.8"); + + // + // Scrypt + public static readonly DerObjectIdentifier id_scrypt = new DerObjectIdentifier("1.3.6.1.4.1.11591.4.11"); } } diff --git a/crypto/src/asn1/ua/UAObjectIdentifiers.cs b/crypto/src/asn1/ua/UAObjectIdentifiers.cs new file mode 100644 index 000000000..9beca3af5 --- /dev/null +++ b/crypto/src/asn1/ua/UAObjectIdentifiers.cs @@ -0,0 +1,107 @@ +namespace Org.BouncyCastle.Asn1.UA +{ + /** + * Ukrainian object identifiers + * <p> + * {iso(1) member-body(2) Ukraine(804) root(2) security(1) cryptography(1) pki(1)} + * <p> + * { ... pki-alg(1) pki-alg-sym(3) Dstu4145WithGost34311(1) PB(1)} + * <p> + * DSTU4145 in polynomial basis has 2 oids, one for little-endian representation and one for big-endian + */ + public abstract class UAObjectIdentifiers + { + /** Base OID: 1.2.804.2.1.1.1 */ + public static readonly DerObjectIdentifier UaOid = new DerObjectIdentifier("1.2.804.2.1.1.1"); + + /** DSTU4145 Little Endian presentation. OID: 1.2.804.2.1.1.1.1.3.1.1 */ + public static readonly DerObjectIdentifier dstu4145le = UaOid.Branch("1.3.1.1"); + /** DSTU4145 Big Endian presentation. OID: 1.2.804.2.1.1.1.1.3.1.1.1 */ + public static readonly DerObjectIdentifier dstu4145be = UaOid.Branch("1.3.1.1.1.1"); + + /** DSTU7564 256-bit digest presentation. */ + public static readonly DerObjectIdentifier dstu7564digest_256 = UaOid.Branch("1.2.2.1"); + /** DSTU7564 384-bit digest presentation. */ + public static readonly DerObjectIdentifier dstu7564digest_384 = UaOid.Branch("1.2.2.2"); + /** DSTU7564 512-bit digest presentation. */ + public static readonly DerObjectIdentifier dstu7564digest_512 = UaOid.Branch("1.2.2.3"); + + /** DSTU7564 256-bit mac presentation. */ + public static readonly DerObjectIdentifier dstu7564mac_256 = UaOid.Branch("1.2.2.4"); + /** DSTU7564 384-bit mac presentation. */ + public static readonly DerObjectIdentifier dstu7564mac_384 = UaOid.Branch("1.2.2.5"); + /** DSTU7564 512-bit mac presentation. */ + public static readonly DerObjectIdentifier dstu7564mac_512 = UaOid.Branch("1.2.2.6"); + + + /** DSTU7624 in ECB mode with 128 bit block/key presentation */ + public static readonly DerObjectIdentifier dstu7624ecb_128 = UaOid.Branch("1.1.3.1.1"); + /** DSTU7624 in ECB mode with 256 bit block/key presentation */ + public static readonly DerObjectIdentifier dstu7624ecb_256 = UaOid.Branch("1.1.3.1.2"); + /** DSTU7624 in ECB mode with 512 bit block/key presentation */ + public static readonly DerObjectIdentifier dstu7624ecb_512 = UaOid.Branch("1.1.3.1.3"); + + /** DSTU7624 in CTR mode with 128 bit block/key presentation */ + public static readonly DerObjectIdentifier dstu7624ctr_128 = UaOid.Branch("1.1.3.2.1"); + /** DSTU7624 in CTR mode with 256 bit block/key presentation */ + public static readonly DerObjectIdentifier dstu7624ctr_256 = UaOid.Branch("1.1.3.2.2"); + /** DSTU7624 in CTR mode with 512 bit block/key presentation */ + public static readonly DerObjectIdentifier dstu7624ctr_512 = UaOid.Branch("1.1.3.2.3"); + + /** DSTU7624 in CFB mode with 128 bit block/key presentation */ + public static readonly DerObjectIdentifier dstu7624cfb_128 = UaOid.Branch("1.1.3.3.1"); + /** DSTU7624 in CFB mode with 256 bit block/key presentation */ + public static readonly DerObjectIdentifier dstu7624cfb_256 = UaOid.Branch("1.1.3.3.2"); + /** DSTU7624 in CFB mode with 512 bit block/key presentation */ + public static readonly DerObjectIdentifier dstu7624cfb_512 = UaOid.Branch("1.1.3.3.3"); + + /** DSTU7624 in MAC mode with 128 bit block/key presentation */ + public static readonly DerObjectIdentifier dstu7624cmac_128 = UaOid.Branch("1.1.3.4.1"); + /** DSTU7624 in MAC mode with 256 bit block/key presentation */ + public static readonly DerObjectIdentifier dstu7624cmac_256 = UaOid.Branch("1.1.3.4.2"); + /** DSTU7624 in MAC mode with 512 bit block/key presentation */ + public static readonly DerObjectIdentifier dstu7624cmac_512 = UaOid.Branch("1.1.3.4.3"); + + /** DSTU7624 in CBC mode with 128 bit block/key presentation */ + public static readonly DerObjectIdentifier dstu7624cbc_128 = UaOid.Branch("1.1.3.5.1"); + /** DSTU7624 in CBC mode with 256 bit block/key presentation */ + public static readonly DerObjectIdentifier dstu7624cbc_256 = UaOid.Branch("1.1.3.5.2"); + /** DSTU7624 in CBC mode with 512 bit block/key presentation */ + public static readonly DerObjectIdentifier dstu7624cbc_512 = UaOid.Branch("1.1.3.5.3"); + + /** DSTU7624 in OFB mode with 128 bit block/key presentation */ + public static readonly DerObjectIdentifier dstu7624ofb_128 = UaOid.Branch("1.1.3.6.1"); + /** DSTU7624 in OFB mode with 256 bit block/key presentation */ + public static readonly DerObjectIdentifier dstu7624ofb_256 = UaOid.Branch("1.1.3.6.2"); + /** DSTU7624 in OFB mode with 512 bit block/key presentation */ + public static readonly DerObjectIdentifier dstu7624ofb_512 = UaOid.Branch("1.1.3.6.3"); + + /** DSTU7624 in GMAC (GCM witout encryption) mode with 128 bit block/key presentation */ + public static readonly DerObjectIdentifier dstu7624gmac_128 = UaOid.Branch("1.1.3.7.1"); + /** DSTU7624 in GMAC (GCM witout encryption) mode with 256 bit block/key presentation */ + public static readonly DerObjectIdentifier dstu7624gmac_256 = UaOid.Branch("1.1.3.7.2"); + /** DSTU7624 in GMAC (GCM witout encryption) mode with 512 bit block/key presentation */ + public static readonly DerObjectIdentifier dstu7624gmac_512 = UaOid.Branch("1.1.3.7.3"); + + /** DSTU7624 in CCM mode with 128 bit block/key presentation */ + public static readonly DerObjectIdentifier dstu7624ccm_128 = UaOid.Branch("1.1.3.8.1"); + /** DSTU7624 in CCM mode with 256 bit block/key presentation */ + public static readonly DerObjectIdentifier dstu7624ccm_256 = UaOid.Branch("1.1.3.8.2"); + /** DSTU7624 in CCM mode with 512 bit block/key presentation */ + public static readonly DerObjectIdentifier dstu7624ccm_512 = UaOid.Branch("1.1.3.8.3"); + + /** DSTU7624 in XTS mode with 128 bit block/key presentation */ + public static readonly DerObjectIdentifier dstu7624xts_128 = UaOid.Branch("1.1.3.9.1"); + /** DSTU7624 in XTS mode with 256 bit block/key presentation */ + public static readonly DerObjectIdentifier dstu7624xts_256 = UaOid.Branch("1.1.3.9.2"); + /** DSTU7624 in XTS mode with 512 bit block/key presentation */ + public static readonly DerObjectIdentifier dstu7624xts_512 = UaOid.Branch("1.1.3.9.3"); + + /** DSTU7624 in key wrap (KW) mode with 128 bit block/key presentation */ + public static readonly DerObjectIdentifier dstu7624kw_128 = UaOid.Branch("1.1.3.10.1"); + /** DSTU7624 in key wrap (KW) mode with 256 bit block/key presentation */ + public static readonly DerObjectIdentifier dstu7624kw_256 = UaOid.Branch("1.1.3.10.2"); + /** DSTU7624 in key wrap (KW) mode with 512 bit block/key presentation */ + public static readonly DerObjectIdentifier dstu7624kw_512 = UaOid.Branch("1.1.3.10.3"); + } +} diff --git a/crypto/src/crypto/digests/Blake2bDigest.cs b/crypto/src/crypto/digests/Blake2bDigest.cs new file mode 100644 index 000000000..b8e4f272e --- /dev/null +++ b/crypto/src/crypto/digests/Blake2bDigest.cs @@ -0,0 +1,531 @@ +using System; + +using Org.BouncyCastle.Crypto.Utilities; +using Org.BouncyCastle.Utilities; + +namespace Org.BouncyCastle.Crypto.Digests +{ + /* The BLAKE2 cryptographic hash function was designed by Jean- + Philippe Aumasson, Samuel Neves, Zooko Wilcox-O'Hearn, and Christian + Winnerlein. + + Reference Implementation and Description can be found at: https://blake2.net/ + Internet Draft: https://tools.ietf.org/html/draft-saarinen-blake2-02 + + This implementation does not support the Tree Hashing Mode. + + For unkeyed hashing, developers adapting BLAKE2 to ASN.1 - based + message formats SHOULD use the OID tree at x = 1.3.6.1.4.1.1722.12.2. + + Algorithm | Target | Collision | Hash | Hash ASN.1 | + Identifier | Arch | Security | nn | OID Suffix | + ---------------+--------+-----------+------+------------+ + id-blake2b160 | 64-bit | 2**80 | 20 | x.1.20 | + id-blake2b256 | 64-bit | 2**128 | 32 | x.1.32 | + id-blake2b384 | 64-bit | 2**192 | 48 | x.1.48 | + id-blake2b512 | 64-bit | 2**256 | 64 | x.1.64 | + ---------------+--------+-----------+------+------------+ + */ + + /** + * Implementation of the cryptographic hash function Blakbe2b. + * <p> + * Blake2b offers a built-in keying mechanism to be used directly + * for authentication ("Prefix-MAC") rather than a HMAC construction. + * <p> + * Blake2b offers a built-in support for a salt for randomized hashing + * and a personal string for defining a unique hash function for each application. + * <p> + * BLAKE2b is optimized for 64-bit platforms and produces digests of any size + * between 1 and 64 bytes. + */ + public class Blake2bDigest + : IDigest + { + // Blake2b Initialization Vector: + private static readonly ulong[] blake2b_IV = + // Produced from the square root of primes 2, 3, 5, 7, 11, 13, 17, 19. + // The same as SHA-512 IV. + { + 0x6a09e667f3bcc908UL, 0xbb67ae8584caa73bUL, 0x3c6ef372fe94f82bUL, + 0xa54ff53a5f1d36f1UL, 0x510e527fade682d1UL, 0x9b05688c2b3e6c1fUL, + 0x1f83d9abfb41bd6bUL, 0x5be0cd19137e2179UL + }; + + // Message word permutations: + private static readonly byte[,] blake2b_sigma = + { + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, + { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 }, + { 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 }, + { 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 }, + { 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 }, + { 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 }, + { 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 }, + { 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 }, + { 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 }, + { 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, + { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 } + }; + + private const int ROUNDS = 12; // to use for Catenas H' + private const int BLOCK_LENGTH_BYTES = 128;// bytes + + // General parameters: + private int digestLength = 64; // 1- 64 bytes + private int keyLength = 0; // 0 - 64 bytes for keyed hashing for MAC + private byte[] salt = null;// new byte[16]; + private byte[] personalization = null;// new byte[16]; + + // the key + private byte[] key = null; + + // Tree hashing parameters: + // Because this class does not implement the Tree Hashing Mode, + // these parameters can be treated as constants (see init() function) + /* + * private int fanout = 1; // 0-255 private int depth = 1; // 1 - 255 + * private int leafLength= 0; private long nodeOffset = 0L; private int + * nodeDepth = 0; private int innerHashLength = 0; + */ + + // whenever this buffer overflows, it will be processed + // in the Compress() function. + // For performance issues, long messages will not use this buffer. + private byte[] buffer = null;// new byte[BLOCK_LENGTH_BYTES]; + // Position of last inserted byte: + private int bufferPos = 0;// a value from 0 up to 128 + + private ulong[] internalState = new ulong[16]; // In the Blake2b paper it is + // called: v + private ulong[] chainValue = null; // state vector, in the Blake2b paper it + // is called: h + + private ulong t0 = 0UL; // holds last significant bits, counter (counts bytes) + private ulong t1 = 0UL; // counter: Length up to 2^128 are supported + private ulong f0 = 0UL; // finalization flag, for last block: ~0L + + // For Tree Hashing Mode, not used here: + // private long f1 = 0L; // finalization flag, for last node: ~0L + + public Blake2bDigest() + : this(512) + { + } + + public Blake2bDigest(Blake2bDigest digest) + { + this.bufferPos = digest.bufferPos; + this.buffer = Arrays.Clone(digest.buffer); + this.keyLength = digest.keyLength; + this.key = Arrays.Clone(digest.key); + this.digestLength = digest.digestLength; + this.chainValue = Arrays.Clone(digest.chainValue); + this.personalization = Arrays.Clone(digest.personalization); + this.salt = Arrays.Clone(digest.salt); + this.t0 = digest.t0; + this.t1 = digest.t1; + this.f0 = digest.f0; + } + + /** + * Basic sized constructor - size in bits. + * + * @param digestSize size of the digest in bits + */ + public Blake2bDigest(int digestSize) + { + if (digestSize != 160 && digestSize != 256 && digestSize != 384 && digestSize != 512) + throw new ArgumentException("BLAKE2b digest restricted to one of [160, 256, 384, 512]"); + + buffer = new byte[BLOCK_LENGTH_BYTES]; + keyLength = 0; + this.digestLength = digestSize / 8; + Init(); + } + + /** + * Blake2b for authentication ("Prefix-MAC mode"). + * After calling the doFinal() method, the key will + * remain to be used for further computations of + * this instance. + * The key can be overwritten using the clearKey() method. + * + * @param key A key up to 64 bytes or null + */ + public Blake2bDigest(byte[] key) + { + buffer = new byte[BLOCK_LENGTH_BYTES]; + if (key != null) + { + this.key = new byte[key.Length]; + Array.Copy(key, 0, this.key, 0, key.Length); + + if (key.Length > 64) + throw new ArgumentException("Keys > 64 are not supported"); + + keyLength = key.Length; + Array.Copy(key, 0, buffer, 0, key.Length); + bufferPos = BLOCK_LENGTH_BYTES; // zero padding + } + digestLength = 64; + Init(); + } + + /** + * Blake2b with key, required digest length (in bytes), salt and personalization. + * After calling the doFinal() method, the key, the salt and the personal string + * will remain and might be used for further computations with this instance. + * The key can be overwritten using the clearKey() method, the salt (pepper) + * can be overwritten using the clearSalt() method. + * + * @param key A key up to 64 bytes or null + * @param digestLength from 1 up to 64 bytes + * @param salt 16 bytes or null + * @param personalization 16 bytes or null + */ + public Blake2bDigest(byte[] key, int digestLength, byte[] salt, byte[] personalization) + { + if (digestLength < 1 || digestLength > 64) + throw new ArgumentException("Invalid digest length (required: 1 - 64)"); + + this.digestLength = digestLength; + this.buffer = new byte[BLOCK_LENGTH_BYTES]; + + if (salt != null) + { + if (salt.Length != 16) + throw new ArgumentException("salt length must be exactly 16 bytes"); + + this.salt = new byte[16]; + Array.Copy(salt, 0, this.salt, 0, salt.Length); + } + if (personalization != null) + { + if (personalization.Length != 16) + throw new ArgumentException("personalization length must be exactly 16 bytes"); + + this.personalization = new byte[16]; + Array.Copy(personalization, 0, this.personalization, 0, personalization.Length); + } + if (key != null) + { + if (key.Length > 64) + throw new ArgumentException("Keys > 64 are not supported"); + + this.key = new byte[key.Length]; + Array.Copy(key, 0, this.key, 0, key.Length); + + keyLength = key.Length; + Array.Copy(key, 0, buffer, 0, key.Length); + bufferPos = BLOCK_LENGTH_BYTES; // zero padding + } + Init(); + } + + // initialize chainValue + private void Init() + { + if (chainValue == null) + { + chainValue = new ulong[8]; + + chainValue[0] = blake2b_IV[0] ^ (ulong)(digestLength | (keyLength << 8) | 0x1010000); + + // 0x1010000 = ((fanout << 16) | (depth << 24) | (leafLength << + // 32)); + // with fanout = 1; depth = 0; leafLength = 0; + chainValue[1] = blake2b_IV[1];// ^ nodeOffset; with nodeOffset = 0; + chainValue[2] = blake2b_IV[2];// ^ ( nodeDepth | (innerHashLength << 8) ); + // with nodeDepth = 0; innerHashLength = 0; + + chainValue[3] = blake2b_IV[3]; + + chainValue[4] = blake2b_IV[4]; + chainValue[5] = blake2b_IV[5]; + if (salt != null) + { + chainValue[4] ^= Pack.LE_To_UInt64(salt, 0); + chainValue[5] ^= Pack.LE_To_UInt64(salt, 8); + } + + chainValue[6] = blake2b_IV[6]; + chainValue[7] = blake2b_IV[7]; + if (personalization != null) + { + chainValue[6] ^= Pack.LE_To_UInt64(personalization, 0); + chainValue[7] ^= Pack.LE_To_UInt64(personalization, 8); + } + } + } + + private void InitializeInternalState() + { + // initialize v: + Array.Copy(chainValue, 0, internalState, 0, chainValue.Length); + Array.Copy(blake2b_IV, 0, internalState, chainValue.Length, 4); + internalState[12] = t0 ^ blake2b_IV[4]; + internalState[13] = t1 ^ blake2b_IV[5]; + internalState[14] = f0 ^ blake2b_IV[6]; + internalState[15] = blake2b_IV[7];// ^ f1 with f1 = 0 + } + + /** + * update the message digest with a single byte. + * + * @param b the input byte to be entered. + */ + public virtual void Update(byte b) + { + int remainingLength = 0; // left bytes of buffer + + // process the buffer if full else add to buffer: + remainingLength = BLOCK_LENGTH_BYTES - bufferPos; + if (remainingLength == 0) + { // full buffer + t0 += BLOCK_LENGTH_BYTES; + if (t0 == 0) + { // if message > 2^64 + t1++; + } + Compress(buffer, 0); + Array.Clear(buffer, 0, buffer.Length);// clear buffer + buffer[0] = b; + bufferPos = 1; + } + else + { + buffer[bufferPos] = b; + bufferPos++; + return; + } + } + + /** + * update the message digest with a block of bytes. + * + * @param message the byte array containing the data. + * @param offset the offset into the byte array where the data starts. + * @param len the length of the data. + */ + public virtual void BlockUpdate(byte[] message, int offset, int len) + { + if (message == null || len == 0) + return; + + int remainingLength = 0; // left bytes of buffer + + if (bufferPos != 0) + { // commenced, incomplete buffer + + // complete the buffer: + remainingLength = BLOCK_LENGTH_BYTES - bufferPos; + if (remainingLength < len) + { // full buffer + at least 1 byte + Array.Copy(message, offset, buffer, bufferPos, + remainingLength); + t0 += BLOCK_LENGTH_BYTES; + if (t0 == 0) + { // if message > 2^64 + t1++; + } + Compress(buffer, 0); + bufferPos = 0; + Array.Clear(buffer, 0, buffer.Length);// clear buffer + } + else + { + Array.Copy(message, offset, buffer, bufferPos, len); + bufferPos += len; + return; + } + } + + // process blocks except last block (also if last block is full) + int messagePos; + int blockWiseLastPos = offset + len - BLOCK_LENGTH_BYTES; + for (messagePos = offset + remainingLength; messagePos < blockWiseLastPos; messagePos += BLOCK_LENGTH_BYTES) + { // block wise 128 bytes + // without buffer: + t0 += BLOCK_LENGTH_BYTES; + if (t0 == 0) + { + t1++; + } + Compress(message, messagePos); + } + + // fill the buffer with left bytes, this might be a full block + Array.Copy(message, messagePos, buffer, 0, offset + len + - messagePos); + bufferPos += offset + len - messagePos; + } + + /** + * close the digest, producing the final digest value. The doFinal + * call leaves the digest reset. + * Key, salt and personal string remain. + * + * @param out the array the digest is to be copied into. + * @param outOffset the offset into the out array the digest is to start at. + */ + public virtual int DoFinal(byte[] output, int outOffset) + { + f0 = 0xFFFFFFFFFFFFFFFFUL; + t0 += (ulong)bufferPos; + if (bufferPos > 0 && t0 == 0) + { + t1++; + } + Compress(buffer, 0); + Array.Clear(buffer, 0, buffer.Length);// Holds eventually the key if input is null + Array.Clear(internalState, 0, internalState.Length); + + for (int i = 0; i < chainValue.Length && (i * 8 < digestLength); i++) + { + byte[] bytes = Pack.UInt64_To_LE(chainValue[i]); + + if (i * 8 < digestLength - 8) + { + Array.Copy(bytes, 0, output, outOffset + i * 8, 8); + } + else + { + Array.Copy(bytes, 0, output, outOffset + i * 8, digestLength - (i * 8)); + } + } + + Array.Clear(chainValue, 0, chainValue.Length); + + Reset(); + + return digestLength; + } + + /** + * Reset the digest back to it's initial state. + * The key, the salt and the personal string will + * remain for further computations. + */ + public virtual void Reset() + { + bufferPos = 0; + f0 = 0L; + t0 = 0L; + t1 = 0L; + chainValue = null; + Array.Clear(buffer, 0, buffer.Length); + if (key != null) + { + Array.Copy(key, 0, buffer, 0, key.Length); + bufferPos = BLOCK_LENGTH_BYTES; // zero padding + } + Init(); + } + + private void Compress(byte[] message, int messagePos) + { + InitializeInternalState(); + + ulong[] m = new ulong[16]; + for (int j = 0; j < 16; j++) + { + m[j] = Pack.LE_To_UInt64(message, messagePos + j * 8); + } + + for (int round = 0; round < ROUNDS; round++) + { + // G apply to columns of internalState:m[blake2b_sigma[round][2 * blockPos]] /+1 + G(m[blake2b_sigma[round,0]], m[blake2b_sigma[round,1]], 0, 4, 8, 12); + G(m[blake2b_sigma[round,2]], m[blake2b_sigma[round,3]], 1, 5, 9, 13); + G(m[blake2b_sigma[round,4]], m[blake2b_sigma[round,5]], 2, 6, 10, 14); + G(m[blake2b_sigma[round,6]], m[blake2b_sigma[round,7]], 3, 7, 11, 15); + // G apply to diagonals of internalState: + G(m[blake2b_sigma[round,8]], m[blake2b_sigma[round,9]], 0, 5, 10, 15); + G(m[blake2b_sigma[round,10]], m[blake2b_sigma[round,11]], 1, 6, 11, 12); + G(m[blake2b_sigma[round,12]], m[blake2b_sigma[round,13]], 2, 7, 8, 13); + G(m[blake2b_sigma[round,14]], m[blake2b_sigma[round,15]], 3, 4, 9, 14); + } + + // update chain values: + for (int offset = 0; offset < chainValue.Length; offset++) + { + chainValue[offset] = chainValue[offset] ^ internalState[offset] ^ internalState[offset + 8]; + } + } + + private void G(ulong m1, ulong m2, int posA, int posB, int posC, int posD) + { + internalState[posA] = internalState[posA] + internalState[posB] + m1; + internalState[posD] = Rotr64(internalState[posD] ^ internalState[posA], 32); + internalState[posC] = internalState[posC] + internalState[posD]; + internalState[posB] = Rotr64(internalState[posB] ^ internalState[posC], 24); // replaces 25 of BLAKE + internalState[posA] = internalState[posA] + internalState[posB] + m2; + internalState[posD] = Rotr64(internalState[posD] ^ internalState[posA], 16); + internalState[posC] = internalState[posC] + internalState[posD]; + internalState[posB] = Rotr64(internalState[posB] ^ internalState[posC], 63); // replaces 11 of BLAKE + } + + private static ulong Rotr64(ulong x, int rot) + { + return x >> rot | x << -rot; + } + + /** + * return the algorithm name + * + * @return the algorithm name + */ + public virtual string AlgorithmName + { + get { return "BLAKE2b"; } + } + + /** + * return the size, in bytes, of the digest produced by this message digest. + * + * @return the size, in bytes, of the digest produced by this message digest. + */ + public virtual int GetDigestSize() + { + return digestLength; + } + + /** + * Return the size in bytes of the internal buffer the digest applies it's compression + * function to. + * + * @return byte length of the digests internal buffer. + */ + public virtual int GetByteLength() + { + return BLOCK_LENGTH_BYTES; + } + + /** + * Overwrite the key + * if it is no longer used (zeroization) + */ + public virtual void ClearKey() + { + if (key != null) + { + Array.Clear(key, 0, key.Length); + Array.Clear(buffer, 0, buffer.Length); + } + } + + /** + * Overwrite the salt (pepper) if it + * is secret and no longer used (zeroization) + */ + public virtual void ClearSalt() + { + if (salt != null) + { + Array.Clear(salt, 0, salt.Length); + } + } + } +} diff --git a/crypto/src/crypto/digests/Blake2sDigest.cs b/crypto/src/crypto/digests/Blake2sDigest.cs new file mode 100644 index 000000000..f31032874 --- /dev/null +++ b/crypto/src/crypto/digests/Blake2sDigest.cs @@ -0,0 +1,552 @@ +using System; + +using Org.BouncyCastle.Crypto.Utilities; +using Org.BouncyCastle.Utilities; + +namespace Org.BouncyCastle.Crypto.Digests +{ + /* + The BLAKE2 cryptographic hash function was designed by Jean- + Philippe Aumasson, Samuel Neves, Zooko Wilcox-O'Hearn, and Christian + Winnerlein. + + Reference Implementation and Description can be found at: https://blake2.net/ + RFC: https://tools.ietf.org/html/rfc7693 + + This implementation does not support the Tree Hashing Mode. + + For unkeyed hashing, developers adapting BLAKE2 to ASN.1 - based + message formats SHOULD use the OID tree at x = 1.3.6.1.4.1.1722.12.2. + + Algorithm | Target | Collision | Hash | Hash ASN.1 | + Identifier | Arch | Security | nn | OID Suffix | + ---------------+--------+-----------+------+------------+ + id-blake2s128 | 32-bit | 2**64 | 16 | x.2.4 | + id-blake2s160 | 32-bit | 2**80 | 20 | x.2.5 | + id-blake2s224 | 32-bit | 2**112 | 28 | x.2.7 | + id-blake2s256 | 32-bit | 2**128 | 32 | x.2.8 | + ---------------+--------+-----------+------+------------+ + */ + + /** + * Implementation of the cryptographic hash function BLAKE2s. + * <p/> + * BLAKE2s offers a built-in keying mechanism to be used directly + * for authentication ("Prefix-MAC") rather than a HMAC construction. + * <p/> + * BLAKE2s offers a built-in support for a salt for randomized hashing + * and a personal string for defining a unique hash function for each application. + * <p/> + * BLAKE2s is optimized for 32-bit platforms and produces digests of any size + * between 1 and 32 bytes. + */ + public class Blake2sDigest + : IDigest + { + /** + * BLAKE2s Initialization Vector + **/ + private static readonly uint[] blake2s_IV = + // Produced from the square root of primes 2, 3, 5, 7, 11, 13, 17, 19. + // The same as SHA-256 IV. + { + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, + 0xa54ff53a, 0x510e527f, 0x9b05688c, + 0x1f83d9ab, 0x5be0cd19 + }; + + /** + * Message word permutations + **/ + private static readonly byte[,] blake2s_sigma = + { + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, + { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 }, + { 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 }, + { 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 }, + { 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 }, + { 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 }, + { 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 }, + { 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 }, + { 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 }, + { 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0 } + }; + + private const int ROUNDS = 10; // to use for Catenas H' + private const int BLOCK_LENGTH_BYTES = 64;// bytes + + // General parameters: + private int digestLength = 32; // 1- 32 bytes + private int keyLength = 0; // 0 - 32 bytes for keyed hashing for MAC + private byte[] salt = null; + private byte[] personalization = null; + private byte[] key = null; + + // Tree hashing parameters: + // Because this class does not implement the Tree Hashing Mode, + // these parameters can be treated as constants (see Init() function) + /* + * private int fanout = 1; // 0-255 + * private int depth = 1; // 1 - 255 + * private int leafLength= 0; + * private long nodeOffset = 0L; + * private int nodeDepth = 0; + * private int innerHashLength = 0; + */ + + /** + * Whenever this buffer overflows, it will be processed in the Compress() + * function. For performance issues, long messages will not use this buffer. + */ + private byte[] buffer = null; + /** + * Position of last inserted byte + **/ + private int bufferPos = 0;// a value from 0 up to BLOCK_LENGTH_BYTES + + /** + * Internal state, in the BLAKE2 paper it is called v + **/ + private uint[] internalState = new uint[16]; + /** + * State vector, in the BLAKE2 paper it is called h + **/ + private uint[] chainValue = null; + + // counter (counts bytes): Length up to 2^64 are supported + /** + * holds least significant bits of counter + **/ + private uint t0 = 0; + /** + * holds most significant bits of counter + **/ + private uint t1 = 0; + /** + * finalization flag, for last block: ~0 + **/ + private uint f0 = 0; + + // For Tree Hashing Mode, not used here: + // private long f1 = 0L; // finalization flag, for last node: ~0L + + /** + * BLAKE2s-256 for hashing. + */ + public Blake2sDigest() + : this(256) + { + } + + public Blake2sDigest(Blake2sDigest digest) + { + this.bufferPos = digest.bufferPos; + this.buffer = Arrays.Clone(digest.buffer); + this.keyLength = digest.keyLength; + this.key = Arrays.Clone(digest.key); + this.digestLength = digest.digestLength; + this.chainValue = Arrays.Clone(digest.chainValue); + this.personalization = Arrays.Clone(digest.personalization); + } + + /** + * BLAKE2s for hashing. + * + * @param digestBits the desired digest length in bits. Must be one of + * [128, 160, 224, 256]. + */ + public Blake2sDigest(int digestBits) + { + if (digestBits != 128 && digestBits != 160 && digestBits != 224 && digestBits != 256) + throw new ArgumentException("BLAKE2s digest restricted to one of [128, 160, 224, 256]"); + + buffer = new byte[BLOCK_LENGTH_BYTES]; + keyLength = 0; + digestLength = digestBits / 8; + Init(); + } + + /** + * BLAKE2s for authentication ("Prefix-MAC mode"). + * <p/> + * After calling the doFinal() method, the key will remain to be used for + * further computations of this instance. The key can be overwritten using + * the clearKey() method. + * + * @param key a key up to 32 bytes or null + */ + public Blake2sDigest(byte[] key) + { + buffer = new byte[BLOCK_LENGTH_BYTES]; + if (key != null) + { + if (key.Length > 32) + throw new ArgumentException("Keys > 32 are not supported"); + + this.key = new byte[key.Length]; + Array.Copy(key, 0, this.key, 0, key.Length); + + keyLength = key.Length; + Array.Copy(key, 0, buffer, 0, key.Length); + bufferPos = BLOCK_LENGTH_BYTES; // zero padding + } + digestLength = 32; + Init(); + } + + /** + * BLAKE2s with key, required digest length, salt and personalization. + * <p/> + * After calling the doFinal() method, the key, the salt and the personal + * string will remain and might be used for further computations with this + * instance. The key can be overwritten using the clearKey() method, the + * salt (pepper) can be overwritten using the clearSalt() method. + * + * @param key a key up to 32 bytes or null + * @param digestBytes from 1 up to 32 bytes + * @param salt 8 bytes or null + * @param personalization 8 bytes or null + */ + public Blake2sDigest(byte[] key, int digestBytes, byte[] salt, + byte[] personalization) + { + if (digestBytes < 1 || digestBytes > 32) + throw new ArgumentException("Invalid digest length (required: 1 - 32)"); + + this.digestLength = digestBytes; + this.buffer = new byte[BLOCK_LENGTH_BYTES]; + + if (salt != null) + { + if (salt.Length != 8) + throw new ArgumentException("Salt length must be exactly 8 bytes"); + + this.salt = new byte[8]; + Array.Copy(salt, 0, this.salt, 0, salt.Length); + } + if (personalization != null) + { + if (personalization.Length != 8) + throw new ArgumentException("Personalization length must be exactly 8 bytes"); + + this.personalization = new byte[8]; + Array.Copy(personalization, 0, this.personalization, 0, personalization.Length); + } + if (key != null) + { + if (key.Length > 32) + throw new ArgumentException("Keys > 32 bytes are not supported"); + + this.key = new byte[key.Length]; + Array.Copy(key, 0, this.key, 0, key.Length); + + keyLength = key.Length; + Array.Copy(key, 0, buffer, 0, key.Length); + bufferPos = BLOCK_LENGTH_BYTES; // zero padding + } + Init(); + } + + // initialize chainValue + private void Init() + { + if (chainValue == null) + { + chainValue = new uint[8]; + + chainValue[0] = blake2s_IV[0] ^ (uint)(digestLength | (keyLength << 8) | 0x1010000); + // 0x1010000 = ((fanout << 16) | (depth << 24)); + // with fanout = 1; depth = 0; + chainValue[1] = blake2s_IV[1];// ^ leafLength; with leafLength = 0; + chainValue[2] = blake2s_IV[2];// ^ nodeOffset; with nodeOffset = 0; + chainValue[3] = blake2s_IV[3];// ^ ( (nodeOffset << 32) | (nodeDepth << 16) | (innerHashLength << 24) ); + // with nodeDepth = 0; innerHashLength = 0; + + chainValue[4] = blake2s_IV[4]; + chainValue[5] = blake2s_IV[5]; + if (salt != null) + { + chainValue[4] ^= Pack.LE_To_UInt32(salt, 0); + chainValue[5] ^= Pack.LE_To_UInt32(salt, 4); + } + + chainValue[6] = blake2s_IV[6]; + chainValue[7] = blake2s_IV[7]; + if (personalization != null) + { + chainValue[6] ^= Pack.LE_To_UInt32(personalization, 0); + chainValue[7] ^= Pack.LE_To_UInt32(personalization, 4); + } + } + } + + private void InitializeInternalState() + { + // initialize v: + Array.Copy(chainValue, 0, internalState, 0, chainValue.Length); + Array.Copy(blake2s_IV, 0, internalState, chainValue.Length, 4); + internalState[12] = t0 ^ blake2s_IV[4]; + internalState[13] = t1 ^ blake2s_IV[5]; + internalState[14] = f0 ^ blake2s_IV[6]; + internalState[15] = blake2s_IV[7];// ^ f1 with f1 = 0 + } + + /** + * Update the message digest with a single byte. + * + * @param b the input byte to be entered. + */ + public virtual void Update(byte b) + { + int remainingLength; // left bytes of buffer + + // process the buffer if full else add to buffer: + remainingLength = BLOCK_LENGTH_BYTES - bufferPos; + if (remainingLength == 0) + { // full buffer + t0 += BLOCK_LENGTH_BYTES; + if (t0 == 0) + { // if message > 2^32 + t1++; + } + Compress(buffer, 0); + Array.Clear(buffer, 0, buffer.Length);// clear buffer + buffer[0] = b; + bufferPos = 1; + } + else + { + buffer[bufferPos] = b; + bufferPos++; + } + } + + /** + * Update the message digest with a block of bytes. + * + * @param message the byte array containing the data. + * @param offset the offset into the byte array where the data starts. + * @param len the length of the data. + */ + public virtual void BlockUpdate(byte[] message, int offset, int len) + { + if (message == null || len == 0) + return; + + int remainingLength = 0; // left bytes of buffer + + if (bufferPos != 0) + { // commenced, incomplete buffer + + // complete the buffer: + remainingLength = BLOCK_LENGTH_BYTES - bufferPos; + if (remainingLength < len) + { // full buffer + at least 1 byte + Array.Copy(message, offset, buffer, bufferPos, remainingLength); + t0 += BLOCK_LENGTH_BYTES; + if (t0 == 0) + { // if message > 2^32 + t1++; + } + Compress(buffer, 0); + bufferPos = 0; + Array.Clear(buffer, 0, buffer.Length);// clear buffer + } + else + { + Array.Copy(message, offset, buffer, bufferPos, len); + bufferPos += len; + return; + } + } + + // process blocks except last block (also if last block is full) + int messagePos; + int blockWiseLastPos = offset + len - BLOCK_LENGTH_BYTES; + for (messagePos = offset + remainingLength; + messagePos < blockWiseLastPos; + messagePos += BLOCK_LENGTH_BYTES) + { // block wise 64 bytes + // without buffer: + t0 += BLOCK_LENGTH_BYTES; + if (t0 == 0) + { + t1++; + } + Compress(message, messagePos); + } + + // fill the buffer with left bytes, this might be a full block + Array.Copy(message, messagePos, buffer, 0, offset + len + - messagePos); + bufferPos += offset + len - messagePos; + } + + /** + * Close the digest, producing the final digest value. The doFinal() call + * leaves the digest reset. Key, salt and personal string remain. + * + * @param out the array the digest is to be copied into. + * @param outOffset the offset into the out array the digest is to start at. + */ + public virtual int DoFinal(byte[] output, int outOffset) + { + f0 = 0xFFFFFFFFU; + t0 += (uint)bufferPos; + // bufferPos may be < 64, so (t0 == 0) does not work + // for 2^32 < message length > 2^32 - 63 + if ((t0 < 0) && (bufferPos > -t0)) + { + t1++; + } + Compress(buffer, 0); + Array.Clear(buffer, 0, buffer.Length);// Holds eventually the key if input is null + Array.Clear(internalState, 0, internalState.Length); + + for (int i = 0; i < chainValue.Length && (i * 4 < digestLength); i++) + { + byte[] bytes = Pack.UInt32_To_LE(chainValue[i]); + + if (i * 4 < digestLength - 4) + { + Array.Copy(bytes, 0, output, outOffset + i * 4, 4); + } + else + { + Array.Copy(bytes, 0, output, outOffset + i * 4, digestLength - (i * 4)); + } + } + + Array.Clear(chainValue, 0, chainValue.Length); + + Reset(); + + return digestLength; + } + + /** + * Reset the digest back to its initial state. The key, the salt and the + * personal string will remain for further computations. + */ + public virtual void Reset() + { + bufferPos = 0; + f0 = 0; + t0 = 0; + t1 = 0; + chainValue = null; + Array.Clear(buffer, 0, buffer.Length); + if (key != null) + { + Array.Copy(key, 0, buffer, 0, key.Length); + bufferPos = BLOCK_LENGTH_BYTES; // zero padding + } + Init(); + } + + private void Compress(byte[] message, int messagePos) + { + InitializeInternalState(); + + uint[] m = new uint[16]; + for (int j = 0; j < 16; j++) + { + m[j] = Pack.LE_To_UInt32(message, messagePos + j * 4); + } + + for (int round = 0; round < ROUNDS; round++) + { + + // G apply to columns of internalState:m[blake2s_sigma[round][2 * + // blockPos]] /+1 + G(m[blake2s_sigma[round,0]], m[blake2s_sigma[round,1]], 0, 4, 8, 12); + G(m[blake2s_sigma[round,2]], m[blake2s_sigma[round,3]], 1, 5, 9, 13); + G(m[blake2s_sigma[round,4]], m[blake2s_sigma[round,5]], 2, 6, 10, 14); + G(m[blake2s_sigma[round,6]], m[blake2s_sigma[round,7]], 3, 7, 11, 15); + // G apply to diagonals of internalState: + G(m[blake2s_sigma[round,8]], m[blake2s_sigma[round,9]], 0, 5, 10, 15); + G(m[blake2s_sigma[round,10]], m[blake2s_sigma[round,11]], 1, 6, 11, 12); + G(m[blake2s_sigma[round,12]], m[blake2s_sigma[round,13]], 2, 7, 8, 13); + G(m[blake2s_sigma[round,14]], m[blake2s_sigma[round,15]], 3, 4, 9, 14); + } + + // update chain values: + for (int offset = 0; offset < chainValue.Length; offset++) + { + chainValue[offset] = chainValue[offset] ^ internalState[offset] ^ internalState[offset + 8]; + } + } + + private void G(uint m1, uint m2, int posA, int posB, int posC, int posD) + { + internalState[posA] = internalState[posA] + internalState[posB] + m1; + internalState[posD] = rotr32(internalState[posD] ^ internalState[posA], 16); + internalState[posC] = internalState[posC] + internalState[posD]; + internalState[posB] = rotr32(internalState[posB] ^ internalState[posC], 12); + internalState[posA] = internalState[posA] + internalState[posB] + m2; + internalState[posD] = rotr32(internalState[posD] ^ internalState[posA], 8); + internalState[posC] = internalState[posC] + internalState[posD]; + internalState[posB] = rotr32(internalState[posB] ^ internalState[posC], 7); + } + + private uint rotr32(uint x, int rot) + { + return x >> rot | x << -rot; + } + + /** + * Return the algorithm name. + * + * @return the algorithm name + */ + public virtual string AlgorithmName + { + get { return "BLAKE2s"; } + } + + /** + * Return the size in bytes of the digest produced by this message digest. + * + * @return the size in bytes of the digest produced by this message digest. + */ + public virtual int GetDigestSize() + { + return digestLength; + } + + /** + * Return the size in bytes of the internal buffer the digest applies its + * compression function to. + * + * @return byte length of the digest's internal buffer. + */ + public virtual int GetByteLength() + { + return BLOCK_LENGTH_BYTES; + } + + /** + * Overwrite the key if it is no longer used (zeroization). + */ + public virtual void ClearKey() + { + if (key != null) + { + Array.Clear(key, 0, key.Length); + Array.Clear(buffer, 0, buffer.Length); + } + } + + /** + * Overwrite the salt (pepper) if it is secret and no longer used + * (zeroization). + */ + public virtual void ClearSalt() + { + if (salt != null) + { + Array.Clear(salt, 0, salt.Length); + } + } + } +} diff --git a/crypto/src/security/DigestUtilities.cs b/crypto/src/security/DigestUtilities.cs index 7ddf6c8e4..c6adbdd95 100644 --- a/crypto/src/security/DigestUtilities.cs +++ b/crypto/src/security/DigestUtilities.cs @@ -3,10 +3,14 @@ using System.Collections; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.CryptoPro; +using Org.BouncyCastle.Asn1.GM; +using Org.BouncyCastle.Asn1.Misc; using Org.BouncyCastle.Asn1.Nist; using Org.BouncyCastle.Asn1.Pkcs; using Org.BouncyCastle.Asn1.Oiw; +using Org.BouncyCastle.Asn1.Rosstandart; using Org.BouncyCastle.Asn1.TeleTrust; +using Org.BouncyCastle.Asn1.UA; using Org.BouncyCastle.Security; using Org.BouncyCastle.Crypto.Digests; using Org.BouncyCastle.Crypto; @@ -20,7 +24,11 @@ namespace Org.BouncyCastle.Security public sealed class DigestUtilities { private enum DigestAlgorithm { + BLAKE2B_160, BLAKE2B_256, BLAKE2B_384, BLAKE2B_512, + BLAKE2S_128, BLAKE2S_160, BLAKE2S_224, BLAKE2S_256, + DSTU7564_256, DSTU7564_384, DSTU7564_512, GOST3411, + GOST3411_2012_256, GOST3411_2012_512, KECCAK_224, KECCAK_256, KECCAK_288, KECCAK_384, KECCAK_512, MD2, MD4, MD5, RIPEMD128, RIPEMD160, RIPEMD256, RIPEMD320, @@ -28,6 +36,7 @@ namespace Org.BouncyCastle.Security SHA_512_224, SHA_512_256, SHA3_224, SHA3_256, SHA3_384, SHA3_512, SHAKE128, SHAKE256, + SM3, TIGER, WHIRLPOOL, }; @@ -81,6 +90,24 @@ namespace Org.BouncyCastle.Security algorithms[NistObjectIdentifiers.IdShake128.Id] = "SHAKE128"; algorithms[NistObjectIdentifiers.IdShake256.Id] = "SHAKE256"; + algorithms[GMObjectIdentifiers.sm3.Id] = "SM3"; + + algorithms[MiscObjectIdentifiers.id_blake2b160.Id] = "BLAKE2B-160"; + algorithms[MiscObjectIdentifiers.id_blake2b256.Id] = "BLAKE2B-256"; + algorithms[MiscObjectIdentifiers.id_blake2b384.Id] = "BLAKE2B-384"; + algorithms[MiscObjectIdentifiers.id_blake2b512.Id] = "BLAKE2B-512"; + algorithms[MiscObjectIdentifiers.id_blake2s128.Id] = "BLAKE2S-128"; + algorithms[MiscObjectIdentifiers.id_blake2s160.Id] = "BLAKE2S-160"; + algorithms[MiscObjectIdentifiers.id_blake2s224.Id] = "BLAKE2S-224"; + algorithms[MiscObjectIdentifiers.id_blake2s256.Id] = "BLAKE2S-256"; + + algorithms[RosstandartObjectIdentifiers.id_tc26_gost_3411_12_256.Id] = "GOST3411-2012-256"; + algorithms[RosstandartObjectIdentifiers.id_tc26_gost_3411_12_512.Id] = "GOST3411-2012-512"; + + algorithms[UAObjectIdentifiers.dstu7564digest_256.Id] = "DSTU7564-256"; + algorithms[UAObjectIdentifiers.dstu7564digest_384.Id] = "DSTU7564-384"; + algorithms[UAObjectIdentifiers.dstu7564digest_512.Id] = "DSTU7564-512"; + oids["MD2"] = PkcsObjectIdentifiers.MD2; oids["MD4"] = PkcsObjectIdentifiers.MD4; oids["MD5"] = PkcsObjectIdentifiers.MD5; @@ -101,6 +128,20 @@ namespace Org.BouncyCastle.Security oids["RIPEMD160"] = TeleTrusTObjectIdentifiers.RipeMD160; oids["RIPEMD256"] = TeleTrusTObjectIdentifiers.RipeMD256; oids["GOST3411"] = CryptoProObjectIdentifiers.GostR3411; + oids["SM3"] = GMObjectIdentifiers.sm3; + oids["BLAKE2B-160"] = MiscObjectIdentifiers.id_blake2b160; + oids["BLAKE2B-256"] = MiscObjectIdentifiers.id_blake2b256; + oids["BLAKE2B-384"] = MiscObjectIdentifiers.id_blake2b384; + oids["BLAKE2B-512"] = MiscObjectIdentifiers.id_blake2b512; + oids["BLAKE2S-128"] = MiscObjectIdentifiers.id_blake2s128; + oids["BLAKE2S-160"] = MiscObjectIdentifiers.id_blake2s160; + oids["BLAKE2S-224"] = MiscObjectIdentifiers.id_blake2s224; + oids["BLAKE2S-256"] = MiscObjectIdentifiers.id_blake2s256; + oids["GOST3411-2012-256"] = RosstandartObjectIdentifiers.id_tc26_gost_3411_12_256; + oids["GOST3411-2012-512"] = RosstandartObjectIdentifiers.id_tc26_gost_3411_12_512; + oids["DSTU7564-256"] = UAObjectIdentifiers.dstu7564digest_256; + oids["DSTU7564-384"] = UAObjectIdentifiers.dstu7564digest_384; + oids["DSTU7564-512"] = UAObjectIdentifiers.dstu7564digest_512; } /// <summary> @@ -153,34 +194,48 @@ namespace Org.BouncyCastle.Security switch (digestAlgorithm) { - case DigestAlgorithm.GOST3411: return new Gost3411Digest(); - case DigestAlgorithm.KECCAK_224: return new KeccakDigest(224); - case DigestAlgorithm.KECCAK_256: return new KeccakDigest(256); - case DigestAlgorithm.KECCAK_288: return new KeccakDigest(288); - case DigestAlgorithm.KECCAK_384: return new KeccakDigest(384); - case DigestAlgorithm.KECCAK_512: return new KeccakDigest(512); - case DigestAlgorithm.MD2: return new MD2Digest(); - case DigestAlgorithm.MD4: return new MD4Digest(); - case DigestAlgorithm.MD5: return new MD5Digest(); - case DigestAlgorithm.RIPEMD128: return new RipeMD128Digest(); - case DigestAlgorithm.RIPEMD160: return new RipeMD160Digest(); - case DigestAlgorithm.RIPEMD256: return new RipeMD256Digest(); - case DigestAlgorithm.RIPEMD320: return new RipeMD320Digest(); - case DigestAlgorithm.SHA_1: return new Sha1Digest(); - case DigestAlgorithm.SHA_224: return new Sha224Digest(); - case DigestAlgorithm.SHA_256: return new Sha256Digest(); - case DigestAlgorithm.SHA_384: return new Sha384Digest(); - case DigestAlgorithm.SHA_512: return new Sha512Digest(); - case DigestAlgorithm.SHA_512_224: return new Sha512tDigest(224); - case DigestAlgorithm.SHA_512_256: return new Sha512tDigest(256); - case DigestAlgorithm.SHA3_224: return new Sha3Digest(224); - case DigestAlgorithm.SHA3_256: return new Sha3Digest(256); - case DigestAlgorithm.SHA3_384: return new Sha3Digest(384); - case DigestAlgorithm.SHA3_512: return new Sha3Digest(512); - case DigestAlgorithm.SHAKE128: return new ShakeDigest(128); - case DigestAlgorithm.SHAKE256: return new ShakeDigest(256); - case DigestAlgorithm.TIGER: return new TigerDigest(); - case DigestAlgorithm.WHIRLPOOL: return new WhirlpoolDigest(); + case DigestAlgorithm.BLAKE2B_160: return new Blake2bDigest(160); + case DigestAlgorithm.BLAKE2B_256: return new Blake2bDigest(256); + case DigestAlgorithm.BLAKE2B_384: return new Blake2bDigest(384); + case DigestAlgorithm.BLAKE2B_512: return new Blake2bDigest(512); + case DigestAlgorithm.BLAKE2S_128: return new Blake2sDigest(128); + case DigestAlgorithm.BLAKE2S_160: return new Blake2sDigest(160); + case DigestAlgorithm.BLAKE2S_224: return new Blake2sDigest(224); + case DigestAlgorithm.BLAKE2S_256: return new Blake2sDigest(256); + case DigestAlgorithm.DSTU7564_256: return new Dstu7564Digest(256); + case DigestAlgorithm.DSTU7564_384: return new Dstu7564Digest(384); + case DigestAlgorithm.DSTU7564_512: return new Dstu7564Digest(512); + case DigestAlgorithm.GOST3411: return new Gost3411Digest(); + case DigestAlgorithm.GOST3411_2012_256: return new GOST3411_2012_256Digest(); + case DigestAlgorithm.GOST3411_2012_512: return new GOST3411_2012_512Digest(); + case DigestAlgorithm.KECCAK_224: return new KeccakDigest(224); + case DigestAlgorithm.KECCAK_256: return new KeccakDigest(256); + case DigestAlgorithm.KECCAK_288: return new KeccakDigest(288); + case DigestAlgorithm.KECCAK_384: return new KeccakDigest(384); + case DigestAlgorithm.KECCAK_512: return new KeccakDigest(512); + case DigestAlgorithm.MD2: return new MD2Digest(); + case DigestAlgorithm.MD4: return new MD4Digest(); + case DigestAlgorithm.MD5: return new MD5Digest(); + case DigestAlgorithm.RIPEMD128: return new RipeMD128Digest(); + case DigestAlgorithm.RIPEMD160: return new RipeMD160Digest(); + case DigestAlgorithm.RIPEMD256: return new RipeMD256Digest(); + case DigestAlgorithm.RIPEMD320: return new RipeMD320Digest(); + case DigestAlgorithm.SHA_1: return new Sha1Digest(); + case DigestAlgorithm.SHA_224: return new Sha224Digest(); + case DigestAlgorithm.SHA_256: return new Sha256Digest(); + case DigestAlgorithm.SHA_384: return new Sha384Digest(); + case DigestAlgorithm.SHA_512: return new Sha512Digest(); + case DigestAlgorithm.SHA_512_224: return new Sha512tDigest(224); + case DigestAlgorithm.SHA_512_256: return new Sha512tDigest(256); + case DigestAlgorithm.SHA3_224: return new Sha3Digest(224); + case DigestAlgorithm.SHA3_256: return new Sha3Digest(256); + case DigestAlgorithm.SHA3_384: return new Sha3Digest(384); + case DigestAlgorithm.SHA3_512: return new Sha3Digest(512); + case DigestAlgorithm.SHAKE128: return new ShakeDigest(128); + case DigestAlgorithm.SHAKE256: return new ShakeDigest(256); + case DigestAlgorithm.SM3: return new SM3Digest(); + case DigestAlgorithm.TIGER: return new TigerDigest(); + case DigestAlgorithm.WHIRLPOOL: return new WhirlpoolDigest(); } } catch (ArgumentException) diff --git a/crypto/test/UnitTests.csproj b/crypto/test/UnitTests.csproj index 67d3e1b91..be8b7d3c5 100644 --- a/crypto/test/UnitTests.csproj +++ b/crypto/test/UnitTests.csproj @@ -156,6 +156,8 @@ <Compile Include="src\crypto\test\AESWrapTest.cs" /> <Compile Include="src\crypto\test\AllTests.cs" /> <Compile Include="src\crypto\test\BCryptTest.cs" /> + <Compile Include="src\crypto\test\Blake2bDigestTest.cs" /> + <Compile Include="src\crypto\test\Blake2sDigestTest.cs" /> <Compile Include="src\crypto\test\BlockCipherMonteCarloTest.cs" /> <Compile Include="src\crypto\test\BlockCipherVectorTest.cs" /> <Compile Include="src\crypto\test\BlowfishTest.cs" /> diff --git a/crypto/test/src/crypto/test/Blake2bDigestTest.cs b/crypto/test/src/crypto/test/Blake2bDigestTest.cs new file mode 100644 index 000000000..0d0853977 --- /dev/null +++ b/crypto/test/src/crypto/test/Blake2bDigestTest.cs @@ -0,0 +1,251 @@ +using System; +using System.Text; + +using NUnit.Framework; + +using Org.BouncyCastle.Crypto.Digests; +using Org.BouncyCastle.Utilities; +using Org.BouncyCastle.Utilities.Encoders; +using Org.BouncyCastle.Utilities.Test; + +namespace Org.BouncyCastle.Crypto.Tests +{ + [TestFixture] + public class Blake2bDigestTest + : SimpleTest + { + private static readonly string[][] keyedTestVectors = + { // input/message, key, hash + + // Vectors from BLAKE2 web site: https://blake2.net/blake2b-test.txt + new string[]{ + "", + "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f", + "10ebb67700b1868efb4417987acf4690ae9d972fb7a590c2f02871799aaa4786b5e996e8f0f4eb981fc214b005f42d2ff4233499391653df7aefcbc13fc51568" }, + + new string[]{ + "00", + "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f", + "961f6dd1e4dd30f63901690c512e78e4b45e4742ed197c3c5e45c549fd25f2e4187b0bc9fe30492b16b0d0bc4ef9b0f34c7003fac09a5ef1532e69430234cebd" }, + + new string[]{ + "0001", + "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f", + "da2cfbe2d8409a0f38026113884f84b50156371ae304c4430173d08a99d9fb1b983164a3770706d537f49e0c916d9f32b95cc37a95b99d857436f0232c88a965" }, + + new string[]{ + "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d", + "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f", + "f1aa2b044f8f0c638a3f362e677b5d891d6fd2ab0765f6ee1e4987de057ead357883d9b405b9d609eea1b869d97fb16d9b51017c553f3b93c0a1e0f1296fedcd" }, + + new string[]{ + "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3", + "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f", + "c230f0802679cb33822ef8b3b21bf7a9a28942092901d7dac3760300831026cf354c9232df3e084d9903130c601f63c1f4a4a4b8106e468cd443bbe5a734f45f" }, + + new string[]{ + "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfe", + "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f", + "142709d62e28fcccd0af97fad0f8465b971e82201dc51070faa0372aa43e92484be1c1e73ba10906d5d1853db6a4106e0a7bf9800d373d6dee2d46d62ef2a461" } + }; + + private static readonly string[][] unkeyedTestVectors = + { // from: http://fossies.org/linux/john/src/rawBLAKE2_512_fmt_plug.c + // hash, input/message + // digests without leading $BLAKE2$ + new string[]{ + "4245af08b46fbb290222ab8a68613621d92ce78577152d712467742417ebc1153668f1c9e1ec1e152a32a9c242dc686d175e087906377f0c483c5be2cb68953e", + "blake2" }, + new string[]{ + "021ced8799296ceca557832ab941a50b4a11f83478cf141f51f933f653ab9fbcc05a037cddbed06e309bf334942c4e58cdf1a46e237911ccd7fcf9787cbc7fd0", + "hello world" }, + new string[]{ + "1f7d9b7c9a90f7bfc66e52b69f3b6c3befbd6aee11aac860e99347a495526f30c9e51f6b0db01c24825092a09dd1a15740f0ade8def87e60c15da487571bcef7", + "verystrongandlongpassword" }, + new string[]{ + "a8add4bdddfd93e4877d2746e62817b116364a1fa7bc148d95090bc7333b3673f82401cf7aa2e4cb1ecd90296e3f14cb5413f8ed77be73045b13914cdcd6a918", + "The quick brown fox jumps over the lazy dog" }, + new string[]{ + "786a02f742015903c6c6fd852552d272912f4740e15847618a86e217f71f5419d25e1031afee585313896444934eb04b903a685b1448b755d56f701afe9be2ce", + "" }, + new string[]{ + "ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d17d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923", + "abc" }, + }; + + public override string Name + { + get { return "BLAKE2b"; } + } + + private void offsetTest( + IDigest digest, + byte[] input, + byte[] expected) + { + byte[] resBuf = new byte[expected.Length + 11]; + + digest.BlockUpdate(input, 0, input.Length); + + digest.DoFinal(resBuf, 11); + + if (!AreEqual(Arrays.CopyOfRange(resBuf, 11, resBuf.Length), expected)) + { + Fail("Offset failed got " + Hex.ToHexString(resBuf)); + } + } + + public override void PerformTest() + { + // test keyed test vectors: + + Blake2bDigest blake2bkeyed = new Blake2bDigest(Hex.Decode(keyedTestVectors[0][1])); + for (int tv = 0; tv < keyedTestVectors.Length; tv++) + { + + byte[] input = Hex.Decode(keyedTestVectors[tv][0]); + blake2bkeyed.Reset(); + + blake2bkeyed.BlockUpdate(input, 0, input.Length); + byte[] keyedHash = new byte[64]; + blake2bkeyed.DoFinal(keyedHash, 0); + + if (!Arrays.AreEqual(Hex.Decode(keyedTestVectors[tv][2]), keyedHash)) + { + Fail("BLAKE2b mismatch on test vector ", + keyedTestVectors[tv][2], + Hex.ToHexString(keyedHash)); + } + + offsetTest(blake2bkeyed, input, keyedHash); + } + + Blake2bDigest blake2bunkeyed = new Blake2bDigest(); + // test unkeyed test vectors: + for (int i = 0; i < unkeyedTestVectors.Length; i++) + { + // blake2bunkeyed.update( + // unkeyedTestVectors[i][1].getBytes("UTF-8")); + // test update(byte b) + byte[] unkeyedInput = Encoding.UTF8.GetBytes(unkeyedTestVectors[i][1]); + for (int j = 0; j < unkeyedInput.Length; j++) + { + blake2bunkeyed.Update(unkeyedInput[j]); + } + + byte[] unkeyedHash = new byte[64]; + blake2bunkeyed.DoFinal(unkeyedHash, 0); + blake2bunkeyed.Reset(); + + if (!Arrays.AreEqual(Hex.Decode(unkeyedTestVectors[i][0]), + unkeyedHash)) + { + Fail("BLAKE2b mismatch on test vector ", + unkeyedTestVectors[i][0], + Hex.ToHexString(unkeyedHash)); + } + } + + cloneTest(); + resetTest(); + } + + private void cloneTest() + { + Blake2bDigest blake2bCloneSource = new Blake2bDigest(Hex.Decode(keyedTestVectors[3][1]), 16, Hex.Decode("000102030405060708090a0b0c0d0e0f"), Hex.Decode("101112131415161718191a1b1c1d1e1f")); + byte[] expected = Hex.Decode("b6d48ed5771b17414c4e08bd8d8a3bc4"); + + checkClone(blake2bCloneSource, expected); + + // just digest size + blake2bCloneSource = new Blake2bDigest(160); + expected = Hex.Decode("64202454e538279b21cea0f5a7688be656f8f484"); + checkClone(blake2bCloneSource, expected); + + // null salt and personalisation + blake2bCloneSource = new Blake2bDigest(Hex.Decode(keyedTestVectors[3][1]), 16, null, null); + expected = Hex.Decode("2b4a081fae2d7b488f5eed7e83e42a20"); + checkClone(blake2bCloneSource, expected); + + // null personalisation + blake2bCloneSource = new Blake2bDigest(Hex.Decode(keyedTestVectors[3][1]), 16, Hex.Decode("000102030405060708090a0b0c0d0e0f"), null); + expected = Hex.Decode("00c3a2a02fcb9f389857626e19d706f6"); + checkClone(blake2bCloneSource, expected); + + // null salt + blake2bCloneSource = new Blake2bDigest(Hex.Decode(keyedTestVectors[3][1]), 16, null, Hex.Decode("101112131415161718191a1b1c1d1e1f")); + expected = Hex.Decode("f445ec9c062a3c724f8fdef824417abb"); + checkClone(blake2bCloneSource, expected); + } + + private void checkClone(Blake2bDigest blake2bCloneSource, byte[] expected) + { + byte[] message = Hex.Decode(keyedTestVectors[3][0]); + + blake2bCloneSource.BlockUpdate(message, 0, message.Length); + + byte[] hash = new byte[blake2bCloneSource.GetDigestSize()]; + + Blake2bDigest digClone = new Blake2bDigest(blake2bCloneSource); + + blake2bCloneSource.DoFinal(hash, 0); + if (!AreEqual(expected, hash)) + { + Fail("clone source not correct"); + } + + digClone.DoFinal(hash, 0); + if (!AreEqual(expected, hash)) + { + Fail("clone not correct"); + } + } + + private void resetTest() + { + // Generate a non-zero key + byte[] key = new byte[32]; + for (byte i = 0; i < key.Length; i++) + { + key[i] = i; + } + // Generate some non-zero input longer than the key + byte[] input = new byte[key.Length + 1]; + for (byte i = 0; i < input.Length; i++) + { + input[i] = i; + } + // Hash the input + Blake2bDigest digest = new Blake2bDigest(key); + digest.BlockUpdate(input, 0, input.Length); + byte[] hash = new byte[digest.GetDigestSize()]; + digest.DoFinal(hash, 0); + // Using a second instance, hash the input without calling doFinal() + Blake2bDigest digest1 = new Blake2bDigest(key); + digest1.BlockUpdate(input, 0, input.Length); + // Reset the second instance and hash the input again + digest1.Reset(); + digest1.BlockUpdate(input, 0, input.Length); + byte[] hash1 = new byte[digest.GetDigestSize()]; + digest1.DoFinal(hash1, 0); + // The hashes should be identical + if (!Arrays.AreEqual(hash, hash1)) + { + Fail("state was not reset"); + } + } + + public static void Main(string[] args) + { + RunTest(new Blake2bDigestTest()); + } + + [Test] + public void TestFunction() + { + string resultText = Perform().ToString(); + + Assert.AreEqual(Name + ": Okay", resultText); + } + } +} diff --git a/crypto/test/src/crypto/test/Blake2sDigestTest.cs b/crypto/test/src/crypto/test/Blake2sDigestTest.cs new file mode 100644 index 000000000..2365071dd --- /dev/null +++ b/crypto/test/src/crypto/test/Blake2sDigestTest.cs @@ -0,0 +1,243 @@ +using System; +using System.Text; + +using NUnit.Framework; + +using Org.BouncyCastle.Crypto.Digests; +using Org.BouncyCastle.Utilities; +using Org.BouncyCastle.Utilities.Encoders; +using Org.BouncyCastle.Utilities.Test; + +namespace Org.BouncyCastle.Crypto.Tests +{ + [TestFixture] + public class Blake2sDigestTest + : SimpleTest + { + // Vectors from BLAKE2 web site: https://blake2.net/blake2s-test.txt + private static readonly string[][] keyedTestVectors = { + // input/message, key, hash + new string[]{ + "", + "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + "48a8997da407876b3d79c0d92325ad3b89cbb754d86ab71aee047ad345fd2c49", + }, + new string[]{ + "00", + "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + "40d15fee7c328830166ac3f918650f807e7e01e177258cdc0a39b11f598066f1", + }, + new string[]{ + "0001", + "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + "6bb71300644cd3991b26ccd4d274acd1adeab8b1d7914546c1198bbe9fc9d803", + }, + new string[]{ + "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d", + "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + "172ffc67153d12e0ca76a8b6cd5d4731885b39ce0cac93a8972a18006c8b8baf", + }, + new string[]{ + "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3", + "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + "4f8ce1e51d2fe7f24043a904d898ebfc91975418753413aa099b795ecb35cedb", + }, + new string[]{ + "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfe", + "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + "3fb735061abc519dfe979e54c1ee5bfad0a9d858b3315bad34bde999efd724dd", + }, + }; + + public override string Name + { + get { return "BLAKE2s"; } + } + + public void DoTestDigestWithKeyedTestVectors() + { + Blake2sDigest digest = new Blake2sDigest(Hex.Decode( + keyedTestVectors[0][1])); + for (int i = 0; i != keyedTestVectors.Length; i++) + { + String[] keyedTestVector = keyedTestVectors[i]; + byte[] input = Hex.Decode(keyedTestVector[0]); + digest.Reset(); + + digest.BlockUpdate(input, 0, input.Length); + byte[] hash = new byte[32]; + digest.DoFinal(hash, 0); + + if (!AreEqual(Hex.Decode(keyedTestVector[2]), hash)) + { + Fail("BLAKE2s mismatch on test vector ", + keyedTestVector[2], + Hex.ToHexString(hash)); + } + } + } + + public void DoTestDigestWithKeyedTestVectorsAndRandomUpdate() + { + Blake2sDigest digest = new Blake2sDigest(Hex.Decode( + keyedTestVectors[0][1])); + Random random = new Random(); + for (int i = 0; i < 100; i++) + { + for (int j = 0; j != keyedTestVectors.Length; j++) + { + String[] keyedTestVector = keyedTestVectors[j]; + byte[] input = Hex.Decode(keyedTestVector[0]); + if (input.Length < 3) + { + continue; + } + digest.Reset(); + + int pos = (random.Next() & 0xffff) % input.Length; + if (pos > 0) + { + digest.BlockUpdate(input, 0, pos); + } + digest.Update(input[pos]); + if (pos < (input.Length - 1)) + { + digest.BlockUpdate(input, pos + 1, input.Length - (pos + 1)); + } + + byte[] hash = new byte[32]; + digest.DoFinal(hash, 0); + + if (!AreEqual(Hex.Decode(keyedTestVector[2]), hash)) + { + Fail("BLAKE2s mismatch on test vector ", + keyedTestVector[2], + Hex.ToHexString(hash)); + } + } + } + } + + public void DoTestReset() + { + // Generate a non-zero key + byte[] key = new byte[32]; + for (byte i = 0; i < key.Length; i++) + { + key[i] = i; + } + // Generate some non-zero input longer than the key + byte[] input = new byte[key.Length + 1]; + for (byte i = 0; i < input.Length; i++) + { + input[i] = i; + } + // Hash the input + Blake2sDigest digest = new Blake2sDigest(key); + digest.BlockUpdate(input, 0, input.Length); + byte[] hash = new byte[digest.GetDigestSize()]; + digest.DoFinal(hash, 0); + // Create a second instance, hash the input without calling doFinal() + Blake2sDigest digest1 = new Blake2sDigest(key); + digest1.BlockUpdate(input, 0, input.Length); + // Reset the second instance and hash the input again + digest1.Reset(); + digest1.BlockUpdate(input, 0, input.Length); + byte[] hash1 = new byte[digest.GetDigestSize()]; + digest1.DoFinal(hash1, 0); + // The hashes should be identical + if (!AreEqual(hash, hash1)) + { + Fail("BLAKE2s mismatch on test vector ", + Hex.ToHexString(hash), + Hex.ToHexString(hash1)); + } + } + + // Self-test routine from https://tools.ietf.org/html/rfc7693#appendix-E + private static readonly string SELF_TEST_RESULT = + "6A411F08CE25ADCDFB02ABA641451CEC53C598B24F4FC787FBDC88797F4C1DFE"; + private static readonly int[] SELF_TEST_DIGEST_LEN = {16, 20, 28, 32}; + private static readonly int[] SELF_TEST_INPUT_LEN = {0, 3, 64, 65, 255, 1024}; + + private static byte[] selfTestSequence(int len, int seed) + { + int a = (int)(0xDEAD4BAD * seed); + int b = 1; + int t; + byte[] output = new byte[len]; + + for (int i = 0; i < len; i++) + { + t = a + b; + a = b; + b = t; + output[i] = (byte)(t >> 24); + } + + return output; + } + + public void RunSelfTest() + { + Blake2sDigest testDigest = new Blake2sDigest(); + byte[] md = new byte[32]; + + for (int i = 0; i < 4; i++) + { + int outlen = SELF_TEST_DIGEST_LEN[i]; + for (int j = 0; j < 6; j++) + { + int inlen = SELF_TEST_INPUT_LEN[j]; + + // unkeyed hash + byte[] input = selfTestSequence(inlen, inlen); + Blake2sDigest unkeyedDigest = new Blake2sDigest(outlen * 8); + unkeyedDigest.BlockUpdate(input, 0, inlen); + unkeyedDigest.DoFinal(md, 0); + // hash the hash + testDigest.BlockUpdate(md, 0, outlen); + + // keyed hash + byte[] key = selfTestSequence(outlen, outlen); + Blake2sDigest keyedDigest = new Blake2sDigest(key, outlen, null, + null); + keyedDigest.BlockUpdate(input, 0, inlen); + keyedDigest.DoFinal(md, 0); + // hash the hash + testDigest.BlockUpdate(md, 0, outlen); + } + } + + byte[] hash = new byte[32]; + testDigest.DoFinal(hash, 0); + if (!AreEqual(Hex.Decode(SELF_TEST_RESULT), hash)) + { + Fail("BLAKE2s mismatch on test vector ", + SELF_TEST_RESULT, + Hex.ToHexString(hash)); + } + } + + public override void PerformTest() + { + DoTestDigestWithKeyedTestVectors(); + DoTestDigestWithKeyedTestVectorsAndRandomUpdate(); + DoTestReset(); + RunSelfTest(); + } + + public static void Main(string[] args) + { + RunTest(new Blake2sDigestTest()); + } + + [Test] + public void TestFunction() + { + string resultText = Perform().ToString(); + + Assert.AreEqual(Name + ": Okay", resultText); + } + } +} diff --git a/crypto/test/src/crypto/test/RegressionTest.cs b/crypto/test/src/crypto/test/RegressionTest.cs index c065a1320..13fe23ecc 100644 --- a/crypto/test/src/crypto/test/RegressionTest.cs +++ b/crypto/test/src/crypto/test/RegressionTest.cs @@ -126,6 +126,8 @@ namespace Org.BouncyCastle.Crypto.Tests new BCryptTest(), new OpenBsdBCryptTest(), new X931SignerTest(), + new Blake2bDigestTest(), + new Blake2sDigestTest(), new KeccakDigestTest(), new ShakeDigestTest(), new SM2EngineTest(), diff --git a/crypto/test/src/test/DigestTest.cs b/crypto/test/src/test/DigestTest.cs index 5d840ee66..9f68a8361 100644 --- a/crypto/test/src/test/DigestTest.cs +++ b/crypto/test/src/test/DigestTest.cs @@ -3,6 +3,9 @@ using System.Text; using NUnit.Framework; +using Org.BouncyCastle.Asn1.Misc; +using Org.BouncyCastle.Asn1.Rosstandart; +using Org.BouncyCastle.Asn1.UA; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Security; using Org.BouncyCastle.Utilities.Encoders; @@ -32,7 +35,43 @@ namespace Org.BouncyCastle.Tests { "RIPEMD320", "de4c01b3054f8930a79d09ae738e92301e5a17085beffdc1b8d116713e74f82fa942d64cdbc4682d" }, { "Tiger", "2AAB1484E8C158F2BFB8C5FF41B57A525129131C957B5F93" }, { "GOST3411", "b285056dbf18d7392d7677369524dd14747459ed8143997e163b2986f92fd42c" }, - { "WHIRLPOOL", "4E2448A4C6F486BB16B6562C73B4020BF3043E3A731BCE721AE1B303D97E6D4C7181EEBDB6C57E277D0E34957114CBD6C797FC9D95D8B582D225292076D4EEF5" } + { "WHIRLPOOL", "4E2448A4C6F486BB16B6562C73B4020BF3043E3A731BCE721AE1B303D97E6D4C7181EEBDB6C57E277D0E34957114CBD6C797FC9D95D8B582D225292076D4EEF5" }, + { "SM3", "66c7f0f462eeedd9d1f2d46bdc10e4e24167c4875cf2f7a2297da02b8f4ba8e0" }, + { "SHA3-224", "e642824c3f8cf24ad09234ee7d3c766fc9a3a5168d0c94ad73b46fdf" }, + { "SHA3-256", "3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532" }, + { "SHA3-384", "ec01498288516fc926459f58e2c6ad8df9b473cb0fc08c2596da7cf0e49be4b298d88cea927ac7f539f1edf228376d25" }, + { "SHA3-512", "b751850b1a57168a5693cd924b6b096e08f621827444f70d884f5d0240d2712e10e116e9192af3c91a7ec57647e3934057340b4cf408d5a56592f8274eec53f0" }, + { "KECCAK-224", "c30411768506ebe1c2871b1ee2e87d38df342317300a9b97a95ec6a8" }, + { "KECCAK-256", "4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45" }, + { "KECCAK-288", "20ff13d217d5789fa7fc9e0e9a2ee627363ec28171d0b6c52bbd2f240554dbc94289f4d6" }, + { "KECCAK-384", "f7df1165f033337be098e7d288ad6a2f74409d7a60b49c36642218de161b1f99f8c681e4afaf31a34db29fb763e3c28e" }, + { "KECCAK-512", "18587dc2ea106b9a1563e32b3312421ca164c7f1f07bc922a9c83d77cea3a1e5d0c69910739025372dc14ac9642629379540c17e2a65b19d77aa511a9d00bb96" }, + { "BLAKE2B-160", "384264f676f39536840523f284921cdc68b6846b" }, + { "BLAKE2B-256", "bddd813c634239723171ef3fee98579b94964e3bb1cb3e427262c8c068d52319" }, + { "BLAKE2B-384", "6f56a82c8e7ef526dfe182eb5212f7db9df1317e57815dbda46083fc30f54ee6c66ba83be64b302d7cba6ce15bb556f4" }, + { "BLAKE2B-512", "ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d17d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923" }, + { MiscObjectIdentifiers.id_blake2b160.Id, "384264f676f39536840523f284921cdc68b6846b" }, + { MiscObjectIdentifiers.id_blake2b256.Id, "bddd813c634239723171ef3fee98579b94964e3bb1cb3e427262c8c068d52319" }, + { MiscObjectIdentifiers.id_blake2b384.Id, "6f56a82c8e7ef526dfe182eb5212f7db9df1317e57815dbda46083fc30f54ee6c66ba83be64b302d7cba6ce15bb556f4" }, + { MiscObjectIdentifiers.id_blake2b512.Id, "ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d17d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923" }, + { "BLAKE2S-128", "aa4938119b1dc7b87cbad0ffd200d0ae" }, + { "BLAKE2S-160", "5ae3b99be29b01834c3b508521ede60438f8de17" }, + { "BLAKE2S-224", "0b033fc226df7abde29f67a05d3dc62cf271ef3dfea4d387407fbd55" }, + { "BLAKE2S-256", "508c5e8c327c14e2e1a72ba34eeb452f37458b209ed63a294d999b4c86675982" }, + { MiscObjectIdentifiers.id_blake2s128.Id, "aa4938119b1dc7b87cbad0ffd200d0ae" }, + { MiscObjectIdentifiers.id_blake2s160.Id, "5ae3b99be29b01834c3b508521ede60438f8de17" }, + { MiscObjectIdentifiers.id_blake2s224.Id, "0b033fc226df7abde29f67a05d3dc62cf271ef3dfea4d387407fbd55" }, + { MiscObjectIdentifiers.id_blake2s256.Id, "508c5e8c327c14e2e1a72ba34eeb452f37458b209ed63a294d999b4c86675982" }, + { "GOST3411-2012-256", "4e2919cf137ed41ec4fb6270c61826cc4fffb660341e0af3688cd0626d23b481" }, + { RosstandartObjectIdentifiers.id_tc26_gost_3411_12_256.Id, "4e2919cf137ed41ec4fb6270c61826cc4fffb660341e0af3688cd0626d23b481" }, + { "GOST3411-2012-512", "28156e28317da7c98f4fe2bed6b542d0dab85bb224445fcedaf75d46e26d7eb8d5997f3e0915dd6b7f0aab08d9c8beb0d8c64bae2ab8b3c8c6bc53b3bf0db728" }, + { RosstandartObjectIdentifiers.id_tc26_gost_3411_12_512.Id, "28156e28317da7c98f4fe2bed6b542d0dab85bb224445fcedaf75d46e26d7eb8d5997f3e0915dd6b7f0aab08d9c8beb0d8c64bae2ab8b3c8c6bc53b3bf0db728" }, + { "DSTU7564-256", "0bd1b36109f1318411a0517315aa46b8839df06622a278676f5487996c9cfc04" }, + { UAObjectIdentifiers.dstu7564digest_256.Id, "0bd1b36109f1318411a0517315aa46b8839df06622a278676f5487996c9cfc04" }, + { "DSTU7564-384", "72945012b0820c3132846ddc90da511f80bb7b70abd0cb1ab8df785d600c187b9d0ac567e8b6f76fde8a0b417a2ebf88" }, + { UAObjectIdentifiers.dstu7564digest_384.Id, "72945012b0820c3132846ddc90da511f80bb7b70abd0cb1ab8df785d600c187b9d0ac567e8b6f76fde8a0b417a2ebf88" }, + { "DSTU7564-512", "9e5be7daf7b68b49d2ecbd04c7a5b3af72945012b0820c3132846ddc90da511f80bb7b70abd0cb1ab8df785d600c187b9d0ac567e8b6f76fde8a0b417a2ebf88" }, + { UAObjectIdentifiers.dstu7564digest_512.Id, "9e5be7daf7b68b49d2ecbd04c7a5b3af72945012b0820c3132846ddc90da511f80bb7b70abd0cb1ab8df785d600c187b9d0ac567e8b6f76fde8a0b417a2ebf88" }, }; public override string Name |