public void TestHkdfVector2() { // Expected Values byte[] prkFromSpec = Util.StringToByteArray("06a6b88c5853361a06104c9ceb35b45cef760014904671" + "014a193f40c15fc244"); byte[] okmFromSpec = Util.StringToByteArray("b11e398dc80327a1c8e7f78c596a49344f012eda2d4efa" + "d8a050cc4c19afa97c59045a99cac7827271cb41c65e590e09da3275600c2f09b8367793a9aca3db71c" + "c30c58179ec3e87c14c01d5c1f3434f1d87"); byte[] ikmBytes = Util.StringToByteArray("000102030405060708090a0b0c0d0e0f101112131" + "415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d" + "3e3f404142434445464748494a4b4c4d4e4f"); byte[] saltBytes = Util.StringToByteArray("606162636465666768696a6b6c6d6e6f70717273" + "7475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9" + "d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeaf"); byte[] infoBytes = Util.StringToByteArray("b0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3" + "c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebece" + "deeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff"); int length = 82; Hkdf hkdf = new Hkdf(saltBytes, ikmBytes); byte[] hkdfResult = hkdf.Expand(infoBytes, length); Assert.Equal(prkFromSpec, hkdf.Prk); Assert.Equal(okmFromSpec, hkdfResult); }
public void TestCase1() { var hash = HashAlgorithmName.SHA256; var ikm = StringToByteArray("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"); var salt = StringToByteArray("000102030405060708090a0b0c"); var info = StringToByteArray("f0f1f2f3f4f5f6f7f8f9"); var len = 42; var expectedPrk = StringToByteArray("077709362c2e32df0ddc3f0dc47bba63" + "90b6c73bb50f9c3122ec844ad7c2b3e5"); var expectedOkm = StringToByteArray("3cb25f25faacd57a90434f64d0362f2a" + "2d2d0a90cf1a5a4c5db02d56ecc4c5bf" + "34007208d5b887185865"); using (var hkdf = new Hkdf(hash)) { var actualPrk = hkdf.Extract(ikm, salt); Assert.Equal(expectedPrk, actualPrk); var actualOkm = hkdf.Expand(actualPrk, len, info); Assert.Equal(expectedOkm, actualOkm); } }
public void Test(DigestType type, string ikmHex, string saltHex, string infoHex, string prkHex, string okmHex) { Span <byte> prk = stackalloc byte[255]; var length = Hkdf.Extract(type, ikmHex.FromHex(), saltHex.FromHex(), prk); Assert.AreEqual(prkHex, prk[..length].ToHex());
private (string passwordToken, PasswordSalts passwordSalts, PasswordBasedBackup passwordBasedBackup) GeneratePasswordToken(string password, byte[] seed) { var passwordSalt = Scrypt.GenerateSalt(); var passwordHash = Scrypt.Hash(password, passwordSalt); //var passwordHkdfKey = crypto.hkdf.importHkdfKeyFromString(passwordHash) var passwordTokenSalt = Hkdf.GenerateSalt(); var passwordToken = Hkdf.GetPasswordToken(/*passwordHkdfKey*/ passwordHash, passwordTokenSalt); var passwordBasedEncryptionKeySalt = Hkdf.GenerateSalt(); var passwordBasedEncryptionKey = AesGcmUtils.GetPasswordBasedEncryptionKey(passwordHash, passwordBasedEncryptionKeySalt); var passwordEncryptedSeed = AesGcmUtils.Encrypt(passwordBasedEncryptionKey, seed); var passwordSalts = new PasswordSalts { PasswordSalt = Convert.ToBase64String(passwordSalt), PasswordTokenSalt = Convert.ToBase64String(passwordTokenSalt), }; var passwordBasedBackup = new PasswordBasedBackup { PasswordBasedEncryptionKeySalt = Convert.ToBase64String(passwordBasedEncryptionKeySalt), PasswordEncryptedSeed = Convert.ToBase64String(passwordEncryptedSeed), }; return(passwordToken, passwordSalts, passwordBasedBackup); }
public bool deriveKeyAndNonce(byte[] key, byte[] auth, out byte[] bits, out byte[] nonce, byte[] pub, byte[] senderPub, byte[] salt) { var authKdf = new Hkdf(); var authInfo = new List <byte>(); authInfo.AddRange(System.Text.Encoding.UTF8.GetBytes("WebPush: info\0")); //authInfo.AddRange(System.Text.Encoding.UTF8.GetBytes(pub)); //authInfo.AddRange(System.Text.Encoding.UTF8.GetBytes(senderPub)); authInfo.AddRange(pub); authInfo.AddRange(senderPub); var prk = authKdf.DeriveKey(auth, key, authInfo.ToArray(), 32); var prkKdf = new Hkdf(); var keyInfo = new List <byte>(); keyInfo.AddRange(System.Text.Encoding.UTF8.GetBytes("Content-Encoding: aes128gcm\0")); var keyInfoPrk = prkKdf.DeriveKey(salt, prk, keyInfo.ToArray(), 16); var Kdf = new Hkdf(); var nonceInfo = new List <byte>(); nonceInfo.AddRange(System.Text.Encoding.UTF8.GetBytes("Content-Encoding: nonce\0")); var nonceInfoPrk = prkKdf.DeriveKey(salt, prk, nonceInfo.ToArray(), 12); bits = keyInfoPrk; nonce = nonceInfoPrk; return(true); }
public void TestHkdfLimit() { using (var hkdf = Hkdf.CreateSha256Hkdf(null, null, null)) { hkdf.GetBytes(new byte[32 * 255]); Assert.Throws <CryptographicException>(() => hkdf.GetBytes(new byte[1])); } }
public void TestChainKeyDerivationV3() { byte[] seed = { 0x8a, 0xb7, 0x2d, 0x6f, 0x4c, 0xc5, 0xac, 0x0d, 0x38, 0x7e, 0xaf, 0x46, 0x33, 0x78, 0xdd, 0xb2, 0x8e, 0xdd, 0x07, 0x38, 0x5b, 0x1c, 0xb0, 0x12, 0x50, 0xc7, 0x15, 0x98, 0x2e, 0x7a, 0xd4, 0x8f }; byte[] messageKey = { /* 0x02*/ 0xbf, 0x51, 0xe9, 0xd7, 0x5e, 0x0e, 0x31, 0x03, 0x10, 0x51, 0xf8, 0x2a, 0x24, 0x91, 0xff, 0xc0, 0x84, 0xfa, 0x29, 0x8b, 0x77, 0x93, 0xbd, 0x9d, 0xb6, 0x20, 0x05, 0x6f, 0xeb, 0xf4, 0x52, 0x17 }; byte[] macKey = { 0xc6, 0xc7, 0x7d, 0x6a, 0x73, 0xa3, 0x54, 0x33, 0x7a, 0x56, 0x43, 0x5e, 0x34, 0x60, 0x7d, 0xfe, 0x48, 0xe3, 0xac, 0xe1, 0x4e, 0x77, 0x31, 0x4d, 0xc6, 0xab, 0xc1, 0x72, 0xe7, 0xa7, 0x03, 0x0b }; byte[] nextChainKey = { 0x28, 0xe8, 0xf8, 0xfe, 0xe5, 0x4b, 0x80, 0x1e, 0xef, 0x7c, 0x5c, 0xfb, 0x2f, 0x17, 0xf3, 0x2c, 0x7b, 0x33, 0x44, 0x85, 0xbb, 0xb7, 0x0f, 0xac, 0x6e, 0xc1, 0x03, 0x42, 0xa2, 0x46, 0xd1, 0x5d }; ChainKey chainKey = new ChainKey(Hkdf.CreateFor(3), seed, 0); CollectionAssert.AreEqual(seed, chainKey.GetKey()); CollectionAssert.AreEqual(messageKey, chainKey.GetMessageKeys().GetCipherKey()); CollectionAssert.AreEqual(macKey, chainKey.GetMessageKeys().GetMacKey()); CollectionAssert.AreEqual(nextChainKey, chainKey.GetNextChainKey().GetKey()); Assert.AreEqual <uint>(0, chainKey.GetIndex()); Assert.AreEqual <uint>(0, chainKey.GetMessageKeys().GetCounter()); Assert.AreEqual <uint>(1, chainKey.GetNextChainKey().GetIndex()); Assert.AreEqual <uint>(1, chainKey.GetNextChainKey().GetMessageKeys().GetCounter()); }
public void Default() { Span <byte> output = stackalloc byte[82]; for (var i = 0; i < Max; ++i) { Hkdf.DeriveKey(DigestType.Sha256, _ikm, output, _salt, _info); } }
public void Generate_returns_expected_values(TestCase tc) { var result = Hkdf.Generate(ikm: tc.Ikm.DecodeHex(), salt: tc.Salt.DecodeHex(), info: tc.Info.DecodeHex(), byteCount: tc.ByteCount); Assert.Equal(tc.Expected.DecodeHex(), result); }
public void TestChainKeyDerivationV2() { byte[] seed = { 0x8a, 0xb7, 0x2d, 0x6f, 0x4c, 0xc5, 0xac, 0x0d, 0x38, 0x7e, 0xaf, 0x46, 0x33, 0x78, 0xdd, 0xb2, 0x8e, 0xdd, 0x07, 0x38, 0x5b, 0x1c, 0xb0, 0x12, 0x50, 0xc7, 0x15, 0x98, 0x2e, 0x7a, 0xd4, 0x8f }; byte[] messageKey = { 0x02, 0xa9, 0xaa, 0x6c, 0x7d, 0xbd, 0x64, 0xf9, 0xd3, 0xaa, 0x92, 0xf9, 0x2a, 0x27, 0x7b, 0xf5, 0x46, 0x09, 0xda, 0xdf, 0x0b, 0x00, 0x82, 0x8a, 0xcf, 0xc6, 0x1e, 0x3c, 0x72, 0x4b, 0x84, 0xa7 }; byte[] macKey = { 0xbf, 0xbe, 0x5e, 0xfb, 0x60, 0x30, 0x30, 0x52, 0x67, 0x42, 0xe3, 0xee, 0x89, 0xc7, 0x02, 0x4e, 0x88, 0x4e, 0x44, 0x0f, 0x1f, 0xf3, 0x76, 0xbb, 0x23, 0x17, 0xb2, 0xd6, 0x4d, 0xeb, 0x7c, 0x83 }; byte[] nextChainKey = { 0x28, 0xe8, 0xf8, 0xfe, 0xe5, 0x4b, 0x80, 0x1e, 0xef, 0x7c, 0x5c, 0xfb, 0x2f, 0x17, 0xf3, 0x2c, 0x7b, 0x33, 0x44, 0x85, 0xbb, 0xb7, 0x0f, 0xac, 0x6e, 0xc1, 0x03, 0x42, 0xa2, 0x46, 0xd1, 0x5d }; ChainKey chainKey = new ChainKey(Hkdf.CreateFor(2), seed, 0); Assert.AreEqual(seed, chainKey.GetKey()); CollectionAssert.AreEqual(messageKey, chainKey.GetMessageKeys().GetCipherKey()); CollectionAssert.AreEqual(macKey, chainKey.GetMessageKeys().GetMacKey()); CollectionAssert.AreEqual(nextChainKey, chainKey.GetNextChainKey().GetKey()); Assert.AreEqual <uint>(0, chainKey.GetIndex()); Assert.AreEqual <uint>(0, chainKey.GetMessageKeys().GetCounter()); Assert.AreEqual <uint>(1, chainKey.GetNextChainKey().GetIndex()); Assert.AreEqual <uint>(1, chainKey.GetNextChainKey().GetMessageKeys().GetCounter()); }
public static byte[] getPasswordAuthenticationKey(String userId, String userPassword, String poolName, Tuple <BigInteger, BigInteger> Aa, BigInteger B, BigInteger salt) { // Authenticate the password // u = H(A, B) HashAlgorithm messageDigest = THREAD_MESSAGE_DIGEST; byte[] aArr = Aa.Item1.ToByteArray(); byte[] bArr = B.ToByteArray(); byte[] content = new byte[aArr.Length + bArr.Length]; Buffer.BlockCopy(aArr, 0, content, 0, aArr.Length); Buffer.BlockCopy(bArr, 0, content, aArr.Length, bArr.Length); byte[] digest = messageDigest.ComputeHash(content); BigInteger u = new BigInteger(1, digest); if (u.Equals(BigInteger.Zero)) { throw new Exception("Hash of A and B cannot be zero"); } // x = H(salt | H(poolName | userId | ":" | password)) byte[] poolArr = Encoding.UTF8.GetBytes(poolName); byte[] idArr = Encoding.UTF8.GetBytes(userId); byte[] colonArr = Encoding.UTF8.GetBytes(":"); byte[] passArr = Encoding.UTF8.GetBytes(userPassword); byte[] userIdContent = new byte[poolArr.Length + idArr.Length + colonArr.Length + passArr.Length]; Buffer.BlockCopy(poolArr, 0, userIdContent, 0, poolArr.Length); Buffer.BlockCopy(idArr, 0, userIdContent, poolArr.Length, idArr.Length); Buffer.BlockCopy(colonArr, 0, userIdContent, poolArr.Length + idArr.Length, colonArr.Length); Buffer.BlockCopy(passArr, 0, userIdContent, poolArr.Length + idArr.Length + colonArr.Length, passArr.Length); byte[] userIdHash = messageDigest.ComputeHash(userIdContent); byte[] saltArr = salt.ToByteArray(); byte[] xArr = new byte[saltArr.Length + userIdHash.Length]; Buffer.BlockCopy(saltArr, 0, xArr, 0, saltArr.Length); Buffer.BlockCopy(userIdHash, 0, xArr, saltArr.Length, userIdHash.Length); byte[] xDigest = messageDigest.ComputeHash(xArr); BigInteger x = new BigInteger(1, xDigest); BigInteger S = (B.Subtract(k.Multiply(g.ModPow(x, N))).ModPow(Aa.Item2.Add(u.Multiply(x)), N)).Mod(N); Hkdf hkdf = new Hkdf(); byte[] key = hkdf.DeriveKey(u.ToByteArray(), S.ToByteArray(), Encoding.UTF8.GetBytes(DERIVED_KEY_INFO), DERIVED_KEY_SIZE); return(key); }
public async Task <(string sessionId, DateTime creationDate, string userId)> GenerateKeysAndSignUp( string username, string password, byte[] seed, string email, Dictionary <string, string> profile) { var(passwordToken, passwordSalts, passwordBasedBackup) = GeneratePasswordToken(password, seed); var encryptionKeySalt = Hkdf.GenerateSalt(); var dhKeySalt = Hkdf.GenerateSalt(); var hmacKeySalt = Hkdf.GenerateSalt(); var dhPrivateKey = DiffieHellmanUtils.ImportKeyFromMaster(seed, dhKeySalt); var publicKey = DiffieHellmanUtils.GetPublicKey(dhPrivateKey); var keySalts = new KeySalts { EncryptionKeySalt = Convert.ToBase64String(encryptionKeySalt), DhKeySalt = Convert.ToBase64String(dhKeySalt), HmacKeySalt = Convert.ToBase64String(hmacKeySalt), }; var request = new SignUpApiRequest { Username = username, PasswordToken = passwordToken, PublicKey = publicKey, PasswordSalts = passwordSalts, KeySalts = keySalts, Email = email, Profile = profile, PasswordBasedBackup = passwordBasedBackup }; var response = await _api.SignUp(request); if (response.IsSuccessStatusCode) { var apiResponse = JsonConvert.DeserializeObject <SignUpApiResponse>(await response.Content.ReadAsStringAsync()); return(apiResponse.SessionId, apiResponse.CreationDate, apiResponse.UserId); } var one = ParseGenericErrors(await response.Content.ReadAsStringAsync(), response.StatusCode); if (one != null) { throw one; } var two = await ParseGenericUsernamePasswordError(response); if (two != null) { throw two; } throw new Exception($"Unknown error during SignUp: {response.StatusCode} - {await response.Content.ReadAsStringAsync()}"); }
public void Generate_returns_expected_values() { foreach (var i in HkdfTestCases) { var result = Hkdf.Generate(i.Ikm.DecodeHex(), i.Salt.DecodeHex(), i.Info.DecodeHex(), i.ByteCount); Assert.That(result, Is.EqualTo(i.Expected.DecodeHex())); } }
internal static HandshakeProcessor InitiateNoiseProtocol(IKeyGenerator keyGenerator, byte[] s) { var hkdf = new Hkdf(new HashWithState(), new HashWithState()); return(new HandshakeProcessor(new EllipticCurveActions(), hkdf, new ChaCha20Poly1305CipherFunction( new Mock <ILogger <ChaCha20Poly1305CipherFunction> >().Object), keyGenerator, new Sha256(new Mock <ILogger <Sha256> >().Object), new NoiseMessageTransformer(hkdf, new ChaCha20Poly1305CipherFunction(new Mock <ILogger <ChaCha20Poly1305CipherFunction> >().Object), new ChaCha20Poly1305CipherFunction(new Mock <ILogger <ChaCha20Poly1305CipherFunction> >().Object), new Mock <ILogger <NoiseMessageTransformer> >().Object), new Mock <ILogger <HandshakeProcessor> >().Object)); }
private static Hkdf CreateHkdf(string algorithm, byte[] ikm, byte[] salt, byte[] info) { switch (algorithm) { case "SHA-1": return(Hkdf.CreateSha1Hkdf(ikm, salt, info)); case "SHA-256": return(Hkdf.CreateSha256Hkdf(ikm, salt, info)); default: throw new ArgumentException("Unknown algorithm."); } }
public void Rfc5869HmacSha1TestVector(string salt, string ikm, string info, int length, string expectedPrk, string expectedOkm) { var hkdf = new Hkdf(HashAlgorithmName.SHA1); var prk = hkdf.Extract(StringToByteArray(salt), StringToByteArray(ikm)); ByteArrayToString(prk).Should().BeEquivalentTo(expectedPrk); var okm = hkdf.Expand(prk, StringToByteArray(info), length); ByteArrayToString(okm).Should().BeEquivalentTo(expectedOkm); }
public void Rfc5869HmacSha256TestVector(string salt, string ikm, string info, int length, string expectedPrk, string expectedOkm) { using (var hkdf = new Hkdf <HMACSHA256>()) { var prk = hkdf.Extract(StringToByteArray(salt), StringToByteArray(ikm)); ByteArrayToString(prk).Should().BeEquivalentTo(expectedPrk); var okm = hkdf.Expand(prk, StringToByteArray(info), length); ByteArrayToString(okm).Should().BeEquivalentTo(expectedOkm); } }
private IAEADCrypto CreateSessionCrypto() { Span <byte> sessionKey = SessionKeySpan; Hkdf.DeriveKey( DigestType.Sha1, MasterKeySpan, sessionKey, SaltSpan, ShadowsocksCrypto.InfoBytes ); return(CreateCrypto(sessionKey)); }
static public byte[] ExpandTLSLabel(Hkdf hkdf, byte[] secret, ReadOnlySpan <byte> label, ushort length) { var info = new byte[4 + TLS_LABEL.Length + label.Length]; info.AsSpan().Write(length) .Write((byte)(TLS_LABEL.Length + label.Length)) .Write(TLS_LABEL) .Write(label) .Write((byte)0); //Console.WriteLine($"info: {BitConverter.ToString(info).Replace("-", "")}"); return(hkdf.Expand(secret, length, info)); }
public static RebuildPasswordTokenResponse RebuildPasswordToken(string password, GetPasswordSaltsResponse salts) { var passwordhash = Scrypt.Hash(password, salts.PasswordSalt); var ikm = Utils.FillOddsWithZeros(Encoding.ASCII.GetBytes(passwordhash)); var info = Utils.FillOddsWithZeros(Encoding.ASCII.GetBytes("password-token")); var salt = Convert.FromBase64String(salts.PasswordTokenSalt); var passwordToken = new Hkdf().DeriveKey(salt, ikm, info, 32); return(new RebuildPasswordTokenResponse { PasswordHkdfKey = ikm, PasswordToken = Convert.ToBase64String(passwordToken), }); }
private static void TestCase2() { byte[] inputKeyingMaterial = Utilities.HexToBinary("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f"); byte[] salt = Utilities.HexToBinary("606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeaf"); byte[] info = Utilities.HexToBinary("b0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff"); int outputLength = 82; string expectedPrk = "06a6b88c5853361a06104c9ceb35b45cef760014904671014a193f40c15fc244"; string expectedOkm = "b11e398dc80327a1c8e7f78c596a49344f012eda2d4efad8a050cc4c19afa97c59045a99cac7827271cb41c65e590e09da3275600c2f09b8367793a9aca3db71cc30c58179ec3e87c14c01d5c1f3434f1d87"; string actualPrk = Utilities.BinaryToHex(Hkdf.Extract(HashAlgorithmName.SHA256, inputKeyingMaterial, salt)); string actualOkm = Utilities.BinaryToHex(Hkdf.DeriveKey(HashAlgorithmName.SHA256, inputKeyingMaterial, outputLength, info, salt)); Console.WriteLine($"Test 2.1: {(expectedPrk == actualPrk ? Success : Fail)}"); Console.WriteLine($"Test 2.2: {(expectedOkm == actualOkm ? Success : Fail)}"); }
private static void TestCase3() { byte[] inputKeyingMaterial = Utilities.HexToBinary("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"); var salt = Array.Empty <byte>(); var info = Array.Empty <byte>(); int outputLength = 42; string expectedPrk = "19ef24a32c717b167f33a91d6f648bdf96596776afdb6377ac434c1c293ccb04"; string expectedOkm = "8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d9d201395faa4b61a96c8"; string actualPrk = Utilities.BinaryToHex(Hkdf.Extract(HashAlgorithmName.SHA256, inputKeyingMaterial, salt)); string actualOkm = Utilities.BinaryToHex(Hkdf.DeriveKey(HashAlgorithmName.SHA256, inputKeyingMaterial, outputLength, info, salt)); Console.WriteLine($"Test 3.1: {(expectedPrk == actualPrk ? Success : Fail)}"); Console.WriteLine($"Test 3.2: {(expectedOkm == actualOkm ? Success : Fail)}"); }
public void HkdfShouldProduceCorrectResults(ModeValues mode, DigestSizes digest, string ikm, string salt, string info, int length, string okm) { var hmac = new HmacFactory(new NativeShaFactory()).GetHmacInstance(new HashFunction(mode, digest)); var hkdf = new Hkdf(hmac); var ikmBs = new BitString(ikm); var saltBs = new BitString(salt); var infoBs = new BitString(info); var okmBs = new BitString(okm); var result = hkdf.DeriveKey(saltBs, ikmBs, infoBs, length); Assert.IsTrue(result.Success); Assert.AreEqual(okmBs, result.DerivedKey); }
private static void TestCase1() { byte[] inputKeyingMaterial = Utilities.HexToBinary("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"); byte[] salt = Utilities.HexToBinary("000102030405060708090a0b0c"); byte[] info = Utilities.HexToBinary("f0f1f2f3f4f5f6f7f8f9"); int outputLength = 42; string expectedPrk = "077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5"; string expectedOkm = "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865"; string actualPrk = Utilities.BinaryToHex(Hkdf.Extract(HashAlgorithmName.SHA256, inputKeyingMaterial, salt)); string actualOkm = Utilities.BinaryToHex(Hkdf.DeriveKey(HashAlgorithmName.SHA256, inputKeyingMaterial, outputLength, info, salt)); Console.WriteLine($"Test 1.1: {(expectedPrk == actualPrk ? Success : Fail)}"); Console.WriteLine($"Test 1.2: {(expectedOkm == actualOkm ? Success : Fail)}"); }
public ChainKey GetReceiverChainKey(IEcPublicKey senderEphemeral) { Pair <StorageProtos.SessionStructure.Types.Chain, uint> receiverChainAndIndex = GetReceiverChain(senderEphemeral); StorageProtos.SessionStructure.Types.Chain receiverChain = receiverChainAndIndex.First(); if (receiverChain == null) { return(null); } else { return(new ChainKey(Hkdf.CreateFor(GetSessionVersion()), receiverChain.ChainKey.Key.ToByteArray(), receiverChain.ChainKey.Index)); } }
/// <summary> /// Generates a versioned authentication header /// </summary> /// <param name="httpMethod">The HTTP method</param> /// <param name="uri">The URI</param> /// <param name="token">A ncryptf.Token instance</param> /// <param name="date">DateTime date</param> /// <param name="payload">String payload</param> /// <param name="version">Authorization version to generate. Defaults to 2</param> /// <param name="salt">32 byte salt value. If not provided, one will be generated.</param> public Authorization( String httpMethod, String uri, Token token, DateTime date, String payload, int version = 2, byte[] salt = null ) { httpMethod = httpMethod.ToUpper(); if (salt == null) { salt = SodiumCore.GetRandomBytes(32); } if (salt.Length != 32) { throw new ArgumentException("Salt must be 32 bytes"); } this.salt = salt; this.signature = Signature.Derive(httpMethod, uri, salt, date, payload, version); this.date = date; this.version = version; this.token = token; Hkdf hkdf = new Hkdf(HashAlgorithmName.SHA256); byte[] kdf = hkdf.Expand( hkdf.Extract(token.IKM, salt), 32, System.Text.Encoding.UTF8.GetBytes(AUTH_INFO) ); String hkdfString = Sodium.Utilities.BinaryToHex(kdf); byte[] key = System.Text.Encoding.UTF8.GetBytes(hkdfString.ToLower()); byte[] sig = System.Text.Encoding.UTF8.GetBytes(this.signature); HMACSHA256 hmac = new HMACSHA256(key); this.hmac = hmac.ComputeHash(sig); }
public void TestVectorV2() { byte[] ikm = { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b }; byte[] salt = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c }; byte[] info = { 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9 }; byte[] okm = { 0x6e, 0xc2, 0x55, 0x6d, 0x5d, 0x7b, 0x1d, 0x81, 0xde, 0xe4, 0x22, 0x2a, 0xd7, 0x48, 0x36, 0x95, 0xdd, 0xc9, 0x8f, 0x4f, 0x5f, 0xab, 0xc0, 0xe0, 0x20, 0x5d, 0xc2, 0xef, 0x87, 0x52, 0xd4, 0x1e, 0x04, 0xe2, 0xe2, 0x11, 0x01, 0xc6, 0x8f, 0xf0, 0x93, 0x94, 0xb8, 0xad, 0x0b, 0xdc, 0xb9, 0x60, 0x9c, 0xd4, 0xee, 0x82, 0xac, 0x13, 0x19, 0x9b, 0x4a, 0xa9, 0xfd, 0xa8, 0x99, 0xda, 0xeb, 0xec }; byte[] actualOutput = Hkdf.CreateFor(2).DeriveSecrets(ikm, salt, info, 64); CollectionAssert.AreEqual(okm, actualOutput); }
public void TestHkdfVector3() { // Expected Values byte[] prkFromSpec = Util.StringToByteArray("19ef24a32c717b167f33a91d6f648bdf96596776afdb6" + "377ac434c1c293ccb04"); byte[] okmFromSpec = Util.StringToByteArray("8da4e775a563c18f715f802a063c5a31b8a11f5c5ee18" + "79ec3454e5f3c738d2d9d201395faa4b61a96c8"); byte[] ikmBytes = Util.StringToByteArray("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"); byte[] saltBytes = Util.StringToByteArray(""); byte[] infoBytes = Util.StringToByteArray(""); int length = 42; Hkdf hkdf = new Hkdf(saltBytes, ikmBytes); byte[] hkdfResult = hkdf.Expand(infoBytes, length); Assert.Equal(prkFromSpec, hkdf.Prk); Assert.Equal(okmFromSpec, hkdfResult); }
public void TestHkdfVector1() { // Expected Values byte[] prkFromSepc = Util.StringToByteArray("077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3" + "122ec844ad7c2b3e5"); byte[] okmFromSpec = Util.StringToByteArray("3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4" + "c5db02d56ecc4c5bf34007208d5b887185865"); byte[] ikmBytes = Util.StringToByteArray("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"); byte[] saltBytes = Util.StringToByteArray("000102030405060708090a0b0c"); byte[] infoBytes = Util.StringToByteArray("f0f1f2f3f4f5f6f7f8f9"); int length = 42; Hkdf hkdf = new Hkdf(saltBytes, ikmBytes); byte[] hkdfResult = hkdf.Expand(infoBytes, length); Assert.Equal(prkFromSepc, hkdf.Prk); Assert.Equal(okmFromSpec, hkdfResult); }
// Decrypt a byte array into a byte array using a key and an IV private byte[] Decrypt(byte[] cipherData, byte[] Key, byte[] IV) { Hkdf hkdf = new Hkdf(); byte[] output = hkdf.DeriveKey(salt, this.key, info, 48); Array.Copy(output, 0, this.key, 0, 32); Array.Copy(output, 32, InitV, 0, 16); MemoryStream ms = new MemoryStream(); Rijndael alg = Rijndael.Create(); alg.Key = Key; alg.IV = InitV; alg.Padding = PaddingMode.None; CryptoStream cs = new CryptoStream(ms, alg.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(cipherData, 0, cipherData.Length); cs.Close(); byte[] decryptedData = ms.ToArray(); return(decryptedData); }