public override byte[] CalculateMic(string appKey) { IMac mac = MacUtilities.GetMac("AESCMAC"); KeyParameter key = new KeyParameter(StringToByteArray(appKey)); mac.Init(key); byte[] rfu = new byte[1]; rfu[0] = 0x0; var algoinput = mhdr.Concat(appNonce).Concat(netID).Concat(devAddr).Concat(rfu).Concat(rxDelay).ToArray(); if (cfList != null) { algoinput = algoinput.Concat(cfList).ToArray(); } byte[] msgLength = BitConverter.GetBytes(algoinput.Length); byte direction = 0x01; byte[] aBlock = { 0x49, 0x00, 0x00, 0x00, 0x00, direction, (byte)(devAddr[3]), (byte)(devAddr[2]), (byte)(devAddr[1]), (byte)(devAddr[0]), (byte)(fcnt[0]), (byte)(fcnt[1]), 0x00, 0x00, 0x00, msgLength[0] }; algoinput = aBlock.Concat(algoinput).ToArray(); byte[] result = new byte[16]; mac.BlockUpdate(algoinput, 0, algoinput.Length); result = MacUtilities.DoFinal(mac); mic = result.Take(4).ToArray(); return(mic); }
private void DoTestHMac(string hmacName, int defKeySize, byte[] output) { KeyParameter key = new KeyParameter(keyBytes); //, hmacName); IMac mac = MacUtilities.GetMac(hmacName); mac.Init(key); mac.Reset(); mac.BlockUpdate(message, 0, message.Length); byte[] outBytes = MacUtilities.DoFinal(mac); if (!AreEqual(outBytes, output)) { Fail("Failed - expected " + Hex.ToHexString(output) + " got " + Hex.ToHexString(outBytes)); } CipherKeyGenerator kGen = GeneratorUtilities.GetKeyGenerator(hmacName); key = new KeyParameter(kGen.GenerateKey()); mac.Init(key); // hmacName mac.BlockUpdate(message, 0, message.Length); outBytes = MacUtilities.DoFinal(mac); IsTrue("default key wrong length", key.GetKey().Length == (defKeySize / 8)); }
private byte[] PerformMic(string appKey) { IMac mac = MacUtilities.GetMac("AESCMAC"); KeyParameter key = new KeyParameter(ConversionHelper.StringToByteArray(appKey)); mac.Init(key); var algoInputBytes = new byte[19]; var algoInput = new Memory <byte>(algoInputBytes); var offset = 0; this.Mhdr.CopyTo(algoInput); offset += this.Mhdr.Length; this.AppEUI.CopyTo(algoInput.Slice(offset)); offset += this.AppEUI.Length; this.DevEUI.CopyTo(algoInput.Slice(offset)); offset += this.DevEUI.Length; this.DevNonce.CopyTo(algoInput.Slice(offset)); mac.BlockUpdate(algoInputBytes, 0, algoInputBytes.Length); var result = MacUtilities.DoFinal(mac); return(result.Take(4).ToArray()); }
/// <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)); }
protected override void Dispose(bool disposing) { try { if (!disposing) { return; } macStream.Dispose(); // TODO Parent context(s) should really be be closed explicitly eiGen.Close(); // [TODO] auth attributes go here byte[] macOctets = MacUtilities.DoFinal(mac); authGen.AddObject(new DerOctetString(macOctets)); // [TODO] unauth attributes go here authGen.Close(); cGen.Close(); } finally { base.Dispose(disposing); } }
private void DoTestHMac(string hmacName, byte[] output) { KeyParameter key = new KeyParameter(keyBytes); //, hmacName); IMac mac = MacUtilities.GetMac(hmacName); mac.Init(key); mac.Reset(); mac.BlockUpdate(message, 0, message.Length); byte[] outBytes = MacUtilities.DoFinal(mac); if (!AreEqual(outBytes, output)) { Fail("Failed - expected " + Hex.ToHexString(output) + " got " + Hex.ToHexString(outBytes)); } // no key generator for the old algorithms if (hmacName.StartsWith("Old")) { return; } CipherKeyGenerator kGen = GeneratorUtilities.GetKeyGenerator(hmacName); key = new KeyParameter(kGen.GenerateKey()); mac.Init(key); // hmacName mac.BlockUpdate(message, 0, message.Length); outBytes = MacUtilities.DoFinal(mac); }
protected virtual byte[] CalculateRecordMac(KeyParameter macKey, byte[] additionalData, byte[] buf, int off, int len) { IMac mac = new Poly1305(); mac.Init(macKey); this.UpdateRecordMac(mac, additionalData, 0, additionalData.Length); this.UpdateRecordMac(mac, buf, off, len); return(MacUtilities.DoFinal(mac)); }
internal static byte[] CalculatePbeMac(DerObjectIdentifier oid, byte[] salt, int itCount, char[] password, bool wrongPkcs12Zero, byte[] data) { Asn1Encodable pbeParameters = PbeUtilities.GenerateAlgorithmParameters(oid, salt, itCount); ICipherParameters parameters = PbeUtilities.GenerateCipherParameters(oid, password, wrongPkcs12Zero, pbeParameters); IMac mac = (IMac)PbeUtilities.CreateEngine(oid); mac.Init(parameters); return(MacUtilities.DoFinal(mac, data)); }
/** * Return the MAC calculated for the content stream. Note: this call is only meaningful once all * the content has been read. * * @return byte array containing the mac. */ public byte[] GetMac() { if (macStream != null && resultMac == null) { resultMac = MacUtilities.DoFinal(macStream.ReadMac()); } return(Arrays.Clone(resultMac)); }
private CmsAuthenticatedData Generate(CmsProcessable content, string macOid, CipherKeyGenerator keyGen) { KeyParameter keyParameter; AlgorithmIdentifier algorithmIdentifier; Asn1OctetString content2; Asn1OctetString mac2; try { byte[] array = keyGen.GenerateKey(); keyParameter = ParameterUtilities.CreateKeyParameter(macOid, array); Asn1Encodable asn1Params = GenerateAsn1Parameters(macOid, array); algorithmIdentifier = GetAlgorithmIdentifier(macOid, keyParameter, asn1Params, out ICipherParameters _); IMac mac = MacUtilities.GetMac(macOid); mac.Init(keyParameter); MemoryStream memoryStream = new MemoryStream(); Stream stream = new TeeOutputStream(memoryStream, new MacOutputStream(mac)); content.Write(stream); Platform.Dispose(stream); content2 = new BerOctetString(memoryStream.ToArray()); byte[] str = MacUtilities.DoFinal(mac); mac2 = new DerOctetString(str); } catch (SecurityUtilityException e) { throw new CmsException("couldn't create cipher.", e); } catch (InvalidKeyException e2) { throw new CmsException("key invalid in message.", e2); } catch (IOException e3) { throw new CmsException("exception decoding algorithm parameters.", e3); } Asn1EncodableVector asn1EncodableVector = new Asn1EncodableVector(); foreach (RecipientInfoGenerator recipientInfoGenerator in recipientInfoGenerators) { try { asn1EncodableVector.Add(recipientInfoGenerator.Generate(keyParameter, rand)); } catch (InvalidKeyException e4) { throw new CmsException("key inappropriate for algorithm.", e4); } catch (GeneralSecurityException e5) { throw new CmsException("error making encrypted content.", e5); } } ContentInfo encapsulatedContent = new ContentInfo(CmsObjectIdentifiers.Data, content2); ContentInfo contentInfo = new ContentInfo(CmsObjectIdentifiers.AuthenticatedData, new AuthenticatedData(null, new DerSet(asn1EncodableVector), algorithmIdentifier, null, encapsulatedContent, null, mac2, null)); return(new CmsAuthenticatedData(contentInfo)); }
public override void Close() { this.macStream.Close(); this.eiGen.Close(); byte[] str = MacUtilities.DoFinal(this.mac); this.authGen.AddObject(new DerOctetString(str)); this.authGen.Close(); this.cGen.Close(); }
public override void Close() { Platform.Dispose(macStream); eiGen.Close(); byte[] str = MacUtilities.DoFinal(mac); authGen.AddObject(new DerOctetString(str)); authGen.Close(); cGen.Close(); base.Close(); }
internal static byte[] CalculatePbeMac(DerObjectIdentifier oid, byte[] salt, int itCount, char[] password, bool wrongPkcs12Zero, byte[] data) { Asn1Encodable asn1Params = PbeUtilities.GenerateAlgorithmParameters(oid, salt, itCount); ICipherParameters cipherParams = PbeUtilities.GenerateCipherParameters(oid, password, wrongPkcs12Zero, asn1Params); var mac = (IMac)PbeUtilities.CreateEngine(oid); mac.Init(cipherParams); mac.BlockUpdate(data, 0, data.Length); return(MacUtilities.DoFinal(mac)); }
public byte[] GetMac() { if (this.resultMac == null) { object cryptoObject = this.secureReadable.CryptoObject; if (cryptoObject is IMac) { this.resultMac = MacUtilities.DoFinal((IMac)cryptoObject); } } return(Arrays.Clone(this.resultMac)); }
public override void Close() { macStream.Close(); eiGen.Close(); // [TODO] auth attributes go here byte[] macOctets = MacUtilities.DoFinal(macStream.WriteMac()); authGen.AddObject(new DerOctetString(macOctets)); // [TODO] unauth attributes go here authGen.Close(); cGen.Close(); }
/// <summary> /// Calculate the signature of <paramref name="data"/> /// </summary> /// <param name="data">The data to sign</param> /// <param name="consumerSecret">The consumer secret</param> /// <param name="tokenSecret">The token secret</param> /// <returns>The signature</returns> public string CalculateSignature(byte[] data, string consumerSecret, string tokenSecret) { var key = string.Format("{0}&{1}", consumerSecret, tokenSecret); var keyData = _encoding.GetBytes(key); var digest = new Sha1Digest(); var crypto = new HMac(digest); crypto.Init(new KeyParameter(keyData)); crypto.BlockUpdate(data, 0, data.Length); var hash = MacUtilities.DoFinal(crypto); return(Convert.ToBase64String(hash)); }
private static byte[] GenerateHkdf(byte[] salt, byte[] ikm, byte[] info, int len) { IMac prkGen = MacUtilities.GetMac("HmacSHA256"); prkGen.Init(new KeyParameter(MacUtilities.CalculateMac("HmacSHA256", new KeyParameter(salt), ikm))); prkGen.BlockUpdate(info, 0, info.Length); prkGen.Update(1); byte[] result = MacUtilities.DoFinal(prkGen); if (result.Length > len) { Array.Resize(ref result, len); } return(result); }
public static byte[] GenerateHKDF(byte[] salt, byte[] ikm, byte[] info, int len) { IMac PRKGen = MacUtilities.GetMac("HmacSHA256"); PRKGen.Init(new KeyParameter(MacUtilities.CalculateMac("HmacSHA256", new KeyParameter(salt), ikm))); PRKGen.BlockUpdate(info, 0, info.Length); PRKGen.Update((byte)1); byte[] Result = MacUtilities.DoFinal(PRKGen); if (Result.Length > len) { Array.Resize(ref Result, len); } return(Result); }
/// <summary> /// 哈希计算 /// </summary> /// <param name="data">输入字符串</param> /// <param name="key">密钥KEY</param> /// <param name="digest"></param> /// <returns>哈希值</returns> public static byte[] Compute(string data, byte[] key, IDigest digest) { if (string.IsNullOrEmpty(data)) { throw new ArgumentNullException(nameof(data)); } var keyParameter = new Org.BouncyCastle.Crypto.Parameters.KeyParameter(key); var input = Encoding.UTF8.GetBytes(data); IMac mac = new Org.BouncyCastle.Crypto.Macs.HMac(digest); mac.Init(keyParameter); mac.BlockUpdate(input, 0, input.Length); return(MacUtilities.DoFinal(mac)); }
/// <summary> /// A Method to calculate the Mic of the message /// </summary> /// <returns> the Mic bytes</returns> public byte[] CalculateMic(string appKey, byte[] algoinput) { IMac mac = MacUtilities.GetMac("AESCMAC"); KeyParameter key = new KeyParameter(ConversionHelper.StringToByteArray(appKey)); mac.Init(key); byte[] rfu = new byte[1]; rfu[0] = 0x0; byte[] msgLength = BitConverter.GetBytes(algoinput.Length); byte[] result = new byte[16]; mac.BlockUpdate(algoinput, 0, algoinput.Length); result = MacUtilities.DoFinal(mac); this.Mic = result.Take(4).ToArray(); return(this.Mic.ToArray()); }
/// <summary> /// Method to check if the mic is valid /// </summary> /// <param name="nwskey">the network security key</param> /// <returns></returns> public bool CheckMic(string nwskey) { IMac mac = MacUtilities.GetMac("AESCMAC"); KeyParameter key = new KeyParameter(StringToByteArray(nwskey)); mac.Init(key); byte[] block = { 0x49, 0x00, 0x00, 0x00, 0x00, (byte)this.payloadMessage.direction, (byte)(this.payloadMessage.devAddr[3]), (byte)(payloadMessage.devAddr[2]), (byte)(payloadMessage.devAddr[1]), (byte)(payloadMessage.devAddr[0]), this.payloadMessage.fcnt[0], this.payloadMessage.fcnt[1], 0x00, 0x00, 0x00, (byte)(this.payloadMessage.rawMessage.Length - 4) }; var algoinput = block.Concat(this.payloadMessage.rawMessage.Take(this.payloadMessage.rawMessage.Length - 4)).ToArray(); byte[] result = new byte[16]; mac.BlockUpdate(algoinput, 0, algoinput.Length); result = MacUtilities.DoFinal(mac); return(this.payloadMessage.mic.SequenceEqual(result.Take(4).ToArray())); }
/** * Calculate the mac for some given data. * <p/> * TlsMac will keep track of the sequence number internally. * * @param type The message type of the message. * @param message A byte-buffer containing the message. * @param offset The number of bytes to skip, before the message starts. * @param len The length of the message. * @return A new byte-buffer containing the mac value. */ public virtual byte[] CalculateMac( ContentType type, byte[] message, int offset, int len) { byte[] macHeader = new byte[13]; TlsUtilities.WriteUint64(seqNo++, macHeader, 0); TlsUtilities.WriteUint8((byte)type, macHeader, 8); TlsUtilities.WriteVersion(macHeader, 9); TlsUtilities.WriteUint16(len, macHeader, 11); mac.BlockUpdate(macHeader, 0, macHeader.Length); mac.BlockUpdate(message, offset, len); return(MacUtilities.DoFinal(mac)); }
public override void Close() { macStream.Close(); // TODO Parent context(s) should really be be closed explicitly eiGen.Close(); // [TODO] auth attributes go here byte[] macOctets = MacUtilities.DoFinal(mac); authGen.AddObject(new DerOctetString(macOctets)); // [TODO] unauth attributes go here authGen.Close(); cGen.Close(); }
public void SetMic(string nwskey) { rawMessage = this.ToMessage(); IMac mac = MacUtilities.GetMac("AESCMAC"); KeyParameter key = new KeyParameter(StringToByteArray(nwskey)); mac.Init(key); byte[] block = { 0x49, 0x00, 0x00, 0x00, 0x00, (byte)direction, (byte)(devAddr[3]), (byte)(devAddr[2]), (byte)(devAddr[1]), (byte)(devAddr[0]), fcnt[0], fcnt[1], 0x00, 0x00, 0x00, (byte)(rawMessage.Length) }; var algoinput = block.Concat(rawMessage.Take(rawMessage.Length)).ToArray(); byte[] result = new byte[16]; mac.BlockUpdate(algoinput, 0, algoinput.Length); result = MacUtilities.DoFinal(mac); mic = result.Take(4).ToArray(); }
public virtual byte[] CalculateMac(long seqNo, byte type, byte[] message, int offset, int length) { ProtocolVersion serverVersion = context.ServerVersion; bool isSsl = serverVersion.IsSsl; byte[] array = new byte[isSsl ? 11 : 13]; TlsUtilities.WriteUint64(seqNo, array, 0); TlsUtilities.WriteUint8(type, array, 8); if (!isSsl) { TlsUtilities.WriteVersion(serverVersion, array, 9); } TlsUtilities.WriteUint16(length, array, array.Length - 2); mac.BlockUpdate(array, 0, array.Length); mac.BlockUpdate(message, offset, length); return(Truncate(MacUtilities.DoFinal(mac))); }
private byte[] PerformMic(string appKey) { IMac mac = MacUtilities.GetMac("AESCMAC"); KeyParameter key = new KeyParameter(ConversionHelper.StringToByteArray(appKey)); mac.Init(key); var algoinput = Mhdr.ToArray().Concat(AppEUI.ToArray()).Concat(DevEUI.ToArray()).Concat(DevNonce.ToArray()).ToArray(); byte[] result = new byte[19]; mac.BlockUpdate(algoinput, 0, algoinput.Length); result = MacUtilities.DoFinal(mac); var resStr = BitConverter.ToString(result); return(result.Take(4).ToArray()); }
public static BigInteger CalculateMacTag(string participantId, string partnerParticipantId, BigInteger gx1, BigInteger gx2, BigInteger gx3, BigInteger gx4, BigInteger keyingMaterial, IDigest digest) { byte[] array = CalculateMacKey(keyingMaterial, digest); HMac hMac = new HMac(digest); hMac.Init(new KeyParameter(array)); Arrays.Fill(array, 0); UpdateMac(hMac, "KC_1_U"); UpdateMac(hMac, participantId); UpdateMac(hMac, partnerParticipantId); UpdateMac(hMac, gx1); UpdateMac(hMac, gx2); UpdateMac(hMac, gx3); UpdateMac(hMac, gx4); byte[] bytes = MacUtilities.DoFinal(hMac); return(new BigInteger(bytes)); }
public override void Close() { BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(macStream); // TODO Parent context(s) should really be be closed explicitly eiGen.Close(); // [TODO] auth attributes go here byte[] macOctets = MacUtilities.DoFinal(mac); authGen.AddObject(new DerOctetString(macOctets)); // [TODO] unauth attributes go here authGen.Close(); cGen.Close(); base.Close(); }
public virtual byte[] CalculateMac(long seqNo, byte type, byte[] message, int offset, int length) { ProtocolVersion serverVersion = this.context.ServerVersion; bool isSsl = serverVersion.IsSsl; byte[] buf = new byte[!isSsl ? 13 : 11]; TlsUtilities.WriteUint64(seqNo, buf, 0); TlsUtilities.WriteUint8(type, buf, 8); if (!isSsl) { TlsUtilities.WriteVersion(serverVersion, buf, 9); } TlsUtilities.WriteUint16(length, buf, buf.Length - 2); this.mac.BlockUpdate(buf, 0, buf.Length); this.mac.BlockUpdate(message, offset, length); return(this.Truncate(MacUtilities.DoFinal(this.mac))); }
/// <summary> /// Method to check if the mic is valid /// </summary> /// <param name="nwskey">the network security key</param> /// <returns>if the Mic is valid or not</returns> public override bool CheckMic(string nwskey) { IMac mac = MacUtilities.GetMac("AESCMAC"); KeyParameter key = new KeyParameter(ConversionHelper.StringToByteArray(nwskey)); mac.Init(key); byte[] block = { 0x49, 0x00, 0x00, 0x00, 0x00, (byte)Direction, (byte)DevAddr.Span[3], (byte)DevAddr.Span[2], (byte)DevAddr.Span[1], (byte)DevAddr.Span[0], Fcnt.Span[0], Fcnt.Span[1], 0x00, 0x00, 0x00, (byte)(RawMessage.Length - 4) }; var algoinput = block.Concat(RawMessage.Take(RawMessage.Length - 4)).ToArray(); byte[] result = new byte[16]; mac.BlockUpdate(algoinput, 0, algoinput.Length); result = MacUtilities.DoFinal(mac); return(Mic.ToArray().SequenceEqual(result.Take(4).ToArray())); }