/// <summary> /// Gets the verifying stream. /// </summary> /// <returns></returns> public VerifyingStream GetVerifyingStream(Keyczar keyczar) { var hmac = new HMac(new Sha1Digest()); hmac.Init(new KeyParameter(HmacKeyBytes)); return(new HmacStream(hmac)); }
/// <summary> /// See <see cref="IRequest.GetUri()"/>. /// </summary> /// <returns>The <see cref="Uri"/>.</returns> public virtual Uri GetUri() { var scheme = this.IsSsl ? "https://" : "http://"; var queryString = string.Join("&", this.GetQueryStringParameters().Select(x => x.Value == null ? Uri.EscapeDataString(x.Key) : Uri.EscapeDataString(x.Key) + "=" + Uri.EscapeDataString(x.Value))); var uri = new Uri(scheme + this.BaseUrl + "?" + queryString); if (this.ClientId == null) { return(uri); } var url = uri.LocalPath + uri.Query + "&client=" + this.ClientId; var bytes = Encoding.UTF8.GetBytes(url); var privateKey = Convert.FromBase64String(this.Key.Replace("-", "+").Replace("_", "/")); var hmac = new HMac(new Sha1Digest()); hmac.Init(new KeyParameter(privateKey)); var signature = new byte[hmac.GetMacSize()]; hmac.BlockUpdate(bytes, 0, bytes.Length); hmac.DoFinal(signature, 0); var base64Signature = Convert.ToBase64String(signature).Replace("+", "-").Replace("/", "_"); return(new Uri(uri.Scheme + "://" + uri.Host + url + "&signature=" + base64Signature)); }
public Packet ChannelDecrypt(ICipherSetRemoteInfo channelInfo, Packet outer) { // We gotta have the primary components and something to decrypt if (outer.Body.Length < 25) { return(null); } var ci = (CS1ARemoteInfo)channelInfo; // Rip apart our packet byte[] token = outer.Body.Take(16).ToArray(); byte[] iv = outer.Body.Skip(16).Take(4).ToArray(); byte[] encryptedData = outer.Body.Skip(20).Take(outer.Body.Length - 24).ToArray(); byte[] dataMac = outer.Body.Skip(outer.Body.Length - 4).Take(4).ToArray(); // Make sure we're on the right channel if (!token.SequenceEqual(ci.Token)) { return(null); } // Validate us some hmac byte[] hmacKey = new byte[20]; Buffer.BlockCopy(ci.DecryptionKey, 0, hmacKey, 0, 16); Buffer.BlockCopy(iv, 0, hmacKey, 16, 4); var hmac = new HMac(new Sha256Digest()); hmac.Init(new KeyParameter(hmacKey)); hmac.BlockUpdate(encryptedData, 0, encryptedData.Length); byte[] mac = new byte[hmac.GetMacSize()]; hmac.DoFinal(mac, 0); var foldedMac = Helpers.Fold(mac, 3); if (!foldedMac.SequenceEqual(dataMac)) { // Get out of here with your bad data return(null); } // Everything seems ok. Get it decrypted byte[] aesIV = new byte[16]; Buffer.BlockCopy(iv, 0, aesIV, 0, 4); Array.Clear(aesIV, 4, 12); var cipher = new SicBlockCipher(new AesFastEngine()); var parameters = new ParametersWithIV(new KeyParameter(ci.DecryptionKey), aesIV); cipher.Init(false, parameters); var decryptedData = new byte[encryptedData.Length]; BufferedBlockCipher bufferCipher = new BufferedBlockCipher(cipher); var offset = bufferCipher.ProcessBytes(encryptedData, decryptedData, 0); bufferCipher.DoFinal(decryptedData, offset); // Build a packet and ship it off return(Packet.DecodePacket(decryptedData)); }
public EncryptedPacket EncryptData(byte[] original, RSAWithRSAParameterKey rsaParams, DigitalSignatureFuncs digitalSignature) { // Generate our session key var sessionKey = _aes.GenerateRandomNumber(32); // Create the encrypted packet and generate the IV var encryptedPacket = new EncryptedPacket { IV = _aes.GenerateRandomNumber(16) }; // Encrypt our data with AES encryptedPacket.EncryptedData = _aes.Encrypt(original, sessionKey, encryptedPacket.IV); // Encrypt the session key with RSA encryptedPacket.EncryptedSessionKey = rsaParams.EncryptData(sessionKey); // Calculate a HMAC encryptedPacket.HMAC = HMac.ComputeHMACSha256(encryptedPacket.EncryptedData, sessionKey); // Generate digital signature of packet to send encryptedPacket.Signature = digitalSignature.SignData(encryptedPacket.HMAC); return(encryptedPacket); }
public void Pack(byte[] plain, byte[] tag) { byte[] cipher = new byte[NtagHelpers.NFC3D_AMIIBO_SIZE]; // Generate keys var tagKeys = GenerateKey(this.tag, plain); var dataKeys = GenerateKey(this.data, plain); // Init OpenSSL HMAC context HMac hmacCtx = new HMac(new Sha256Digest()); // Generate tag HMAC hmacCtx.Init(new KeyParameter(tagKeys.hmacKey)); hmacCtx.BlockUpdate(plain, 0x1D4, 0x34); hmacCtx.DoFinal(cipher, HMAC_POS_TAG); // Generate data HMAC hmacCtx.Init(new KeyParameter(dataKeys.hmacKey)); hmacCtx.BlockUpdate(plain, 0x029, 0x18B); // Data hmacCtx.BlockUpdate(cipher, HMAC_POS_TAG, 0x20); // Tag HMAC hmacCtx.BlockUpdate(plain, 0x1D4, 0x34); // Tag hmacCtx.DoFinal(cipher, HMAC_POS_DATA); // Encrypt dataKeys.Cipher(plain, cipher, true); // Convert back to hardware NtagHelpers.InternalToTag(cipher, tag); Array.Copy(plain, 0x208, tag, 0x208, 0x014); }
/// <summary> /// Calculates the MacTag (to be used for key confirmation), as defined by /// <a href="http://csrc.nist.gov/publications/nistpubs/800-56A/SP800-56A_Revision1_Mar08-2007.pdf">NIST SP 800-56A Revision 1</a>, /// Section 8.2 Unilateral Key Confirmation for Key Agreement Schemes. /// /// MacTag = HMAC(MacKey, MacLen, MacData) /// MacKey = H(K || "JPAKE_KC") /// MacData = "KC_1_U" || participantId || partnerParticipantId || gx1 || gx2 || gx3 || gx4 /// /// Note that both participants use "KC_1_U" because the sender of the round 3 message /// is always the initiator for key confirmation. /// /// HMAC = {@link HMac} used with the given {@link Digest} /// H = The given {@link Digest} /// MacLen = length of MacTag /// </summary> public static BigInteger CalculateMacTag(string participantId, string partnerParticipantId, BigInteger gx1, BigInteger gx2, BigInteger gx3, BigInteger gx4, BigInteger keyingMaterial, IDigest digest) { byte[] macKey = CalculateMacKey(keyingMaterial, digest); HMac mac = new HMac(digest); mac.Init(new KeyParameter(macKey)); Arrays.Fill(macKey, (byte)0); /* * MacData = "KC_1_U" || participantId_Alice || participantId_Bob || gx1 || gx2 || gx3 || gx4. */ UpdateMac(mac, "KC_1_U"); UpdateMac(mac, participantId); UpdateMac(mac, partnerParticipantId); UpdateMac(mac, gx1); UpdateMac(mac, gx2); UpdateMac(mac, gx3); UpdateMac(mac, gx4); byte[] macOutput = MacUtilities.DoFinal(mac); return(new BigInteger(macOutput)); }
/// <summary> /// Generate digest. The digest can be reused. /// </summary> /// <param name="parameters">Parameters.</param> /// <returns></returns> /// <exception cref="Exception"/> public IMac GenerateDigest(ICipherParameters parameters) { IMac digest = new HMac(_hashAlgorithm.GenerateDigest()); digest.Init(parameters); return(digest); }
public bool Unpack(byte[] tag, byte[] plain) { byte[] internalBytes = NtagHelpers.GetInternalTag(tag); // Generate keys KeygenDerivedkeys dataKeys = GenerateKey(this.data, internalBytes); KeygenDerivedkeys tagKeys = GenerateKey(this.tag, internalBytes); // Decrypt dataKeys.Cipher(internalBytes, plain, false); // Init OpenSSL HMAC context HMac hmacCtx = new HMac(new Sha256Digest()); // Regenerate tag HMAC. Note: order matters, data HMAC depends on tag HMAC! hmacCtx.Init(new KeyParameter(tagKeys.hmacKey)); hmacCtx.BlockUpdate(plain, 0x1D4, 0x34); hmacCtx.DoFinal(plain, HMAC_POS_TAG); // Regenerate data HMAC hmacCtx.Init(new KeyParameter(dataKeys.hmacKey)); hmacCtx.BlockUpdate(plain, 0x029, 0x1DF); hmacCtx.DoFinal(plain, HMAC_POS_DATA); Array.Copy(tag, 0x208, plain, 0x208, 0x014); return (NativeHelpers.MemCmp(plain, internalBytes, HMAC_POS_DATA, 32) && NativeHelpers.MemCmp(plain, internalBytes, HMAC_POS_TAG, 32)); }
private void Init(byte[] key, byte[] macKey) { this.blockCipher = new CbcBlockCipher(new TBlockCipher()); this.cipher = new BufferedBlockCipher(this.blockCipher); this.mac = new HMac(new TDigest()); this.mac.Init(new KeyParameter(macKey)); }
public static byte[] ComputeHmac(byte[] data, byte[] key, int bitLength) { IDigest digest; if (bitLength == 256) { digest = new Sha256Digest(); } else if (bitLength == 512) { digest = new Sha512Digest(); } else { throw new ArgumentException("SHA digest restricted to one of [256, 512]"); } HMac hmac = new HMac(digest); hmac.Init(new KeyParameter(key)); byte[] buffer = new byte[hmac.GetMacSize()]; hmac.BlockUpdate(data, 0, data.Length); hmac.DoFinal(buffer, 0); return(buffer); }
/// <summary> /// Creates a new instance of the <see cref="Secio1Stream"/> class. /// </summary> /// <param name="stream"> /// The source/destination of SECIO packets. /// </param> /// <param name="cipherName"> /// The cipher for the <paramref name="stream"/>, such as AES-256 or AES-128. /// </param> /// <param name="hashName"> /// The hash for the <paramref name="stream"/>, such as SHA256. /// </param> /// <param name="localKey"> /// The keys used by the local endpoint. /// </param> /// <param name="remoteKey"> /// The keys used by the remote endpoint. /// </param> public Secio1Stream( Stream stream, string cipherName, string hashName, StretchedKey localKey, StretchedKey remoteKey) { this.stream = stream; inHmac = new HMac(DigestUtilities.GetDigest(hashName)); inHmac.Init(new KeyParameter(localKey.MacKey)); outHmac = new HMac(DigestUtilities.GetDigest(hashName)); outHmac.Init(new KeyParameter(remoteKey.MacKey)); if (cipherName == "AES-256" || cipherName == "AES-512") { decrypt = new CtrStreamCipher(new AesEngine()); var p = new ParametersWithIV(new KeyParameter(remoteKey.CipherKey), remoteKey.IV); decrypt.Init(false, p); encrypt = new CtrStreamCipher(new AesEngine()); p = new ParametersWithIV(new KeyParameter(localKey.CipherKey), localKey.IV); encrypt.Init(true, p); } else { throw new NotSupportedException($"Cipher '{cipherName}' is not supported."); } }
public static byte[] PBKDF2(byte[] password, byte[] salt, int iterCount, int cOctets, IDigest digest) { // PRF = HMAC- SHA (256, 384, 512) // P = passsword // S = salt // c = iteration count // dkLen = cbits in octets // l = CIEL(dkLen / hLen) // r = dkLen - (l - 1)*hLen // T_n = F ( P, S, c, n) (iterate n=1 to l) // F ( P, S, c, i) = U_1 ^ U_2 ^ ... ^ U_c // U_1 = PRF( P, S || INT (i)) // U_2 = PRF( P, U_1 ) // U_c = PRF( P, U_{c-1}) // INT = int32- big-ending HMac hmac = new HMac(digest); ICipherParameters k = new KeyParameter(password); hmac.Init(k); int hLen = hmac.GetMacSize(); int l = (cOctets + hLen - 1) / hLen; byte[] rgbStart = new byte[salt.Length + 4]; Array.Copy(salt, 0, rgbStart, 0, salt.Length); byte[] rgbOutput = new byte[l * hLen]; for (int i = 1; i <= l; i++) { byte[] rgbT = new byte[hLen]; byte[] rgbH = new byte[hLen]; hmac.Reset(); rgbStart[rgbStart.Length - 1] = (byte)i; hmac.BlockUpdate(rgbStart, 0, rgbStart.Length); hmac.DoFinal(rgbH, 0); Array.Copy(rgbH, rgbT, rgbH.Length); for (int j = 1; j < iterCount; j++) { hmac.Reset(); hmac.BlockUpdate(rgbH, 0, rgbH.Length); hmac.DoFinal(rgbH, 0); for (int k1 = 0; k1 < rgbH.Length; k1++) { rgbT[k1] ^= rgbH[k1]; } } Array.Copy(rgbT, hLen * (i - 1), rgbOutput, 0, rgbT.Length); } byte[] rgbOut = new Byte[cOctets]; Array.Copy(rgbOutput, rgbOut, cOctets); return(rgbOut); }
internal static byte[] SignatureMethod(string secret, string source, string signatureAlgorithm) { if (signatureAlgorithm == "ACS3-HMAC-SHA256") { byte[] signData; using (KeyedHashAlgorithm algorithm = CryptoConfig.CreateFromName("HMACSHA256") as KeyedHashAlgorithm) { algorithm.Key = Encoding.UTF8.GetBytes(secret); signData = algorithm.ComputeHash(Encoding.UTF8.GetBytes(source.ToSafeString().ToCharArray())); } return(signData); } else if (signatureAlgorithm == "ACS3-HMAC-SM3") { byte[] signData; HMac hmacInstance = new HMac(new SM3Digest()); hmacInstance.Init(new KeyParameter(Encoding.UTF8.GetBytes(secret))); signData = new byte[hmacInstance.GetMacSize()]; var raw = Encoding.UTF8.GetBytes(source); hmacInstance.BlockUpdate(raw, 0, raw.Length); hmacInstance.DoFinal(signData, 0); return(signData); } else if (signatureAlgorithm == "ACS3-RSA-SHA256") { return(RSASign(source, secret)); } return(null); }
public IBlockResult GetResult(int outputLength) { IMac md5Hmac = new HMac(md5Provider.CreateEngine(EngineUsage.GENERAL)); IMac sha1HMac = FipsShs.CreateHmac(FipsShs.Sha1HMac); return(new SimpleBlockResult(PRF_legacy(parameters, outputLength, md5Hmac, sha1HMac))); }
public HmacSha256(byte[] key) { var sharedKey = Ensure.Type <byte[]>(key, "HmacSha256 alg expectes key to be byte[] array."); _hmac = new HMac(new Sha256Digest()); _hmac.Init(new KeyParameter(sharedKey)); }
/// <summary> /// See <see cref="IRequest.GetUri()"/>. /// </summary> /// <returns>The <see cref="Uri"/>.</returns> public virtual Uri GetUri() { const string SCHEME = "https://"; var queryStringParameters = this.GetQueryStringParameters() .Select(x => x.Value == null ? Uri.EscapeDataString(x.Key) : Uri.EscapeDataString(x.Key) + "=" + Uri.EscapeDataString(x.Value)); var queryString = string.Join("&", queryStringParameters); var uri = new Uri($"{SCHEME}{this.BaseUrl}?{queryString}"); if (this.ClientId == null) { return(uri); } var url = $"{uri.LocalPath}{uri.Query}&client={this.ClientId}"; var bytes = Encoding.UTF8.GetBytes(url); var privateKey = Convert.FromBase64String(this.Key.Replace("-", "+").Replace("_", "/")); var hmac = new HMac(new Sha1Digest()); hmac.Init(new KeyParameter(privateKey)); var hmacSize = hmac.GetMacSize(); var signature = new byte[hmacSize]; hmac.BlockUpdate(bytes, 0, bytes.Length); hmac.DoFinal(signature, 0); var base64Signature = Convert.ToBase64String(signature).Replace("+", "-").Replace("/", "_"); return(new Uri($"{uri.Scheme}://{uri.Host}{url}&signature={base64Signature}")); }
public ITestResult Perform() { HMac hmac = new HMac(new RipeMD128Digest()); byte[] resBuf = new byte[hmac.GetMacSize()]; for (int i = 0; i < messages.Length; i++) { byte[] m = Encoding.ASCII.GetBytes(messages[i]); if (messages[i].StartsWith("0x")) { m = Hex.Decode(messages[i].Substring(2)); } hmac.Init(new KeyParameter(Hex.Decode(keys[i]))); hmac.BlockUpdate(m, 0, m.Length); hmac.DoFinal(resBuf, 0); if (!Arrays.AreEqual(resBuf, Hex.Decode(digests[i]))) { return(new SimpleTestResult(false, Name + ": Vector " + i + " failed")); } } return(new SimpleTestResult(true, Name + ": Okay")); }
private void ComputeNextBlock(HMac hash) { BigEndian.CopyBytes(m_blockNumber, m_saltWithBlock, m_saltWithBlock.Length - 4); byte[] final = new byte[hash.GetMacSize()]; byte[] tmp = new byte[hash.GetMacSize()]; //InitialPass: U1 = PRF(Password, Salt || INT_32_BE(i)) hash.Reset(); hash.BlockUpdate(m_saltWithBlock, 0, m_saltWithBlock.Length); hash.DoFinal(final, 0); final.CopyTo(tmp, 0); for (int iteration = 1; iteration < m_iterations; iteration++) { //U2 = PRF(Password, U1) //hash.Reset(); hash.BlockUpdate(tmp, 0, tmp.Length); hash.DoFinal(tmp, 0); for (int x = 0; x < tmp.Length; x++) { final[x] ^= tmp[x]; } } m_blockNumber++; foreach (var b in final) { m_results.Enqueue(b); } }
/// <summary> /// Gets the verifying stream. /// </summary> /// <returns></returns> public VerifyingStream GetVerifyingStream(KeyczarBase keyczar) { IDigest digest; if (Digest == DigestAlg.Sha256) { digest = new Sha256Digest(); } else if (Digest == DigestAlg.Sha384) { digest = new Sha384Digest(); } else if (Digest == DigestAlg.Sha512) { digest = new Sha512Digest(); } else { throw new InvalidKeyTypeException($"Unsupported digest type :{Digest}"); } var hmac = new HMac(digest); hmac.Init(new KeyParameter(HmacKeyBytes)); return(new HmacStream(hmac, HashLength)); }
private Byte[] StreamDecryption(Byte[] source, Byte[] data, HMac hmac, out Int32 sequenceNum) { // ciphered text consist of data and mac Byte[] decrypted; if (source.SequenceEqual(this.ClientDirection)) { var d = this.DataDecrypter.DecryptData(data, WriteKeySpec.Client); decrypted = new Byte[d.Length]; Array.Copy(d, decrypted, d.Length); var key = new KeyParameter(this.ClientHMacKey); hmac.Init(key); sequenceNum = this.DataDecrypter.ClientSeq; } else { var d = this.DataDecrypter.DecryptData(data, WriteKeySpec.Server); decrypted = new Byte[d.Length]; Array.Copy(d, decrypted, d.Length); var key = new KeyParameter(this.ServerHMacKey); hmac.Init(key); sequenceNum = this.DataDecrypter.ServerSeq; } return(decrypted); }
/// <summary> /// When overridden in a derived class, releases the unmanaged resources used by the <see cref="T:System.Security.Cryptography.DeriveBytes"/> class and optionally releases the managed resources. /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { if (disposing) { m_hash1 = null; } base.Dispose(disposing); }
/// <summary> ///A test for HMac`1 Constructor ///</summary> public void HMacConstructorTestHelper <T>() where T : HashAlgorithm, new() { byte[] key = null; // TODO: Initialize to an appropriate value HMac <T> target = new HMac <T>(key); Assert.Inconclusive("TODO: Implement code to verify target"); }
public byte[] HmacSha256(byte[] data, byte[] key) { var hmac = new HMac(new Sha256Digest()); hmac.Init(new KeyParameter(key)); var result = new byte[hmac.GetMacSize()]; hmac.BlockUpdate(data, 0, data.Length); hmac.DoFinal(result, 0); return result; }
/// <summary> ///A test for Initialize ///</summary> public void InitializeTestHelper <T>() where T : HashAlgorithm, new() { byte[] key = null; // TODO: Initialize to an appropriate value HMac <T> target = new HMac <T>(key); // TODO: Initialize to an appropriate value target.Initialize(); Assert.Inconclusive("A method that does not return a value cannot be verified."); }
/// <summary> /// Create a new PBKDF2 object /// </summary> public PBKDF2(byte[] password, byte[] salt, int iterations) { m_password = password; m_salt = salt; m_iterations = iterations; m_mac = new HMac(new Sha1Digest()); m_hlen = m_mac.GetMacSize(); }
private static SecureRandom GetDRBG(byte[] message) { Sha256Digest sha256 = new Sha256Digest(); HMac hMac = new HMac(sha256); return(new SP800SecureRandomBuilder() .SetEntropyBitsRequired(ENT_BITS) .SetPersonalizationString(ALG) .BuildHMac(hMac, message, true)); }
public static SimulatedTlsSrpIdentityManager GetRfc5054Default(Srp6GroupParameters group, byte[] seedKey) { Srp6VerifierGenerator srp6VerifierGenerator = new Srp6VerifierGenerator(); srp6VerifierGenerator.Init(group, TlsUtilities.CreateHash(2)); HMac hMac = new HMac(TlsUtilities.CreateHash(2)); hMac.Init(new KeyParameter(seedKey)); return(new SimulatedTlsSrpIdentityManager(group, srp6VerifierGenerator, hMac)); }
/** * Create a {@link SimulatedTlsSRPIdentityManager} that implements the algorithm from RFC 5054 2.5.1.3 * * @param group the {@link SRP6GroupParameters} defining the group that SRP is operating in * @param seedKey the secret "seed key" referred to in RFC 5054 2.5.1.3 * @return an instance of {@link SimulatedTlsSRPIdentityManager} */ public static SimulatedTlsSrpIdentityManager GetRfc5054Default(Srp6GroupParameters group, byte[] seedKey) { Srp6VerifierGenerator verifierGenerator = new Srp6VerifierGenerator(); verifierGenerator.Init(group, TlsUtilities.CreateHash(HashAlgorithm.sha1)); HMac mac = new HMac(TlsUtilities.CreateHash(HashAlgorithm.sha1)); mac.Init(new KeyParameter(seedKey)); return new SimulatedTlsSrpIdentityManager(group, verifierGenerator, mac); }
public static string GenerateHMACBC(byte[] data, byte[] EK) { var hmac = new HMac(new Sha256Digest()); hmac.Init(new KeyParameter(EK)); byte[] hashMessage = new byte[hmac.GetMacSize()]; hmac.BlockUpdate(data, 0, data.Length); hmac.DoFinal(hashMessage, 0); return(Convert.ToBase64String(hashMessage)); }
internal static byte[] ComputeSHA256HMac(byte[] msg, byte[] password) { var hmac = new HMac(new Sha256Digest()); hmac.Init(new KeyParameter(password)); byte[] result = new byte[hmac.GetMacSize()]; hmac.BlockUpdate(msg, 0, msg.Length); hmac.DoFinal(result, 0); return(result); }