// Methods public DigestRandomGenerator(IDigest digest) { this.digest = digest; this.seed = new byte[digest.GetDigestSize()]; this.seedCounter = 1L; this.state = new byte[digest.GetDigestSize()]; this.stateCounter = 1L; }
/** * Used by both Dual EC and Hash. */ internal static byte[] HashDF(IDigest digest, byte[] seedMaterial, int seedLength) { // 1. temp = the Null string. // 2. . // 3. counter = an 8-bit binary value representing the integer "1". // 4. For i = 1 to len do // Comment : In step 4.1, no_of_bits_to_return // is used as a 32-bit string. // 4.1 temp = temp || Hash (counter || no_of_bits_to_return || // input_string). // 4.2 counter = counter + 1. // 5. requested_bits = Leftmost (no_of_bits_to_return) of temp. // 6. Return SUCCESS and requested_bits. byte[] temp = new byte[(seedLength + 7) / 8]; int len = temp.Length / digest.GetDigestSize(); int counter = 1; byte[] dig = new byte[digest.GetDigestSize()]; for (int i = 0; i <= len; i++) { digest.Update((byte)counter); digest.Update((byte)(seedLength >> 24)); digest.Update((byte)(seedLength >> 16)); digest.Update((byte)(seedLength >> 8)); digest.Update((byte)seedLength); digest.BlockUpdate(seedMaterial, 0, seedMaterial.Length); digest.DoFinal(dig, 0); int bytesToCopy = ((temp.Length - i * dig.Length) > dig.Length) ? dig.Length : (temp.Length - i * dig.Length); Array.Copy(dig, 0, temp, i * dig.Length, bytesToCopy); counter++; } // do a left shift to get rid of excess bits. if (seedLength % 8 != 0) { int shift = 8 - (seedLength % 8); uint carry = 0; for (int i = 0; i != temp.Length; i++) { uint b = temp[i]; temp[i] = (byte)((b >> shift) | (carry << (8 - shift))); carry = b; } } return temp; }
public DigestRandomGenerator(IDigest digest) { _digest = digest; _seed = new byte[digest.GetDigestSize()]; _seedCounter = 1; _state = new byte[digest.GetDigestSize()]; _stateCounter = 1; }
/// <summary> /// Encode the stream with the given digest. /// </summary> /// <param name="data">The byte array to be encoded.</param> /// <param name="digest">The digest to be used.</param> /// <returns>Hashed value of the byte array as a hex string.</returns> private static string Encode(byte[] data, IDigest digest) { digest.BlockUpdate(data, 0, data.Length); byte[] output = new byte[digest.GetDigestSize()]; digest.DoFinal (output, 0); return Hex.Encode(output); }
public TlsStreamCipher(TlsClientContext context, IStreamCipher encryptCipher, IStreamCipher decryptCipher, IDigest writeDigest, IDigest readDigest, int cipherKeySize) { this.context = context; this.encryptCipher = encryptCipher; this.decryptCipher = decryptCipher; int prfSize = (2 * cipherKeySize) + writeDigest.GetDigestSize() + readDigest.GetDigestSize(); SecurityParameters securityParameters = context.SecurityParameters; byte[] keyBlock = TlsUtilities.PRF(securityParameters.masterSecret, "key expansion", TlsUtilities.Concat(securityParameters.serverRandom, securityParameters.clientRandom), prfSize); int offset = 0; // Init MACs writeMac = CreateTlsMac(writeDigest, keyBlock, ref offset); readMac = CreateTlsMac(readDigest, keyBlock, ref offset); // Build keys KeyParameter encryptKey = CreateKeyParameter(keyBlock, ref offset, cipherKeySize); KeyParameter decryptKey = CreateKeyParameter(keyBlock, ref offset, cipherKeySize); if (offset != prfSize) throw new TlsFatalAlert(AlertDescription.internal_error); // Init Ciphers encryptCipher.Init(true, encryptKey); decryptCipher.Init(false, decryptKey); }
/// <summary> /// Generate a signer for the with either implicit or explicit trailers /// for ISO9796-2, scheme 2 or 3. /// </summary> /// <param name="cipher">base cipher to use for signature creation/verification</param> /// <param name="digest">digest to use.</param> /// <param name="saltLength">length of salt in bytes.</param> /// <param name="isImplicit">whether or not the trailer is implicit or gives the hash.</param> public Iso9796d2PssSigner( IAsymmetricBlockCipher cipher, IDigest digest, int saltLength, bool isImplicit) { this.cipher = cipher; this.digest = digest; this.hLen = digest.GetDigestSize(); this.saltLength = saltLength; if (isImplicit) { trailer = TrailerImplicit; } else { if (digest is Sha1Digest) { trailer = TrailerSha1; } else if (digest is RipeMD160Digest) { trailer = TrailerRipeMD160; } else if (digest is RipeMD128Digest) { trailer = TrailerRipeMD128; } else { throw new ArgumentException("no valid trailer for digest"); } } }
public static byte[] Compute(IDigest hash, byte[] data) { var result = new byte[hash.GetDigestSize()]; hash.BlockUpdate(data, 0, data.Length); hash.DoFinal(result, 0); return result; }
protected virtual TlsMac CreateTlsMac(IDigest digest, byte[] buf, ref int off) { int len = digest.GetDigestSize(); TlsMac mac = new TlsMac(digest, buf, off, len); off += len; return mac; }
private static TlsMac CreateTlsMac(IDigest digest, byte[] buf, ref int off) { int len = digest.GetDigestSize(); TlsMac mac = new TlsMac(digest, buf, off, len); off += len; return mac; }
private void doExpectedTest(IDigest digest, int seed, byte[] expected, byte[] noCycle) { DigestRandomGenerator rGen = new DigestRandomGenerator(digest); byte[] output = new byte[digest.GetDigestSize()]; rGen.AddSeedMaterial(seed); for (int i = 0; i != 1024; i++) { rGen.NextBytes(output); } if (noCycle != null) { if (Arrays.AreEqual(noCycle, output)) { Fail("seed not being cycled!"); } } if (!Arrays.AreEqual(expected, output)) { Fail("expected output doesn't match"); } }
/** * Construct a Pkcs 12 Parameters generator. * * @param digest the digest to be used as the source of derived keys. * @exception ArgumentException if an unknown digest is passed in. */ public Pkcs12ParametersGenerator( IDigest digest) { this.digest = digest; u = digest.GetDigestSize(); v = digest.GetByteLength(); }
private string GetHash(string s, IDigest algorithm) { var bytes = Encoding.UTF8.GetBytes(s); algorithm.BlockUpdate(bytes,0,bytes.Length); var res = new byte[algorithm.GetDigestSize()]; algorithm.DoFinal(res, 0); return BitConverter.ToString(res).Replace("-", string.Empty); }
public HMac(IDigest digest) { this.digest = digest; this.digestSize = digest.GetDigestSize(); this.blockLength = digest.GetByteLength(); this.inputPad = new byte[blockLength]; this.outputBuf = new byte[blockLength + digestSize]; }
private static byte[] Hash(byte[] data, IDigest digestAlgoritm) { digestAlgoritm.BlockUpdate(data, 0, data.Length); var result = new byte[digestAlgoritm.GetDigestSize()]; digestAlgoritm.DoFinal(result, 0); return result; }
/// <exception cref="IOException"></exception> public TlsNullCipher(TlsContext context, IDigest clientWriteDigest, IDigest serverWriteDigest) { if ((clientWriteDigest == null) != (serverWriteDigest == null)) throw new TlsFatalAlert(AlertDescription.internal_error); this.context = context; TlsMac clientWriteMac = null, serverWriteMac = null; if (clientWriteDigest != null) { int key_block_size = clientWriteDigest.GetDigestSize() + serverWriteDigest.GetDigestSize(); byte[] key_block = TlsUtilities.CalculateKeyBlock(context, key_block_size); int offset = 0; clientWriteMac = new TlsMac(context, clientWriteDigest, key_block, offset, clientWriteDigest.GetDigestSize()); offset += clientWriteDigest.GetDigestSize(); serverWriteMac = new TlsMac(context, serverWriteDigest, key_block, offset, serverWriteDigest.GetDigestSize()); offset += serverWriteDigest.GetDigestSize(); if (offset != key_block_size) { throw new TlsFatalAlert(AlertDescription.internal_error); } } if (context.IsServer) { writeMac = serverWriteMac; readMac = clientWriteMac; } else { writeMac = clientWriteMac; readMac = serverWriteMac; } }
private static BigInteger HashPaddedPair(IDigest digest, BigInteger N, BigInteger n1, BigInteger n2) { int length = (N.BitLength + 7) / 8; byte[] padded = GetPadded(n1, length); byte[] input = GetPadded(n2, length); digest.BlockUpdate(padded, 0, padded.Length); digest.BlockUpdate(input, 0, input.Length); byte[] output = new byte[digest.GetDigestSize()]; digest.DoFinal(output, 0); return new BigInteger(1, output).Mod(N); }
public HMac( IDigest digest) { this.digest = digest; digestSize = digest.GetDigestSize(); blockLength = digest.GetByteLength(); inputPad = new byte[blockLength]; outputPad = new byte[blockLength]; }
/// <summary> /// Encode the stream with the given digest. /// </summary> /// <param name="instream">The stream to be encoded.</param> /// <param name="digest">The digest to be used.</param> /// <returns>Hashed value of the stream as a hex string.</returns> private static string Encode(Stream instream , IDigest digest) { byte[] buffer = new byte[BUFFER_SIZE]; int read; while ((read = instream.Read(buffer, 0, BUFFER_SIZE)) > 0) { digest.BlockUpdate(buffer, 0, read); } byte[] output = new byte[digest.GetDigestSize()]; digest.DoFinal(output, 0); return Hex.Encode(output); }
public static BigInteger CalculateX(IDigest digest, BigInteger N, byte[] salt, byte[] identity, byte[] password) { byte[] output = new byte[digest.GetDigestSize()]; digest.BlockUpdate(identity, 0, identity.Length); digest.Update(0x3a); digest.BlockUpdate(password, 0, password.Length); digest.DoFinal(output, 0); digest.BlockUpdate(salt, 0, salt.Length); digest.BlockUpdate(output, 0, output.Length); digest.DoFinal(output, 0); return new BigInteger(1, output).Mod(N); }
private byte[] MakeTestHash( IDigest digest) { for (int i = 0; i < digest.GetDigestSize(); ++i) { digest.Update((byte) i); } digest.BlockUpdate(TestBytes, 0, TestBytes.Length); return DigestUtilities.DoFinal(digest); }
private PssSigner(IAsymmetricBlockCipher cipher, IDigest contentDigest1, IDigest contentDigest2, IDigest mgfDigest, int saltLen, byte trailer) { _cipher = cipher; _contentDigest1 = contentDigest1; _contentDigest2 = contentDigest2; _mgfDigest = mgfDigest; _hLen = contentDigest2.GetDigestSize(); _mgfhLen = mgfDigest.GetDigestSize(); _sLen = saltLen; _salt = new byte[saltLen]; _mDash = new byte[8 + saltLen + _hLen]; _trailer = trailer; }
/** * Base constructor for one of the standard digest algorithms that the byteLength of * the algorithm is know for. Behaviour is undefined for digests other than MD5 or SHA1. * * @param digest the digest. */ public Ssl3Mac(IDigest digest) { this.digest = digest; if (digest.GetDigestSize() == 20) { this.padLength = 40; } else { this.padLength = 48; } }
public PssSigner( IAsymmetricBlockCipher cipher, IDigest digest, int saltLen, byte trailer) { this.cipher = cipher; this.digest = digest; this.hLen = digest.GetDigestSize(); this.sLen = saltLen; this.salt = new byte[saltLen]; this.mDash = new byte[8 + saltLen + hLen]; this.trailer = trailer; }
public OaepEncoding(IAsymmetricBlockCipher cipher, IDigest hash, IDigest mgf1Hash, byte[] encodingParams) { _engine = cipher; _hash = hash; _mgf1Hash = mgf1Hash; _defHash = new byte[hash.GetDigestSize()]; if (encodingParams != null) { hash.BlockUpdate(encodingParams, 0, encodingParams.Length); } hash.DoFinal(_defHash, 0); }
/** * 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 static BigInteger CalculateX(IDigest digest, BigInteger N, byte[] salt, byte[] identity, byte[] password) { byte[] output = new byte[digest.GetDigestSize()]; digest.BlockUpdate(identity, 0, identity.Length); digest.Update((byte)':'); digest.BlockUpdate(password, 0, password.Length); digest.DoFinal(output, 0); digest.BlockUpdate(salt, 0, salt.Length); digest.BlockUpdate(output, 0, output.Length); digest.DoFinal(output, 0); return(new BigInteger(1, output)); }
/** * Constructs a new index generator. * * @param seed a seed of arbitrary length to initialize the index generator with * @param params NtruEncrypt parameters */ IndexGenerator(byte[] seed, NTRUEncryptionParameters encryptionParameters) { this.seed = seed; N = encryptionParameters.N; c = encryptionParameters.c; minCallsR = encryptionParameters.minCallsR; totLen = 0; remLen = 0; counter = 0; hashAlg = encryptionParameters.hashAlg; hLen = hashAlg.GetDigestSize(); // hash length initialized = false; }
private static BigInteger HashPaddedPair(IDigest digest, BigInteger N, BigInteger n1, BigInteger n2) { int padLength = (N.BitLength + 7) / 8; byte[] n1_bytes = GetPadded(n1, padLength); byte[] n2_bytes = GetPadded(n2, padLength); digest.BlockUpdate(n1_bytes, 0, n1_bytes.Length); digest.BlockUpdate(n2_bytes, 0, n2_bytes.Length); byte[] output = new byte[digest.GetDigestSize()]; digest.DoFinal(output, 0); return new BigInteger(1, output).Mod(N); }
public virtual byte[] GenerateSignature() { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (!forSigning) { throw new InvalidOperationException("GOST3410DigestSigner not initialised for signature generation."); } byte[] array = new byte[digest.GetDigestSize()]; digest.DoFinal(array, 0); try { BigInteger[] array2 = dsaSigner.GenerateSignature(array); byte[] array3 = new byte[64]; byte[] array4 = array2[0].ToByteArrayUnsigned(); byte[] array5 = array2[1].ToByteArrayUnsigned(); ((global::System.Array)array5).CopyTo((global::System.Array)array3, 32 - array5.Length); ((global::System.Array)array4).CopyTo((global::System.Array)array3, 64 - array4.Length); return(array3); } catch (global::System.Exception ex) { throw new SignatureException(ex.get_Message(), ex); } }
/** * Base constructor for one of the standard digest algorithms that the byteLength of * the algorithm is know for. Behaviour is undefined for digests other than MD5 or SHA1. * * @param digest the digest. */ public Ssl3Mac(IDigest digest) { this.digest = digest; if (digest.GetDigestSize() == 20) { this.ipad = SHA1_IPAD; this.opad = SHA1_OPAD; } else { this.ipad = MD5_IPAD; this.opad = MD5_OPAD; } }
/** * Base constructor for one of the standard digest algorithms that the byteLength of * the algorithm is know for. Behaviour is undefined for digests other than MD5 or SHA1. * * @param digest the digest. */ public Ssl3Mac(IDigest digest) { this.digest = digest; if (digest.GetDigestSize() == 20) { this.ipad = SHA1_IPAD; this.opad = SHA1_OPAD; } else { this.ipad = MD5_IPAD; this.opad = MD5_OPAD; } }
public ShortenedDigest(IDigest baseDigest, int length) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) if (baseDigest == null) { throw new ArgumentNullException("baseDigest"); } if (length > baseDigest.GetDigestSize()) { throw new ArgumentException("baseDigest output not large enough to support length"); } this.baseDigest = baseDigest; this.length = length; }
internal AbstractTlsContext(SecureRandom secureRandom, SecurityParameters securityParameters) { IDigest d = TlsUtilities.CreateHash(HashAlgorithm.sha256); byte[] seed = new byte[d.GetDigestSize()]; secureRandom.NextBytes(seed); this.mNonceRandom = new DigestRandomGenerator(d); mNonceRandom.AddSeedMaterial(NextCounterValue()); mNonceRandom.AddSeedMaterial(Times.NanoTime()); mNonceRandom.AddSeedMaterial(seed); this.mSecureRandom = secureRandom; this.mSecurityParameters = securityParameters; }
private static BigInteger HashPaddedPair(IDigest digest, BigInteger N, BigInteger n1, BigInteger n2) { int padLength = (N.BitLength + 7) / 8; byte[] n1_bytes = GetPadded(n1, padLength); byte[] n2_bytes = GetPadded(n2, padLength); digest.BlockUpdate(n1_bytes, 0, n1_bytes.Length); digest.BlockUpdate(n2_bytes, 0, n2_bytes.Length); byte[] output = new byte[digest.GetDigestSize()]; digest.DoFinal(output, 0); return(new BigInteger(1, output)); }
public AsyncDtlsClientContext(SecureRandom secureRandom, AsyncDtlsSecurityParameters securityParameters) { IDigest d = TlsUtilities.CreateHash(HashAlgorithm.sha256); byte[] seed = new byte[d.GetDigestSize()]; secureRandom.NextBytes(seed); this.nonceRandom = new DigestRandomGenerator(d); nonceRandom.AddSeedMaterial(NextCounterValue()); nonceRandom.AddSeedMaterial(Times.NanoTime()); nonceRandom.AddSeedMaterial(seed); this.secureRandom = secureRandom; this.securityParameters = securityParameters; }
/** * Signs a document with a PAdES-LTV Timestamp. The document is closed at the end. * @param sap the signature appearance * @param tsa the timestamp generator * @param signatureName the signature name or null to have a name generated * automatically * @throws Exception */ public static void Timestamp(PdfSignatureAppearance sap, ITSAClient tsa, String signatureName) { int contentEstimated = tsa.GetTokenSizeEstimate(); sap.AddDeveloperExtension(PdfDeveloperExtension.ESIC_1_7_EXTENSIONLEVEL5); sap.SetVisibleSignature(new Rectangle(0, 0, 0, 0), 1, signatureName); PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ETSI_RFC3161); dic.Put(PdfName.TYPE, PdfName.DOCTIMESTAMP); sap.CryptoDictionary = dic; Dictionary <PdfName, int> exc = new Dictionary <PdfName, int>(); exc[PdfName.CONTENTS] = contentEstimated * 2 + 2; sap.PreClose(exc); Stream data = sap.GetRangeStream(); IDigest messageDigest = tsa.GetMessageDigest(); byte[] buf = new byte[4096]; int n; while ((n = data.Read(buf, 0, buf.Length)) > 0) { messageDigest.BlockUpdate(buf, 0, n); } byte[] tsImprint = new byte[messageDigest.GetDigestSize()]; messageDigest.DoFinal(tsImprint, 0); byte[] tsToken; try { tsToken = tsa.GetTimeStampToken(tsImprint); } catch (Exception e) { throw new GeneralSecurityException(e.Message); } if (contentEstimated + 2 < tsToken.Length) { throw new IOException("Not enough space"); } byte[] paddedSig = new byte[contentEstimated]; System.Array.Copy(tsToken, 0, paddedSig, 0, tsToken.Length); PdfDictionary dic2 = new PdfDictionary(); dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true)); sap.Close(dic2); }
public PssSigner( IAsymmetricBlockCipher cipher, IDigest contentDigest, IDigest mgfDigest, int saltLen, byte trailer) { this.cipher = cipher; this.contentDigest = contentDigest; this.mgfDigest = mgfDigest; this.hLen = mgfDigest.GetDigestSize(); this.sLen = saltLen; this.salt = new byte[saltLen]; this.mDash = new byte[8 + saltLen + hLen]; this.trailer = trailer; }
public byte[] GenerateSignature() { if (PreComputedSignature?.Length > 0) { currentSignature = PreComputedSignature; return(PreComputedSignature); } else { byte[] hash = new byte[digest.GetDigestSize()]; digest.DoFinal(hash, 0); //jbonilla currentSignature = hash; return(currentSignature); } }
public byte[] calculateHash(HashAlgorithm hashAlgorithm, byte[] inputAsBytes) { IDigest alg = createHash(hashAlgorithm); if (alg == null) { return(null); } byte[] retValue = new byte[alg.GetDigestSize()]; if (inputAsBytes != null) { alg.BlockUpdate(inputAsBytes, 0, inputAsBytes.Length); } alg.DoFinal(retValue, 0); return(retValue); }
public OaepEncoding( IAsymmetricBlockCipher cipher, IDigest hash, byte[] encodingParams) { this.engine = cipher; this.hash = hash; this.defHash = new byte[hash.GetDigestSize()]; if (encodingParams != null) { hash.BlockUpdate(encodingParams, 0, encodingParams.Length); } hash.DoFinal(defHash, 0); }
internal FastRandomGenerator( SafeRandomGenerator safeRng, bool ownsSafeRng, IDigest digest) { if (digest == null) { throw new ArgumentNullException(nameof(digest)); } _safeRandomGenerator = safeRng ?? throw new ArgumentNullException(nameof(safeRng)); _ownsSafeRandomGenerator = ownsSafeRng; _prng = new DigestRandomGenerator(digest); _digestSize = digest.GetDigestSize(); SeedSize = _digestSize; Reseed(); }
private byte[] Decrypt(byte[] input, int inOff, int inLen) { byte[] c1 = new byte[mCurveLength * 2 + 1]; Array.Copy(input, inOff, c1, 0, c1.Length); ECPoint c1P = mECParams.Curve.DecodePoint(c1); ECPoint s = c1P.Multiply(mECParams.H); if (s.IsInfinity) { throw new InvalidCipherTextException("[h]C1 at infinity"); } c1P = c1P.Multiply(((ECPrivateKeyParameters)mECKey).D).Normalize(); byte[] c2 = new byte[inLen - c1.Length - mDigest.GetDigestSize()]; Array.Copy(input, inOff + c1.Length, c2, 0, c2.Length); Kdf(mDigest, c1P, c2); AddFieldElement(mDigest, c1P.AffineXCoord); mDigest.BlockUpdate(c2, 0, c2.Length); AddFieldElement(mDigest, c1P.AffineYCoord); byte[] c3 = DigestUtilities.DoFinal(mDigest); int check = 0; for (int i = 0; i != c3.Length; i++) { check |= c3[i] ^ input[inOff + c1.Length + c2.Length + i]; } Arrays.Fill(c1, 0); Arrays.Fill(c3, 0); if (check != 0) { Arrays.Fill(c2, 0); throw new InvalidCipherTextException("invalid cipher text"); } return(c2); }
private static byte[] HKDF(byte[] secret, byte[] salt, byte[] info, int cbit, IDigest digest) { // Now start doing HKDF // Perform the Extract phase HMac mac = new HMac(digest); int hashLength = digest.GetDigestSize(); int c = ((cbit + 7) / 8 + hashLength - 1) / hashLength; if (salt == null) { salt = new byte[0]; } KeyParameter key = new KeyParameter(salt); mac.Init(key); mac.BlockUpdate(secret, 0, secret.Length); byte[] rgbExtract = new byte[hashLength]; mac.DoFinal(rgbExtract, 0); // Now do the Expand Phase byte[] rgbOut = new byte[cbit / 8]; byte[] rgbT = new byte[hashLength * c]; mac = new HMac(digest); key = new KeyParameter(rgbExtract); mac.Init(key); byte[] rgbLast = new byte[0]; byte[] rgbHash2 = new byte[hashLength]; for (int i = 0; i < c; i++) { mac.Reset(); mac.BlockUpdate(rgbLast, 0, rgbLast.Length); mac.BlockUpdate(info, 0, info.Length); mac.Update((byte)(i + 1)); rgbLast = rgbHash2; mac.DoFinal(rgbLast, 0); Array.Copy(rgbLast, 0, rgbT, i * hashLength, hashLength); } Array.Copy(rgbT, 0, rgbOut, 0, cbit / 8); return(rgbOut); }
protected virtual byte[] Kdf(ECPoint u, byte[] za, byte[] zb, int klen) { int digestSize = mDigest.GetDigestSize(); byte[] buf = new byte[System.Math.Max(4, digestSize)]; byte[] rv = new byte[(klen + 7) / 8]; int off = 0; IMemoable memo = mDigest as IMemoable; IMemoable copy = null; if (memo != null) { AddFieldElement(mDigest, u.AffineXCoord); AddFieldElement(mDigest, u.AffineYCoord); mDigest.BlockUpdate(za, 0, za.Length); mDigest.BlockUpdate(zb, 0, zb.Length); copy = memo.Copy(); } uint ct = 0; while (off < rv.Length) { if (memo != null) { memo.Reset(copy); } else { AddFieldElement(mDigest, u.AffineXCoord); AddFieldElement(mDigest, u.AffineYCoord); mDigest.BlockUpdate(za, 0, za.Length); mDigest.BlockUpdate(zb, 0, zb.Length); } Pack.UInt32_To_BE(++ct, buf, 0); mDigest.BlockUpdate(buf, 0, 4); mDigest.DoFinal(buf, 0); int copyLen = System.Math.Min(digestSize, rv.Length - off); Array.Copy(buf, 0, rv, off, copyLen); off += copyLen; } return(rv); }
private static DigestRandomGenerator CreatePrng(string digestName, bool autoSeed) { IDigest digest = FipsShs.CreateDigest(FipsShs.Sha256); if (digest == null) { return(null); } DigestRandomGenerator prng = new DigestRandomGenerator(digest); if (autoSeed) { prng.AddSeedMaterial(NextCounterValue()); prng.AddSeedMaterial(GetNextBytes(Master, digest.GetDigestSize())); } return(prng); }
private static DigestRandomGenerator CreatePrng(string digestName, bool autoSeed) { IDigest digest = DigestUtilities.GetDigest(digestName); if (digest == null) { return(null); } DigestRandomGenerator prng = new DigestRandomGenerator(digest); if (autoSeed) { prng.AddSeedMaterial(NextCounterValue()); prng.AddSeedMaterial(GetSeed(digest.GetDigestSize())); } return(prng); }
/** * Base constructor. * * @param baseDigest underlying digest to use. * @param length length in bytes of the output of doFinal. * @exception ArgumentException if baseDigest is null, or length is greater than baseDigest.GetDigestSize(). */ public ShortenedDigest( IDigest baseDigest, int length) { if (baseDigest == null) { throw new ArgumentNullException("baseDigest"); } if (length > baseDigest.GetDigestSize()) { throw new ArgumentException("baseDigest output not large enough to support length"); } this.baseDigest = baseDigest; this.length = length; }
public byte[] ComputeDigest(byte[] data) { if (data == null || data.Length < 1) { throw new ArgumentNullException("data"); } IDigest digest = GetImplementationInstance(); byte[] hash = new byte[digest.GetDigestSize()]; digest.Reset(); digest.BlockUpdate(data, 0, data.Length); digest.DoFinal(hash, 0); return(hash); }
static byte[] CreateMessageDigestHash(Stream data, string algorithm) { IDigest messageDigest = DigestUtilities.GetDigest(algorithm); byte[] buf = new byte[8192]; int n; while ((n = data.Read(buf, 0, buf.Length)) > 0) { messageDigest.BlockUpdate(buf, 0, n); } byte[] hash = new byte[messageDigest.GetDigestSize()]; messageDigest.DoFinal(hash, 0); return(hash); }
public static Span <byte> X963Kdf(IDigest digest, ReadOnlySpan <byte> shsee, ReadOnlySpan <byte> shsss, ReadOnlySpan <byte> shared, int length) { var size = digest.GetDigestSize(); var cnt = 0U; var ret = new byte[size * ((length + size - 1) / size)]; for (var offs = 0; offs < length; offs += size) { digest.Reset(); digest.BlockUpdate(shsee); digest.BlockUpdate(shsss); digest.BlockUpdate(++cnt); digest.BlockUpdate(shared); digest.DoFinal(ret, offs); } return(ret.AsSpan(0, length)); }
/** * Base constructor. * * @param baseDigest underlying digest to use. * @param length length in bytes of the output of doFinal. * @exception ArgumentException if baseDigest is null, or length is greater than baseDigest.GetDigestSize(). */ public ShortenedDigest( IDigest baseDigest, int length) { if (baseDigest == null) { throw new ArgumentNullException("baseDigest"); } if (length > baseDigest.GetDigestSize()) { throw new ArgumentException("baseDigest output not large enough to support length"); } this.baseDigest = baseDigest; this.length = length; }
private static DigestRandomGenerator CreatePrng(string digestName, bool autoSeed) { IDigest digest = DigestUtilities.GetDigest(digestName); if (digest == null) { return(null); } DigestRandomGenerator digestRandomGenerator = new DigestRandomGenerator(digest); if (autoSeed) { digestRandomGenerator.AddSeedMaterial(NextCounterValue()); digestRandomGenerator.AddSeedMaterial(GetNextBytes(Master, digest.GetDigestSize())); } return(digestRandomGenerator); }
public TlsBlockCipher(TlsClientContext context, IBlockCipher encryptCipher, IBlockCipher decryptCipher, IDigest writeDigest, IDigest readDigest, int cipherKeySize) { this.context = context; this.randomData = new byte[256]; context.SecureRandom.NextBytes(randomData); this.encryptCipher = encryptCipher; this.decryptCipher = decryptCipher; int prfSize = (2 * cipherKeySize) + writeDigest.GetDigestSize() + readDigest.GetDigestSize() + encryptCipher.GetBlockSize() + decryptCipher.GetBlockSize(); SecurityParameters securityParameters = context.SecurityParameters; byte[] keyBlock = TlsUtilities.PRF(securityParameters.masterSecret, "key expansion", TlsUtilities.Concat(securityParameters.serverRandom, securityParameters.clientRandom), prfSize); int offset = 0; // Init MACs wMac = CreateTlsMac(writeDigest, keyBlock, ref offset); rMac = CreateTlsMac(readDigest, keyBlock, ref offset); // Build keys KeyParameter encryptKey = CreateKeyParameter(keyBlock, ref offset, cipherKeySize); KeyParameter decryptKey = CreateKeyParameter(keyBlock, ref offset, cipherKeySize); // Add IVs ParametersWithIV encryptParams = CreateParametersWithIV(encryptKey, keyBlock, ref offset, encryptCipher.GetBlockSize()); ParametersWithIV decryptParams = CreateParametersWithIV(decryptKey, keyBlock, ref offset, decryptCipher.GetBlockSize()); if (offset != prfSize) { throw new TlsFatalAlert(AlertDescription.internal_error); } // Init Ciphers encryptCipher.Init(true, encryptParams); decryptCipher.Init(false, decryptParams); }
private IMacFactory GenCalculator(PbmParameter parameters, char[] password) { // From RFC 4211 // // 1. Generate a random salt value S // // 2. Append the salt to the pw. K = pw || salt. // // 3. Hash the value of K. K = HASH(K) // // 4. Iter = Iter - 1. If Iter is greater than zero. Goto step 3. // // 5. Compute an HMAC as documented in [HMAC]. // // MAC = HASH( K XOR opad, HASH( K XOR ipad, data) ) // // Where opad and ipad are defined in [HMAC]. byte[] pw = Strings.ToUtf8ByteArray(password); byte[] salt = parameters.Salt.GetOctets(); byte[] K = new byte[pw.Length + salt.Length]; Array.Copy(pw, 0, K, 0, pw.Length); Array.Copy(salt, 0, K, pw.Length, salt.Length); IDigest digest = provider.CreateDigest(parameters.Owf); int iter = parameters.IterationCount.IntValueExact; digest.BlockUpdate(K, 0, K.Length); K = new byte[digest.GetDigestSize()]; digest.DoFinal(K, 0); while (--iter > 0) { digest.BlockUpdate(K, 0, K.Length); digest.DoFinal(K, 0); } byte[] key = K; return(new PKMacFactory(key, parameters)); }
protected override void Dispose(bool disposing) { if (disposing) { if (m_digest != null) { try { m_pbFinalHash = new byte[m_digest.GetDigestSize()]; } catch (Exception) { Debug.Assert(false); } m_digest = null; } } base.Dispose(disposing); }
private void doExpectedTest(IDigest digest, byte[] seed, byte[] expected) { DigestRandomGenerator rGen = new DigestRandomGenerator(digest); byte[] output = new byte[digest.GetDigestSize()]; rGen.AddSeedMaterial(seed); for (int i = 0; i != 1024; i++) { rGen.NextBytes(output); } if (!Arrays.AreEqual(expected, output)) { Fail("expected output doesn't match"); } }
public Iso9796d2PssSigner(IAsymmetricBlockCipher cipher, IDigest digest, int saltLength, bool isImplicit) { //IL_0049: Unknown result type (might be due to invalid IL or missing references) this.cipher = cipher; this.digest = digest; hLen = digest.GetDigestSize(); this.saltLength = saltLength; if (isImplicit) { trailer = 188; return; } if (IsoTrailers.NoTrailerAvailable(digest)) { throw new ArgumentException("no valid trailer", "digest"); } trailer = IsoTrailers.GetTrailer(digest); }
public TlsBlockCipher(TlsClientContext context, IBlockCipher encryptCipher, IBlockCipher decryptCipher, IDigest writeDigest, IDigest readDigest, int cipherKeySize) { this.context = context; this.randomData = new byte[256]; context.SecureRandom.NextBytes(randomData); this.encryptCipher = encryptCipher; this.decryptCipher = decryptCipher; int prfSize = (2 * cipherKeySize) + writeDigest.GetDigestSize() + readDigest.GetDigestSize() + encryptCipher.GetBlockSize() + decryptCipher.GetBlockSize(); SecurityParameters securityParameters = context.SecurityParameters; byte[] keyBlock = TlsUtilities.PRF(securityParameters.masterSecret, "key expansion", TlsUtilities.Concat(securityParameters.serverRandom, securityParameters.clientRandom), prfSize); int offset = 0; // Init MACs wMac = CreateTlsMac(writeDigest, keyBlock, ref offset); rMac = CreateTlsMac(readDigest, keyBlock, ref offset); // Build keys KeyParameter encryptKey = CreateKeyParameter(keyBlock, ref offset, cipherKeySize); KeyParameter decryptKey = CreateKeyParameter(keyBlock, ref offset, cipherKeySize); // Add IVs ParametersWithIV encryptParams = CreateParametersWithIV(encryptKey, keyBlock, ref offset, encryptCipher.GetBlockSize()); ParametersWithIV decryptParams = CreateParametersWithIV(decryptKey, keyBlock, ref offset, decryptCipher.GetBlockSize()); if (offset != prfSize) throw new TlsFatalAlert(AlertDescription.internal_error); // Init Ciphers encryptCipher.Init(true, encryptParams); decryptCipher.Init(false, decryptParams); }
public byte[] GetFinalHash(byte hashAlgorithm) { IDigest d = (IDigest)hashes[hashAlgorithm]; if (d == null) { throw new InvalidOperationException("HashAlgorithm." + HashAlgorithm.GetText(hashAlgorithm) + " is not being tracked"); } d = DtlsHelper.CloneHash(hashAlgorithm, d); if (buf != null) { buf.UpdateDigest(d); } byte[] bs = new byte[d.GetDigestSize()]; d.DoFinal(bs, 0); return(bs); }
internal TlsBlockCipher(TlsProtocolHandler handler, IBlockCipher encryptCipher, IBlockCipher decryptCipher, IDigest writeDigest, IDigest readDigest, int cipherKeySize, SecurityParameters securityParameters) { this.handler = handler; this.encryptCipher = encryptCipher; this.decryptCipher = decryptCipher; int prfSize = (2 * cipherKeySize) + writeDigest.GetDigestSize() + readDigest.GetDigestSize() + encryptCipher.GetBlockSize() + decryptCipher.GetBlockSize(); byte[] keyBlock = TlsUtilities.PRF(securityParameters.masterSecret, "key expansion", TlsUtilities.Concat(securityParameters.serverRandom, securityParameters.clientRandom), prfSize); int offset = 0; // Init MACs writeMac = CreateTlsMac(writeDigest, keyBlock, ref offset); readMac = CreateTlsMac(readDigest, keyBlock, ref offset); // Build keys KeyParameter encryptKey = CreateKeyParameter(keyBlock, ref offset, cipherKeySize); KeyParameter decryptKey = CreateKeyParameter(keyBlock, ref offset, cipherKeySize); // Add IVs ParametersWithIV encryptParams = CreateParametersWithIV(encryptKey, keyBlock, ref offset, encryptCipher.GetBlockSize()); ParametersWithIV decryptParams = CreateParametersWithIV(decryptKey, keyBlock, ref offset, decryptCipher.GetBlockSize()); if (offset != prfSize) handler.FailWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_internal_error); // Init Ciphers encryptCipher.Init(true, encryptParams); decryptCipher.Init(false, decryptParams); }