public static byte[] DoFinal( IMac mac) { byte[] b = new byte[mac.GetMacSize()]; mac.DoFinal(b, 0); return b; }
public Scp03CMacSession(IMac cmac, Session session, KeyParameter key_mac, KeyParameter key_rmac, byte[] mac_chaining) { this.cmac = cmac; this.session = session; this.key_mac = key_mac; this.key_rmac = key_rmac; this.mac_chaining = mac_chaining; }
/** * set up for use with stream mode, where the key derivation function * is used to provide a stream of bytes to xor with the message. * * @param agree the key agreement used as the basis for the encryption * @param kdf the key derivation function used for byte generation * @param mac the message authentication code generator for the message */ public IesEngine(IBasicAgreement agree, IDerivationFunction kdf, IMac mac) { _agree = agree; _kdf = kdf; _mac = mac; _macBuf = new byte[mac.GetMacSize()]; // this.cipher = null; }
/** * set up for use in conjunction with a block cipher to handle the * message. * * @param agree the key agreement used as the basis for the encryption * @param kdf the key derivation function used for byte generation * @param mac the message authentication code generator for the message * @param cipher the cipher to used for encrypting the message */ public IesEngine(IBasicAgreement agree, IDerivationFunction kdf, IMac mac, BufferedBlockCipher cipher) { _agree = agree; _kdf = kdf; _mac = mac; _macBuf = new byte[mac.GetMacSize()]; _cipher = cipher; }
/// <summary> /// Initialize this class using the message digests enumeration name /// </summary> /// /// <param name="DigestType">The message digest enumeration name</param> public HKDF(Digests DigestType) { IDigest digest = Helper.DigestFromName.GetInstance(DigestType); m_disposeEngine = true; m_kdfMac = new HMAC(digest); m_hashSize = digest.DigestSize; }
public static byte[] CalculateMac(string algorithm, ICipherParameters cp, byte[] input) { IMac mac = GetMac(algorithm); mac.Init(cp); mac.BlockUpdate(input, 0, input.Length); return(DoFinal(mac)); }
public static void BlockUpdate(this IMac mac, uint value) { var bytes = ArrayPool <byte> .Shared.Rent(4); BinaryPrimitives.WriteUInt32BigEndian(bytes, value); mac.BlockUpdate(bytes, 0, 4); ArrayPool <byte> .Shared.Return(bytes); }
public static void BlockUpdate(this IMac mac, ReadOnlySpan <byte> input) { var bytes = ArrayPool <byte> .Shared.Rent(input.Length); input.CopyTo(bytes); mac.BlockUpdate(bytes, 0, input.Length); ArrayPool <byte> .Shared.Return(bytes); }
public CmsAuthenticatedDataOutputStream(Stream macStream, IMac mac, BerSequenceGenerator cGen, BerSequenceGenerator authGen, BerSequenceGenerator eiGen) { this.macStream = macStream; this.mac = mac; this.cGen = cGen; this.authGen = authGen; this.eiGen = eiGen; }
public virtual IStreamCalculator CreateCalculator() { IMac mac = MacUtilities.GetMac(parameters.Mac.Algorithm); mac.Init(new KeyParameter(key)); return(new PKMacStreamCalculator(mac)); }
internal HMacDRBGProvider(FipsDigestAlgorithm algorithm, byte[] nonce, byte[] personalizationString, int securityStrength, byte[] primaryAdditionalInput) { CryptoStatus.IsReady(); this.hMac = FipsShs.CreateHmac(algorithm); this.nonce = nonce; this.personalizationString = personalizationString; this.securityStrength = securityStrength; this.primaryAdditionalInput = primaryAdditionalInput; }
/** * set up for use with stream mode, where the key derivation function * is used to provide a stream of bytes to xor with the message. * @param agree the key agreement used as the basis for the encryption * @param kdf the key derivation function used for byte generation * @param mac the message authentication code generator for the message * @param hash hash ing function * @param cipher the actual cipher */ public EthereumIesEngine( IMac mac, IDigest hash, BufferedBlockCipher cipher) { Mac = mac; _hash = hash; Cipher = cipher; }
public EaxBlockCipher(IBlockCipher cipher) { this.blockSize = cipher.GetBlockSize(); this.mac = new CMac(cipher); this.macBlock = new byte[this.blockSize]; this.associatedTextMac = new byte[this.mac.GetMacSize()]; this.nonceMac = new byte[this.mac.GetMacSize()]; this.cipher = new SicBlockCipher(cipher); }
private void testSingleByte(IMac mac, TestCase testCase) { byte[] ad = testCase.getAd(); for (int i = 0; i < ad.Length; i++) { mac.Update(ad[i]); } checkMac(mac, testCase); }
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)); }
/// <summary> /// Generate a new digest and compute data hash. /// </summary> /// <param name="parameters">Parameters.</param> /// <param name="data">Data buffer bytes.</param> /// <param name="offset">The starting offset to read.</param> /// <param name="length">The length to read.</param> /// <returns></returns> public byte[] ComputeHash(ICipherParameters parameters, byte[] data, int offset, int length) { IMac digest = GenerateDigest(parameters); digest.BlockUpdate(data, offset, length); byte[] hash = new byte[this.HashSize]; digest.DoFinal(hash, 0); return(hash); }
public static void MacTest(IMac mac, ReadOnlySpan <byte> message, string expected) { mac.Update(message); Span <byte> digest = new byte[mac.Length]; mac.GetMac(digest); Assert.AreEqual(expected, digest.ToHex()); }
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 MacStream( Stream stream, IMac readMac, IMac writeMac) { this.stream = stream; this.inMac = readMac; this.outMac = writeMac; }
private void Test(IMac mac) { Span <byte> o = stackalloc byte[16]; mac.Update(_randombytes.Span); mac.GetMac(o); mac.Dispose(); }
/// <summary> /// Initialize this class class using an Hmac instance /// </summary> /// /// <param name="Hmac">The Hmac digest instance</param> /// /// <exception cref="CryptoGeneratorException">Thrown if a null Hmac is used</exception> public HKDF(IMac Hmac) { if (Hmac == null) { throw new CryptoGeneratorException("HKDF:Ctor", "Hmac can not be null!", new ArgumentNullException()); } m_kdfMac = Hmac; m_hashSize = Hmac.MacSize; }
protected virtual void UpdateRecordMacText(IMac mac, byte[] buf, int off, int len) { mac.BlockUpdate(buf, off, len); int num = len % 0x10; if (num != 0) { mac.BlockUpdate(Zeroes, 0, 0x10 - num); } }
/// <summary> /// Computes a derived key. /// </summary> /// <param name="hmacAlgorithm"> /// </param> /// <param name="salt"> /// The salt. /// A unique salt means a unique derived key, even if the original key is identical. /// </param> /// <param name="iterations">The number of iterations to apply.</param> /// <param name="derivedKeyLength">The desired length of the derived key.</param> /// <returns>The derived key.</returns> #if USEBC || WINDOWS_UWP || NETCORE public static byte[] ComputeDerivedKey(IMac hmacAlgorithm, byte[] salt, int iterations, int derivedKeyLength) { NBitcoin.Crypto.Internal.Check.Range("derivedKeyLength", derivedKeyLength, 0, int.MaxValue); using (Pbkdf2 kdf = new Pbkdf2(hmacAlgorithm, salt, iterations)) { return(kdf.Read(derivedKeyLength)); } }
private void checkMac(IMac mac, TestCase testCase) { byte[] generatedMac = new byte[mac.GetMacSize()]; mac.DoFinal(generatedMac, 0); if (!AreEqual(testCase.getTag(), generatedMac)) { Fail("Failed " + testCase.getName() + " - expected " + Hex.ToHexString(testCase.getTag()) + " got " + Hex.ToHexString(generatedMac)); } }
public HMACControl(IMac mac) { InitializeComponent(); Y = X = 0; _mac = mac; DataContext = (IAlgorithmElement)this; }
/** * Constructor that accepts an instance of a block cipher engine. * * @param cipher the engine to use */ public EaxBlockCipher( IBlockCipher cipher) { blockSize = cipher.GetBlockSize(); mac = new CMac(cipher); macBlock = new byte[blockSize]; associatedTextMac = new byte[mac.GetMacSize()]; nonceMac = new byte[mac.GetMacSize()]; this.cipher = new SicBlockCipher(cipher); }
public override IAlgorithmElement CreateAlgorithmElement() { IMac hmac = HMACFactory.CreateDigets(Name); switch (hmac.AlgorithmName) { default: return(new HMACControl(hmac)); } }
/** * set up for use with stream mode, where the key derivation function * is used to provide a stream of bytes to xor with the message. * * @param agree the key agreement used as the basis for the encryption * @param kdf the key derivation function used for byte generation * @param mac the message authentication code generator for the message */ public CustomIesEngine( IBasicAgreement agree, IDerivationFunction kdf, IMac mac) { Agree = agree; Kdf = kdf; Mac = mac; Cipher = null; }
private static byte[] PRF(TlsKdfWithPrfParameters parameters, int size) { byte[] label = Strings.ToByteArray(parameters.Label); byte[] labelSeed = Arrays.Concatenate(label, parameters.SeedMaterial); IMac prfMac = FipsShs.CreateHmac(parameters.Prf); byte[] buf = new byte[size]; hmac_hash(prfMac, parameters.Secret, labelSeed, buf); return(buf); }
/** * set up for use in conjunction with a block cipher to handle the * message. * * @param agree the key agreement used as the basis for the encryption * @param kdf the key derivation function used for byte generation * @param mac the message authentication code generator for the message * @param cipher the cipher to used for encrypting the message */ public CustomIesEngine( IBasicAgreement agree, IDerivationFunction kdf, IMac mac, BufferedBlockCipher cipher) { Agree = agree; Kdf = kdf; Mac = mac; Cipher = cipher; }
protected static void UpdateRecordMacText(IMac mac, byte[] buf, int off, int len) { mac.BlockUpdate(buf, off, len); int partial = len % 16; if (partial != 0) { mac.BlockUpdate(Zeroes, 0, 16 - partial); } }
public override IMac CreateEngine(EngineUsage usage) { IMac mac = provider.CreateEngine(usage); if (key != null) { mac.Init(new KeyParameter(key.GetKeyBytes())); } return(mac); }
/** * Generate a new instance of an TlsMac. * * @param context the TLS client context * @param digest The digest to use. * @param key A byte-array where the key for this MAC is located. * @param keyOff The number of bytes to skip, before the key starts in the buffer. * @param keyLen The length of the key. */ public TlsMac(TlsContext context, IDigest digest, byte[] key, int keyOff, int keyLen) { this.context = context; KeyParameter keyParameter = new KeyParameter(key, keyOff, keyLen); this.secret = Arrays.Clone(keyParameter.GetKey()); // TODO This should check the actual algorithm, not rely on the engine type if (digest is LongDigest) { this.digestBlockSize = 128; this.digestOverhead = 16; } else { this.digestBlockSize = 64; this.digestOverhead = 8; } if (TlsUtilities.IsSsl(context)) { this.mac = new Ssl3Mac(digest); // TODO This should check the actual algorithm, not assume based on the digest size if (digest.GetDigestSize() == 20) { /* * NOTE: When SHA-1 is used with the SSL 3.0 MAC, the secret + input pad is not * digest block-aligned. */ this.digestOverhead = 4; } } else { this.mac = new HMac(digest); // NOTE: The input pad for HMAC is always a full digest block } this.mac.Init(keyParameter); this.macLength = mac.GetMacSize(); if (context.SecurityParameters.truncatedHMac) { this.macLength = System.Math.Min(this.macLength, 10); } }
public NetworkLayer(IMac mac) { _mac = mac; _mgmt = new NetworkMgmt(this); _route = new Routing(this, mac, this); #if USE_FRAG int mtu, head, tail; _route.GetMtuSize(out mtu, out head, out tail); _frag = new Fragmentation.Fragmentation(10, _route.DataRequest, mtu, head, tail); #endif _mac.BeaconNotifyIndication = MacBeaconNotifyIndication; _mac.ResetRequest(true, null); }
/** * Construct a SP800-90A Hash DRBG. * <p> * Minimum entropy requirement is the security strength requested. * </p> * @param hMac Hash MAC to base the DRBG on. * @param securityStrength security strength required (in bits) * @param entropySource source of entropy to use for seeding/reseeding. * @param personalizationString personalization string to distinguish this DRBG (may be null). * @param nonce nonce to further distinguish this DRBG (may be null). */ public HMacSP800Drbg(IMac hMac, int securityStrength, IEntropySource entropySource, byte[] personalizationString, byte[] nonce) { if (securityStrength > DrbgUtilities.GetMaxSecurityStrength(hMac)) throw new ArgumentException("Requested security strength is not supported by the derivation function"); if (entropySource.EntropySize < securityStrength) throw new ArgumentException("Not enough entropy for security strength required"); mHMac = hMac; mSecurityStrength = securityStrength; mEntropySource = entropySource; byte[] entropy = GetEntropy(); byte[] seedMaterial = Arrays.ConcatenateAll(entropy, nonce, personalizationString); mK = new byte[hMac.GetMacSize()]; mV = new byte[mK.Length]; Arrays.Fill(mV, (byte)1); hmac_DRBG_Update(seedMaterial); mReseedCounter = 1; }
private static void UpdateMac(IMac mac, byte[] bytes) { mac.BlockUpdate(bytes, 0, bytes.Length); Arrays.Fill(bytes, (byte)0); }
internal MacOutputStream(IMac mac) { this.mac = mac; }
public Pkcs5S2ParametersGenerator(IDigest digest) { this.hMac = new HMac(digest); this.state = new byte[hMac.GetMacSize()]; }
private void testMultibyte(IMac mac, TestCase testCase) { mac.BlockUpdate(testCase.getAd(), 0, testCase.getAd().Length); checkMac(mac, testCase); }
public CmsReadable GetReadable(KeyParameter sKey) { string macAlg = this.algorithm.ObjectID.Id; // Asn1Object sParams = this.algorithm.Parameters.ToAsn1Object(); try { this.mac = MacUtilities.GetMac(macAlg); // FIXME Support for MAC algorithm parameters similar to cipher parameters // ASN1Object sParams = (ASN1Object)macAlg.getParameters(); // // if (sParams != null && !(sParams instanceof ASN1Null)) // { // AlgorithmParameters params = CMSEnvelopedHelper.INSTANCE.createAlgorithmParameters(macAlg.getObjectId().getId(), provider); // // params.init(sParams.getEncoded(), "ASN.1"); // // mac.init(sKey, params.getParameterSpec(IvParameterSpec.class)); // } // else { mac.Init(sKey); } // Asn1Object asn1Params = asn1Enc == null ? null : asn1Enc.ToAsn1Object(); // // ICipherParameters cipherParameters = sKey; // // if (asn1Params != null && !(asn1Params is Asn1Null)) // { // cipherParameters = ParameterUtilities.GetCipherParameters( // macAlg.ObjectID, cipherParameters, asn1Params); // } // else // { // string alg = macAlg.ObjectID.Id; // if (alg.Equals(CmsEnvelopedDataGenerator.DesEde3Cbc) // || alg.Equals(CmsEnvelopedDataGenerator.IdeaCbc) // || alg.Equals(CmsEnvelopedDataGenerator.Cast5Cbc)) // { // cipherParameters = new ParametersWithIV(cipherParameters, new byte[8]); // } // } // // mac.Init(cipherParameters); } catch (SecurityUtilityException e) { throw new CmsException("couldn't create cipher.", e); } catch (InvalidKeyException e) { throw new CmsException("key invalid in message.", e); } catch (IOException e) { throw new CmsException("error decoding algorithm parameters.", e); } try { return new CmsProcessableInputStream( new TeeInputStream( readable.GetInputStream(), new MacOutputStream(this.mac))); } catch (IOException e) { throw new CmsException("error reading content.", e); } }
internal static int GetMaxSecurityStrength(IMac m) { string name = m.AlgorithmName; return (int)maxSecurityStrengths[name.Substring(0, name.IndexOf("/"))]; }
/** * Create an instance, using the specified hash function. * The name is used to obtain from the JVM an implementation * of the hash function and an implementation of HMAC. * * @param hashName the hash function name * @throws IllegalArgumentException on unsupported name */ public DeterministicECDSA(String hashName) { try { dig = DigestUtilities.GetDigest(hashName); } catch(SecurityUtilityException nsae) { throw new ArgumentException("Invalid hash", "hashName", nsae); } if(hashName.IndexOf('-') < 0) { macName = "Hmac" + hashName; } else { StringBuilder sb = new StringBuilder(); sb.Append("Hmac"); int n = hashName.Length; for(int i = 0 ; i < n ; i++) { char c = hashName[i]; if(c != '-') { sb.Append(c); } } macName = sb.ToString(); } try { hmac = MacUtilities.GetMac(macName); } catch(SecurityUtilityException nsae) { throw new InvalidOperationException(nsae.Message, nsae); } holen = hmac.GetMacSize(); }
public Pkcs5S2ParametersGenerator(IDigest digest) { hMac = new HMac(digest); }
private AutoResetEvent _getAddressEvent; // event raised when we got an address public Routing(INetworkLayer net, IMac mac, IDataCallbacks data) { _net = net; _mac = mac; _data = data; _mac.GetMtuSize(out _macMtu, out _macHeader, out _macTailer); // calculate the header sizes for 6LoWPAN // private encapsulation requires one byte (Message.Data.cLength) additional header space int myHeader = Messages6LoWPAN.MeshHeader.cLengthMax + Messages6LoWPAN.BroadcastHeader.cLength; _netHeader6Low = _macHeader + myHeader; _netMtu6Low = _macMtu - myHeader; _netTailer6Low = _macTailer; _neighbourTable = new NeighborTable(this, _macHeader, _macTailer); _routingTable = new RoutingTable(this); _messageContext = new MessageContext(); _seqNoDYMO = 0; _seqNoBroadcast = 0; _panId = 0; _addrShort = cInvalidShortAddr; _addrExt = 0; // to be set at start _isRunning = false; _getAddressEvent = new AutoResetEvent(false); }
/** * Build a SecureRandom based on a SP 800-90A HMAC DRBG. * * @param hMac HMAC algorithm to use in the DRBG underneath the SecureRandom. * @param nonce nonce value to use in DRBG construction. * @param predictionResistant specify whether the underlying DRBG in the resulting SecureRandom should reseed on each request for bytes. * @return a SecureRandom supported by a HMAC DRBG. */ public SP800SecureRandom BuildHMac(IMac hMac, byte[] nonce, bool predictionResistant) { return new SP800SecureRandom(mRandom, mEntropySourceProvider.Get(mEntropyBitsRequired), new HMacDrbgProvider(hMac, nonce, mPersonalizationString, mSecurityStrength), predictionResistant); }
public static byte[] DoFinal(IMac mac, byte[] input) { mac.BlockUpdate(input, 0, input.Length); return DoFinal(mac); }
public CmsAuthenticatedDataOutputStream( Stream macStream, IMac mac, BerSequenceGenerator cGen, BerSequenceGenerator authGen, BerSequenceGenerator eiGen) { this.macStream = macStream; this.mac = mac; this.cGen = cGen; this.authGen = authGen; this.eiGen = eiGen; }
protected virtual void UpdateRecordMacLength(IMac mac, int len) { byte[] longLen = Pack.UInt64_To_LE((ulong)len); mac.BlockUpdate(longLen, 0, longLen.Length); }
private static void UpdateMac(IMac mac, BigInteger bigInteger) { UpdateMac(mac, BigIntegers.AsUnsignedByteArray(bigInteger)); }
public HMacDrbgProvider(IMac hMac, byte[] nonce, byte[] personalizationString, int securityStrength) { this.mHMac = hMac; this.mNonce = nonce; this.mPersonalizationString = personalizationString; this.mSecurityStrength = securityStrength; }
protected virtual void UpdateRecordMacText(IMac mac, byte[] buf, int off, int len) { mac.BlockUpdate(buf, off, len); int partial = len % 16; if (partial != 0) { mac.BlockUpdate(Zeroes, 0, 16 - partial); } }
private void Dispose(bool Disposing) { if (!_isDisposed && Disposing) { try { if (_disposeEngine) { if (_macEngine != null) { _macEngine.Dispose(); _macEngine = null; } } if (_disposeStream) { if (_inStream != null) { _inStream.Dispose(); _inStream = null; } } } finally { _isDisposed = true; } } }
private static void UpdateMac(IMac mac, string str) { UpdateMac(mac, Encoding.UTF8.GetBytes(str)); }
/// <summary> /// Initialize the class with a digest enumeration /// </summary> /// /// <param name="Mac">The initialized <see cref="IMac"/> instance</param> /// <param name="DisposeEngine">Dispose of digest engine when <see cref="Dispose()"/> on this class is called; default is false</param> /// /// <exception cref="CryptoProcessingException">Thrown if an uninitialized Mac is used</exception> public StreamMac(IMac Mac, bool DisposeEngine = false) { if (Mac == null) throw new CryptoProcessingException("StreamMac:CTor", "The Mac can not be null!", new ArgumentNullException()); if (!Mac.IsInitialized) throw new CryptoProcessingException("StreamMac:CTor", "The Mac has not been initialized!", new ArgumentException()); _macEngine = Mac; _blockSize = _macEngine.BlockSize; _disposeEngine = DisposeEngine; }
protected virtual void UpdateRecordMac(IMac mac, byte[] buf, int off, int len) { mac.BlockUpdate(buf, off, len); byte[] longLen = Pack.UInt64_To_LE((ulong)len); mac.BlockUpdate(longLen, 0, longLen.Length); }