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 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 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); }
/// <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 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; }
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); }
/** * 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; }
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; }
/// <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); }
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); }
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); }
public RespID( AsymmetricKeyParameter publicKey) { try { IDigest digest = DigestUtilities.GetDigest("SHA1"); SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey); byte[] encoded = info.PublicKeyData.GetBytes(); digest.BlockUpdate(encoded, 0, encoded.Length); byte[] hash = DigestUtilities.DoFinal(digest); Asn1OctetString keyHash = new DerOctetString(hash); this.id = new ResponderID(keyHash); } catch (Exception e) { throw new OcspException("problem creating ID: " + e, e); } }
private static void ImplSign(byte[] sk, int skOff, byte[] ctx, byte phflag, byte[] m, int mOff, int mLen, byte[] sig, int sigOff) { if (!CheckContextVar(ctx, phflag)) { throw new ArgumentException("ctx"); } IDigest d = CreateDigest(); byte[] h = new byte[d.GetDigestSize()]; d.BlockUpdate(sk, skOff, SecretKeySize); d.DoFinal(h, 0); byte[] s = new byte[ScalarBytes]; PruneScalar(h, 0, s); byte[] pk = new byte[PointBytes]; ScalarMultBaseEncoded(s, pk, 0); ImplSign(d, h, s, pk, 0, ctx, phflag, m, mOff, mLen, sig, sigOff); }
public virtual void Init(ICipherParameters parameters) { digest.Reset(); byte[] key = ((KeyParameter)parameters).GetKey(); int keyLength = key.Length; if (keyLength > blockLength) { digest.BlockUpdate(key, 0, keyLength); digest.DoFinal(inputPad, 0); keyLength = digestSize; } else { Array.Copy(key, 0, inputPad, 0, keyLength); } Array.Clear(inputPad, keyLength, blockLength - keyLength); Array.Copy(inputPad, 0, outputBuf, 0, blockLength); XorPad(inputPad, blockLength, IPAD); XorPad(outputBuf, blockLength, OPAD); if (digest is IMemoable) { opadState = ((IMemoable)digest).Copy(); ((IDigest)opadState).BlockUpdate(outputBuf, 0, blockLength); } digest.BlockUpdate(inputPad, 0, inputPad.Length); if (digest is IMemoable) { ipadState = ((IMemoable)digest).Copy(); } }
public void Init( ICipherParameters parameters) { digest.Reset(); byte[] key = ((KeyParameter)parameters).GetKey(); if (key.Length > blockLength) { digest.BlockUpdate(key, 0, key.Length); digest.DoFinal(inputPad, 0); for (int i = digestSize; i < inputPad.Length; i++) { inputPad[i] = 0; } } else { Array.Copy(key, 0, inputPad, 0, key.Length); for (int i = key.Length; i < inputPad.Length; i++) { inputPad[i] = 0; } } outputPad = new byte[inputPad.Length]; Array.Copy(inputPad, 0, outputPad, 0, inputPad.Length); for (int i = 0; i < inputPad.Length; i++) { inputPad[i] ^= IPAD; } for (int i = 0; i < outputPad.Length; i++) { outputPad[i] ^= OPAD; } digest.BlockUpdate(inputPad, 0, inputPad.Length); }
/// <summary> Generate a signature for the message we've been loaded with using /// the key we were initialised with. /// </summary> public virtual byte[] GenerateSignature() { contentDigest.DoFinal(mDash, mDash.Length - hLen - sLen); if (sLen != 0) { random.NextBytes(salt); salt.CopyTo(mDash, mDash.Length - sLen); } byte[] h = new byte[hLen]; mgfDigest.BlockUpdate(mDash, 0, mDash.Length); mgfDigest.DoFinal(h, 0); block[block.Length - sLen - 1 - hLen - 1] = (byte)(0x01); salt.CopyTo(block, block.Length - sLen - hLen - 1); byte[] dbMask = MaskGeneratorFunction1(h, 0, h.Length, block.Length - hLen - 1); for (int i = 0; i != dbMask.Length; i++) { block[i] ^= dbMask[i]; } block[0] &= (byte)((0xff >> ((block.Length * 8) - emBits))); h.CopyTo(block, block.Length - hLen - 1); block[block.Length - 1] = trailer; byte[] b = cipher.ProcessBlock(block, 0, block.Length); ClearBlock(block); return(b); }
private static void UpdateDigest(IDigest digest, byte[] bytes) { digest.BlockUpdate(bytes, 0, bytes.Length); Arrays.Fill(bytes, (byte)0); }
private static void Hash(IDigest d, byte[] input, byte[] output) { d.BlockUpdate(input, 0, input.Length); d.DoFinal(output, 0); }
private void AddFieldElement(IDigest digest, ECFieldElement v) { byte[] p = v.GetEncoded(); digest.BlockUpdate(p, 0, p.Length); }
// gets keylength and revision and uses revison to choose the initial values for permissions virtual public void SetupAllKeys(byte[] userPassword, byte[] ownerPassword, int permissions) { if (ownerPassword == null || ownerPassword.Length == 0) { ownerPassword = DigestAlgorithms.Digest("MD5", CreateDocumentId()); } md5.Reset(); permissions |= (int)((revision == STANDARD_ENCRYPTION_128 || revision == AES_128 || revision == AES_256) ? (uint)0xfffff0c0 : (uint)0xffffffc0); permissions &= unchecked ((int)0xfffffffc); this.permissions = permissions; if (revision == AES_256) { if (userPassword == null) { userPassword = new byte[0]; } documentID = CreateDocumentId(); byte[] uvs = IVGenerator.GetIV(8); byte[] uks = IVGenerator.GetIV(8); key = IVGenerator.GetIV(32); // Algorithm 3.8.1 IDigest md = DigestUtilities.GetDigest("SHA-256"); md.BlockUpdate(userPassword, 0, Math.Min(userPassword.Length, 127)); md.BlockUpdate(uvs, 0, uvs.Length); userKey = new byte[48]; md.DoFinal(userKey, 0); System.Array.Copy(uvs, 0, userKey, 32, 8); System.Array.Copy(uks, 0, userKey, 40, 8); // Algorithm 3.8.2 md.BlockUpdate(userPassword, 0, Math.Min(userPassword.Length, 127)); md.BlockUpdate(uks, 0, uks.Length); byte[] tempDigest = new byte[32]; md.DoFinal(tempDigest, 0); AESCipherCBCnoPad ac = new AESCipherCBCnoPad(true, tempDigest); ueKey = ac.ProcessBlock(key, 0, key.Length); // Algorithm 3.9.1 byte[] ovs = IVGenerator.GetIV(8); byte[] oks = IVGenerator.GetIV(8); md.BlockUpdate(ownerPassword, 0, Math.Min(ownerPassword.Length, 127)); md.BlockUpdate(ovs, 0, ovs.Length); md.BlockUpdate(userKey, 0, userKey.Length); ownerKey = new byte[48]; md.DoFinal(ownerKey, 0); System.Array.Copy(ovs, 0, ownerKey, 32, 8); System.Array.Copy(oks, 0, ownerKey, 40, 8); // Algorithm 3.9.2 md.BlockUpdate(ownerPassword, 0, Math.Min(ownerPassword.Length, 127)); md.BlockUpdate(oks, 0, oks.Length); md.BlockUpdate(userKey, 0, userKey.Length); md.DoFinal(tempDigest, 0); ac = new AESCipherCBCnoPad(true, tempDigest); oeKey = ac.ProcessBlock(key, 0, key.Length); // Algorithm 3.10 byte[] permsp = IVGenerator.GetIV(16); permsp[0] = (byte)permissions; permsp[1] = (byte)(permissions >> 8); permsp[2] = (byte)(permissions >> 16); permsp[3] = (byte)(permissions >> 24); permsp[4] = (byte)(255); permsp[5] = (byte)(255); permsp[6] = (byte)(255); permsp[7] = (byte)(255); permsp[8] = encryptMetadata ? (byte)'T' : (byte)'F'; permsp[9] = (byte)'a'; permsp[10] = (byte)'d'; permsp[11] = (byte)'b'; ac = new AESCipherCBCnoPad(true, key); perms = ac.ProcessBlock(permsp, 0, permsp.Length); } else { //PDF refrence 3.5.2 Standard Security Handler, Algorithum 3.3-1 //If there is no owner password, use the user password instead. byte[] userPad = PadPassword(userPassword); byte[] ownerPad = PadPassword(ownerPassword); this.ownerKey = ComputeOwnerKey(userPad, ownerPad); documentID = CreateDocumentId(); SetupByUserPad(this.documentID, userPad, this.ownerKey, permissions); } }
private static void UpdateDigest(IDigest d, BigInteger b) { byte[] bytes = b.ToByteArrayUnsigned(); d.BlockUpdate(bytes, 0, bytes.Length); }
private byte[] GenerateDerivedKey(int idByte, int n) { byte[] array = new byte[v]; byte[] array2 = new byte[n]; for (int i = 0; i != array.Length; i++) { array[i] = (byte)idByte; } byte[] array3; if (mSalt != null && mSalt.Length != 0) { array3 = new byte[v * ((mSalt.Length + v - 1) / v)]; for (int j = 0; j != array3.Length; j++) { array3[j] = mSalt[j % mSalt.Length]; } } else { array3 = new byte[0]; } byte[] array4; if (mPassword != null && mPassword.Length != 0) { array4 = new byte[v * ((mPassword.Length + v - 1) / v)]; for (int k = 0; k != array4.Length; k++) { array4[k] = mPassword[k % mPassword.Length]; } } else { array4 = new byte[0]; } byte[] array5 = new byte[array3.Length + array4.Length]; Array.Copy(array3, 0, array5, 0, array3.Length); Array.Copy(array4, 0, array5, array3.Length, array4.Length); byte[] array6 = new byte[v]; int num = (n + u - 1) / u; byte[] array7 = new byte[u]; for (int l = 1; l <= num; l++) { digest.BlockUpdate(array, 0, array.Length); digest.BlockUpdate(array5, 0, array5.Length); digest.DoFinal(array7, 0); for (int m = 1; m != mIterationCount; m++) { digest.BlockUpdate(array7, 0, array7.Length); digest.DoFinal(array7, 0); } for (int num2 = 0; num2 != array6.Length; num2++) { array6[num2] = array7[num2 % array7.Length]; } for (int num3 = 0; num3 != array5.Length / v; num3++) { Adjust(array5, num3 * v, array6); } if (l == num) { Array.Copy(array7, 0, array2, (l - 1) * u, array2.Length - (l - 1) * u); } else { Array.Copy(array7, 0, array2, (l - 1) * u, array7.Length); } } return(array2); }
/// <summary> /// Generates the KDF parameters. /// Sess Sections 7 & 8 of RFC 6637 (http://tools.ietf.org/html/rfc6637) for more details /// </summary> /// <returns></returns> private void UpdateDigestWithKDFParameters(IDigest digest) { var agreement = new ECDHBasicAgreement(); agreement.Init(_privateKey); var zb = agreement.CalculateAgreement(_publicKey).ToByteArrayUnsigned(); digest.Update(0x00); digest.Update(0x00); digest.Update(0x00); digest.Update(0x01); digest.BlockUpdate(zb, 0, zb.Length); var oid = _publicKey.PublicKeyParamSet.ToBytes(); digest.Update((byte)oid.Length); digest.BlockUpdate(oid, 0, oid.Length); digest.Update((byte)PublicKeyAlgorithmTag.Ecdh); digest.Update(0x3); digest.Update(0x1); digest.Update((byte)_publicKey.HashAlgorithm); digest.Update((byte)_publicKey.SymmetricKeyAlgorithm); digest.BlockUpdate(_anonymousSender, 0, _anonymousSender.Length); digest.BlockUpdate(_fingerPrint, 0, _fingerPrint.Length); }
public static byte[] Digest(Stream data, IDigest messageDigest) { byte[] buf = new byte[8192]; int n; while ((n = data.Read(buf, 0, buf.Length)) > 0) { messageDigest.BlockUpdate(buf, 0, n); } byte[] r = new byte[messageDigest.GetDigestSize()]; messageDigest.DoFinal(r, 0); return r; }
/** * Computes the final Key according to the standard routine: Key = H(S) * @param digest The Digest used as the hashing function H * @param N Modulus used to get the pad length * @param S The secret calculated by both sides * @return */ public static BigInteger CalculateKey(IDigest digest, BigInteger N, BigInteger S) { int padLength = (N.BitLength + 7) / 8; byte[] _S = GetPadded(S, padLength); digest.BlockUpdate(_S, 0, _S.Length); byte[] output = new byte[digest.GetDigestSize()]; digest.DoFinal(output, 0); return new BigInteger(1, output); }
private void DigestTest(IDigest Digest, string[] Expected) { byte[] hash = new byte[Digest.DigestSize]; for (int i = 0; i != _messages.Length; i++) { if (_messages.Length != 0) { byte[] data = HexConverter.Decode(_messages[i]); Digest.BlockUpdate(data, 0, data.Length); } Digest.DoFinal(hash, 0); if (Compare.AreEqual(HexConverter.Decode(Expected[i]), hash) == false) throw new Exception("Keccak: Expected hash is not equal! Expected: " + Expected[i] + " Received: " + HexConverter.ToString(hash)); } byte[] k64 = new byte[1024 * 64]; for (int i = 0; i != k64.Length; i++) k64[i] = (byte)'a'; Digest.BlockUpdate(k64, 0, k64.Length); Digest.DoFinal(hash, 0); if (Compare.AreEqual(HexConverter.Decode(Expected[_messages.Length]), hash) == false) throw new Exception("Keccak: Expected hash is not equal! Expected: " + Expected[_messages.Length] + " Received: " + HexConverter.ToString(hash)); for (int i = 0; i != k64.Length; i++) Digest.Update((byte)'a'); Digest.DoFinal(hash, 0); if (Compare.AreEqual(HexConverter.Decode(Expected[_messages.Length]), hash) == false) throw new Exception("Keccak: Expected hash is not equal! Expected: " + Expected[_messages.Length] + " Received: " + HexConverter.ToString(hash)); for (int i = 0; i != k64.Length; i++) k64[i] = (byte)('a' + (i % 26)); Digest.BlockUpdate(k64, 0, k64.Length); Digest.DoFinal(hash, 0); if (Compare.AreEqual(HexConverter.Decode(Expected[_messages.Length + 1]), hash) == false) throw new Exception("Keccak: Expected hash is not equal! Expected: " + Expected[_messages.Length + 1] + " Received: " + HexConverter.ToString(hash)); for (int i = 0; i != 64; i++) { Digest.Update(k64[i * 1024]); Digest.BlockUpdate(k64, i * 1024 + 1, 1023); } Digest.DoFinal(hash, 0); if (Compare.AreEqual(HexConverter.Decode(Expected[_messages.Length + 1]), hash) == false) throw new Exception("Keccak: Expected hash is not equal! Expected: " + Expected[_messages.Length + 1] + " Received: " + HexConverter.ToString(hash)); DoFinalTest(Digest); /*// very long test (passes) for (int i = 0; i != 16384; i++) { for (int j = 0; j != 1024; j++) Digest.BlockUpdate(_xtremeData, 0, _xtremeData.Length); } Digest.DoFinal(hash, 0); if (Compare.AreEqual(HexConverter.Decode(Expected[_messages.Length + 2]), hash) == false) throw new Exception("Keccak: Expected hash is not equal! Expected: " + Expected[_messages.Length + 2] + " Received: " + hash);*/ }
private void TestDigest(IDigest digest, string[] expected) { byte[] hash = new byte[digest.GetDigestSize()]; for (int i = 0; i != messages.Length; i++) { if (messages.Length != 0) { byte[] data = Hex.Decode(messages[i]); digest.BlockUpdate(data, 0, data.Length); } digest.DoFinal(hash, 0); if (!Arrays.AreEqual(Hex.Decode(expected[i]), hash)) { Fail("sha3 mismatch on " + digest.AlgorithmName + " index " + i); } } byte[] k64 = new byte[1024 * 64]; for (int i = 0; i != k64.Length; i++) { k64[i] = (byte)'a'; } digest.BlockUpdate(k64, 0, k64.Length); digest.DoFinal(hash, 0); if (!Arrays.AreEqual(Hex.Decode(expected[messages.Length]), hash)) { Fail("sha3 mismatch on " + digest.AlgorithmName + " 64k a"); } for (int i = 0; i != k64.Length; i++) { digest.Update((byte)'a'); } digest.DoFinal(hash, 0); if (!Arrays.AreEqual(Hex.Decode(expected[messages.Length]), hash)) { Fail("sha3 mismatch on " + digest.AlgorithmName + " 64k a single"); } for (int i = 0; i != k64.Length; i++) { k64[i] = (byte)('a' + (i % 26)); } digest.BlockUpdate(k64, 0, k64.Length); digest.DoFinal(hash, 0); if (!Arrays.AreEqual(Hex.Decode(expected[messages.Length + 1]), hash)) { Fail("sha3 mismatch on " + digest.AlgorithmName + " 64k alpha"); } for (int i = 0; i != 64; i++) { digest.Update(k64[i * 1024]); digest.BlockUpdate(k64, i * 1024 + 1, 1023); } digest.DoFinal(hash, 0); if (!Arrays.AreEqual(Hex.Decode(expected[messages.Length + 1]), hash)) { Fail("sha3 mismatch on " + digest.AlgorithmName + " 64k chunked alpha"); } TestDigestDoFinal(digest); // // extremely long data test // //Console.WriteLine("Starting very long"); //for (int i = 0; i != 16384; i++) //{ // for (int j = 0; j != 1024; j++) // { // digest.BlockUpdate(xtremeData, 0, xtremeData.Length); // } //} //digest.DoFinal(hash, 0); //if (!Arrays.AreEqual(Hex.Decode(expected[messages.Length + 2]), hash)) //{ // Fail("sha3 mismatch on " + digest.AlgorithmName + " extreme data test"); //} //Console.WriteLine("Done"); }
/// <summary> /// Computes hash of the data /// </summary> /// <param name="digest">Hash algorithm implementation</param> /// <param name="data">Data that should be processed</param> /// <returns>Hash of data</returns> private static byte[] ComputeDigest(IDigest digest, byte[] data) { if (digest == null) throw new ArgumentNullException("digest"); if (data == null) throw new ArgumentNullException("data"); byte[] hash = new byte[digest.GetDigestSize()]; digest.Reset(); digest.BlockUpdate(data, 0, data.Length); digest.DoFinal(hash, 0); return hash; }
private void DoTestHMacDetECDsa(IDsa detSigner, IDigest digest, byte[] data, ICipherParameters privKey, BigInteger r, BigInteger s) { byte[] m = new byte[digest.GetDigestSize()]; digest.BlockUpdate(data, 0, data.Length); digest.DoFinal(m, 0); detSigner.Init(true, privKey); BigInteger[] rs = detSigner.GenerateSignature(m); if (!r.Equals(rs[0])) { Fail("r value wrong"); } if (!s.Equals(rs[1])) { Fail("s value wrong"); } }
private void Init() { IBcpgKey key = publicPk.Key; if (publicPk.Version <= 3) { RsaPublicBcpgKey rK = (RsaPublicBcpgKey)key; this.keyId = rK.Modulus.LongValue; try { IDigest digest = DigestUtilities.GetDigest("MD5"); byte[] bytes = rK.Modulus.ToByteArrayUnsigned(); digest.BlockUpdate(bytes, 0, bytes.Length); bytes = rK.PublicExponent.ToByteArrayUnsigned(); digest.BlockUpdate(bytes, 0, bytes.Length); this.fingerprint = DigestUtilities.DoFinal(digest); } //catch (NoSuchAlgorithmException) catch (Exception e) { throw new IOException("can't find MD5", e); } this.keyStrength = rK.Modulus.BitLength; } else { byte[] kBytes = publicPk.GetEncodedContents(); try { IDigest digest = DigestUtilities.GetDigest("SHA1"); digest.Update(0x99); digest.Update((byte)(kBytes.Length >> 8)); digest.Update((byte)kBytes.Length); digest.BlockUpdate(kBytes, 0, kBytes.Length); this.fingerprint = DigestUtilities.DoFinal(digest); } catch (Exception e) { throw new IOException("can't find SHA1", e); } this.keyId = (long)(((ulong)fingerprint[fingerprint.Length - 8] << 56) | ((ulong)fingerprint[fingerprint.Length - 7] << 48) | ((ulong)fingerprint[fingerprint.Length - 6] << 40) | ((ulong)fingerprint[fingerprint.Length - 5] << 32) | ((ulong)fingerprint[fingerprint.Length - 4] << 24) | ((ulong)fingerprint[fingerprint.Length - 3] << 16) | ((ulong)fingerprint[fingerprint.Length - 2] << 8) | (ulong)fingerprint[fingerprint.Length - 1]); if (key is RsaPublicBcpgKey) { this.keyStrength = ((RsaPublicBcpgKey)key).Modulus.BitLength; } else if (key is DsaPublicBcpgKey) { this.keyStrength = ((DsaPublicBcpgKey)key).P.BitLength; } else if (key is ElGamalPublicBcpgKey) { this.keyStrength = ((ElGamalPublicBcpgKey)key).P.BitLength; } } }
private void DigestTest(IDigest Digest) { byte[] hash = new byte[Digest.DigestSize]; int index = hash.Length == 64 ? 1 : 0; for (int i = 0; i < _input.Length; i++) { if (_input[i].Length != 0) { byte[] data = Encoding.ASCII.GetBytes(_input[i]); Digest.BlockUpdate(data, 0, data.Length); } Digest.DoFinal(hash, 0); if (Compare.AreEqual(_expected[index, i], hash) == false) throw new Exception("SHA2Vector: Expected hash is not equal! Expected: " + HexConverter.ToString(_expected[index, i]) + " Received: " + HexConverter.ToString(hash)); } }
public static byte[] Digest(IDigest d, byte[] b, int offset, int len) { d.BlockUpdate(b, offset, len); byte[] r = new byte[d.GetDigestSize()]; d.DoFinal(r, 0); return r; }
public virtual void UpdateWithRecoveredMessage( byte[] signature) { byte[] block = cipher.ProcessBlock(signature, 0, signature.Length); if (((block[0] & 0xC0) ^ 0x40) != 0) { throw new InvalidCipherTextException("malformed signature"); } if (((block[block.Length - 1] & 0xF) ^ 0xC) != 0) { throw new InvalidCipherTextException("malformed signature"); } int delta = 0; if (((block[block.Length - 1] & 0xFF) ^ 0xBC) == 0) { delta = 1; } else { int sigTrail = ((block[block.Length - 2] & 0xFF) << 8) | (block[block.Length - 1] & 0xFF); string digestName = digest.AlgorithmName; if (!trailerMap.Contains(digestName)) { throw new ArgumentException("unrecognised hash in signature"); } if (sigTrail != (int)trailerMap[digestName]) { throw new InvalidOperationException("signer initialised with wrong digest for trailer " + sigTrail); } delta = 2; } // // find out how much padding we've got // int mStart = 0; for (mStart = 0; mStart != block.Length; mStart++) { if (((block[mStart] & 0x0f) ^ 0x0a) == 0) { break; } } mStart++; int off = block.Length - delta - digest.GetDigestSize(); // // there must be at least one byte of message string // if ((off - mStart) <= 0) { throw new InvalidCipherTextException("malformed block"); } // // if we contain the whole message as well, check the hash of that. // if ((block[0] & 0x20) == 0) { fullMessage = true; recoveredMessage = new byte[off - mStart]; Array.Copy(block, mStart, recoveredMessage, 0, recoveredMessage.Length); } else { fullMessage = false; recoveredMessage = new byte[off - mStart]; Array.Copy(block, mStart, recoveredMessage, 0, recoveredMessage.Length); } preSig = signature; preBlock = block; digest.BlockUpdate(recoveredMessage, 0, recoveredMessage.Length); messageLength = recoveredMessage.Length; recoveredMessage.CopyTo(mBuf, 0); }
private byte[] SignEcDsa(IDigest digest, byte[] buffer, int length) { int digestSize = digest.GetDigestSize(); ECDsaSigner signer = new ECDsaSigner(); signer.Init(true, new ParametersWithRandom(PrivateKeyFactory.CreateKey(PrivateKey), _secureRandom)); digest.BlockUpdate(buffer, 0, length); byte[] hash = new byte[digest.GetDigestSize()]; digest.DoFinal(hash, 0); var signature = signer.GenerateSignature(hash); byte[] res = new byte[digestSize * 2]; signature[0].ToByteArrayUnsigned().CopyTo(res, 0); signature[1].ToByteArrayUnsigned().CopyTo(res, digestSize); return res; }
/** * fill len bytes of the output buffer with bytes generated from * the derivation function. * * @throws ArgumentException if the size of the request will cause an overflow. * @throws DataLengthException if the out buffer is too small. */ public virtual int GenerateBytes(byte[] output, int outOff, int length) { if ((output.Length - length) < outOff) { throw new DataLengthException("output buffer too small"); } long oBytes = length; int outLen = digest.GetDigestSize(); // // this is at odds with the standard implementation, the // maximum value should be hBits * (2^32 - 1) where hBits // is the digest output size in bits. We can't have an // array with a long index at the moment... // if (oBytes > ((2L << 32) - 1)) { throw new ArgumentException("Output length too large"); } int cThreshold = (int)((oBytes + outLen - 1) / outLen); byte[] dig = new byte[digest.GetDigestSize()]; byte[] C = new byte[4]; Pack.UInt32_To_BE((uint)counterStart, C, 0); uint counterBase = (uint)(counterStart & ~0xFF); for (int i = 0; i < cThreshold; i++) { digest.BlockUpdate(shared, 0, shared.Length); digest.BlockUpdate(C, 0, 4); if (iv != null) { digest.BlockUpdate(iv, 0, iv.Length); } digest.DoFinal(dig, 0); if (length > outLen) { Array.Copy(dig, 0, output, outOff, outLen); outOff += outLen; length -= outLen; } else { Array.Copy(dig, 0, output, outOff, length); } if (++C[3] == 0) { counterBase += 0x100; Pack.UInt32_To_BE(counterBase, C, 0); } } digest.Reset(); return((int)oBytes); }
public PdfDictionary GetEncryptionDictionary() { PdfDictionary dic = new PdfDictionary(); if (publicKeyHandler.GetRecipientsSize() > 0) { PdfArray recipients = null; dic.Put(PdfName.FILTER, PdfName.PUBSEC); dic.Put(PdfName.R, new PdfNumber(revision)); recipients = publicKeyHandler.GetEncodedRecipients(); if (revision == STANDARD_ENCRYPTION_40) { dic.Put(PdfName.V, new PdfNumber(1)); dic.Put(PdfName.SUBFILTER, PdfName.ADBE_PKCS7_S4); dic.Put(PdfName.RECIPIENTS, recipients); } else if (revision == STANDARD_ENCRYPTION_128 && encryptMetadata) { dic.Put(PdfName.V, new PdfNumber(2)); dic.Put(PdfName.LENGTH, new PdfNumber(128)); dic.Put(PdfName.SUBFILTER, PdfName.ADBE_PKCS7_S4); dic.Put(PdfName.RECIPIENTS, recipients); } else { dic.Put(PdfName.R, new PdfNumber(AES_128)); dic.Put(PdfName.V, new PdfNumber(4)); dic.Put(PdfName.SUBFILTER, PdfName.ADBE_PKCS7_S5); PdfDictionary stdcf = new PdfDictionary(); stdcf.Put(PdfName.RECIPIENTS, recipients); if (!encryptMetadata) { stdcf.Put(PdfName.ENCRYPTMETADATA, PdfBoolean.PDFFALSE); } if (revision == AES_128) { stdcf.Put(PdfName.CFM, PdfName.AESV2); } else { stdcf.Put(PdfName.CFM, PdfName.V2); } PdfDictionary cf = new PdfDictionary(); cf.Put(PdfName.DEFAULTCRYPTFILTER, stdcf); dic.Put(PdfName.CF, cf); if (embeddedFilesOnly) { dic.Put(PdfName.EFF, PdfName.DEFAULTCRYPTFILTER); dic.Put(PdfName.STRF, PdfName.IDENTITY); dic.Put(PdfName.STMF, PdfName.IDENTITY); } else { dic.Put(PdfName.STRF, PdfName.DEFAULTCRYPTFILTER); dic.Put(PdfName.STMF, PdfName.DEFAULTCRYPTFILTER); } } IDigest sh = DigestUtilities.GetDigest("SHA1"); byte[] encodedRecipient = null; byte[] seed = publicKeyHandler.GetSeed(); sh.BlockUpdate(seed, 0, seed.Length); for (int i = 0; i < publicKeyHandler.GetRecipientsSize(); i++) { encodedRecipient = publicKeyHandler.GetEncodedRecipient(i); sh.BlockUpdate(encodedRecipient, 0, encodedRecipient.Length); } if (!encryptMetadata) { sh.BlockUpdate(metadataPad, 0, metadataPad.Length); } byte[] mdResult = new byte[sh.GetDigestSize()]; sh.DoFinal(mdResult, 0); SetupByEncryptionKey(mdResult, keyLength); } else { dic.Put(PdfName.FILTER, PdfName.STANDARD); dic.Put(PdfName.O, new PdfLiteral(PdfContentByte.EscapeString(ownerKey))); dic.Put(PdfName.U, new PdfLiteral(PdfContentByte.EscapeString(userKey))); dic.Put(PdfName.P, new PdfNumber(permissions)); dic.Put(PdfName.R, new PdfNumber(revision)); if (revision == STANDARD_ENCRYPTION_40) { dic.Put(PdfName.V, new PdfNumber(1)); } else if (revision == STANDARD_ENCRYPTION_128 && encryptMetadata) { dic.Put(PdfName.V, new PdfNumber(2)); dic.Put(PdfName.LENGTH, new PdfNumber(128)); } else if (revision == AES_256) { if (!encryptMetadata) { dic.Put(PdfName.ENCRYPTMETADATA, PdfBoolean.PDFFALSE); } dic.Put(PdfName.OE, new PdfLiteral(PdfContentByte.EscapeString(oeKey))); dic.Put(PdfName.UE, new PdfLiteral(PdfContentByte.EscapeString(ueKey))); dic.Put(PdfName.PERMS, new PdfLiteral(PdfContentByte.EscapeString(perms))); dic.Put(PdfName.V, new PdfNumber(revision)); dic.Put(PdfName.LENGTH, new PdfNumber(256)); PdfDictionary stdcf = new PdfDictionary(); stdcf.Put(PdfName.LENGTH, new PdfNumber(32)); if (embeddedFilesOnly) { stdcf.Put(PdfName.AUTHEVENT, PdfName.EFOPEN); dic.Put(PdfName.EFF, PdfName.STDCF); dic.Put(PdfName.STRF, PdfName.IDENTITY); dic.Put(PdfName.STMF, PdfName.IDENTITY); } else { stdcf.Put(PdfName.AUTHEVENT, PdfName.DOCOPEN); dic.Put(PdfName.STRF, PdfName.STDCF); dic.Put(PdfName.STMF, PdfName.STDCF); } stdcf.Put(PdfName.CFM, PdfName.AESV3); PdfDictionary cf = new PdfDictionary(); cf.Put(PdfName.STDCF, stdcf); dic.Put(PdfName.CF, cf); } else { if (!encryptMetadata) { dic.Put(PdfName.ENCRYPTMETADATA, PdfBoolean.PDFFALSE); } dic.Put(PdfName.R, new PdfNumber(AES_128)); dic.Put(PdfName.V, new PdfNumber(4)); dic.Put(PdfName.LENGTH, new PdfNumber(128)); PdfDictionary stdcf = new PdfDictionary(); stdcf.Put(PdfName.LENGTH, new PdfNumber(16)); if (embeddedFilesOnly) { stdcf.Put(PdfName.AUTHEVENT, PdfName.EFOPEN); dic.Put(PdfName.EFF, PdfName.STDCF); dic.Put(PdfName.STRF, PdfName.IDENTITY); dic.Put(PdfName.STMF, PdfName.IDENTITY); } else { stdcf.Put(PdfName.AUTHEVENT, PdfName.DOCOPEN); dic.Put(PdfName.STRF, PdfName.STDCF); dic.Put(PdfName.STMF, PdfName.STDCF); } if (revision == AES_128) { stdcf.Put(PdfName.CFM, PdfName.AESV2); } else { stdcf.Put(PdfName.CFM, PdfName.V2); } PdfDictionary cf = new PdfDictionary(); cf.Put(PdfName.STDCF, stdcf); dic.Put(PdfName.CF, cf); } } return(dic); }
private static void UpdateDigestIncludingSize(IDigest digest, byte[] bytes) { digest.BlockUpdate(IntToByteArray(bytes.Length), 0, 4); digest.BlockUpdate(bytes, 0, bytes.Length); Arrays.Fill(bytes, (byte)0); }
public bool Match( // Certificate cert) X509Certificate x509Cert) { // if (!(cert is X509Certificate)) // { // return false; // } // // X509Certificate x509Cert = (X509Certificate)cert; try { if (holder.BaseCertificateID != null) { return(holder.BaseCertificateID.Serial.Value.Equals(x509Cert.SerialNumber) && MatchesDN(PrincipalUtilities.GetIssuerX509Principal(x509Cert), holder.BaseCertificateID.Issuer)); } if (holder.EntityName != null) { if (MatchesDN(PrincipalUtilities.GetSubjectX509Principal(x509Cert), holder.EntityName)) { return(true); } } if (holder.ObjectDigestInfo != null) { IDigest md = null; try { md = DigestUtilities.GetDigest(DigestAlgorithm); } catch (Exception) { return(false); } switch (DigestedObjectType) { case ObjectDigestInfo.PublicKey: { // TODO: DSA Dss-parms //byte[] b = x509Cert.GetPublicKey().getEncoded(); // TODO Is this the right way to encode? byte[] b = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo( x509Cert.GetPublicKey()).GetEncoded(); md.BlockUpdate(b, 0, b.Length); break; } case ObjectDigestInfo.PublicKeyCert: { byte[] b = x509Cert.GetEncoded(); md.BlockUpdate(b, 0, b.Length); break; } // TODO Default handler? } // TODO Shouldn't this be the other way around? if (!Arrays.AreEqual(DigestUtilities.DoFinal(md), GetObjectDigest())) { return(false); } } } catch (CertificateEncodingException) { return(false); } return(false); }
protected virtual void PerformTest() { byte[] resBuf = new byte[_digest.GetDigestSize()]; for (int i = 0; i < _input.Length - 1; i++) { byte[] msg = toByteArray(_input[i]); vectorTest(_digest, i, resBuf, msg, Hex.Decode(_results[i])); } byte[] lastV = toByteArray(_input[_input.Length - 1]); byte[] lastDigest = Hex.Decode(_results[_input.Length - 1]); vectorTest(_digest, _input.Length - 1, resBuf, lastV, Hex.Decode(_results[_input.Length - 1])); // // clone test // _digest.BlockUpdate(lastV, 0, lastV.Length / 2); // clone the Digest IDigest d = CloneDigest(_digest); _digest.BlockUpdate(lastV, lastV.Length / 2, lastV.Length - lastV.Length / 2); _digest.DoFinal(resBuf, 0); Assert.AreEqual(lastDigest, resBuf, string.Format("fail clone vector test, expected {0} but got {1}", _results[_results.Length - 1], Hex.ToHexString(resBuf))); d.BlockUpdate(lastV, lastV.Length / 2, lastV.Length - lastV.Length / 2); d.DoFinal(resBuf, 0); Assert.AreEqual(lastDigest, resBuf, string.Format("fail second clone vector test, expected {0} but got {1}", _results[_results.Length - 1], Hex.ToHexString(resBuf))); // // memo test // IMemoable m = (IMemoable)_digest; _digest.BlockUpdate(lastV, 0, lastV.Length / 2); // copy the Digest IMemoable copy1 = m.Copy(); IMemoable copy2 = copy1.Copy(); _digest.BlockUpdate(lastV, lastV.Length / 2, lastV.Length - lastV.Length / 2); _digest.DoFinal(resBuf, 0); Assert.AreEqual(lastDigest, resBuf, string.Format("fail memo vector test, expected {0} but got {1}", _results[_results.Length - 1], Hex.ToHexString(resBuf))); m.Reset(copy1); _digest.BlockUpdate(lastV, lastV.Length / 2, lastV.Length - lastV.Length / 2); _digest.DoFinal(resBuf, 0); Assert.AreEqual(lastDigest, resBuf, string.Format("fail memo reset vector test, expected {0} but got {1}", _results[_results.Length - 1], Hex.ToHexString(resBuf))); IDigest md = (IDigest)copy2; md.BlockUpdate(lastV, lastV.Length / 2, lastV.Length - lastV.Length / 2); md.DoFinal(resBuf, 0); Assert.AreEqual(lastDigest, resBuf, string.Format("fail memo copy vector test, expected {0} but got {1}", _results[_results.Length - 1], Hex.ToHexString(resBuf))); }
public byte[] Decrypt(byte[] Input) { if (m_isEncryption) { throw new CryptoAsymmetricException("PointchevalCipher:Decrypt", "The cipher is not initialized for decryption!", new ArgumentException()); } int c1Len = (m_N + 7) >> 3; int c2Len = Input.Length - c1Len; // split cipher text (c1||c2) byte[][] c1c2 = ByteUtils.Split(Input, c1Len); byte[] c1 = c1c2[0]; byte[] c2 = c1c2[1]; // decrypt c1 ... GF2Vector c1Vec = GF2Vector.OS2VP(m_N, c1); GF2Vector[] c1Dec = CCA2Primitives.Decrypt((MPKCPrivateKey)m_asmKey, c1Vec); byte[] rPrimeBytes = c1Dec[0].GetEncoded(); // ... and obtain error vector z GF2Vector z = c1Dec[1]; byte[] mrBytes; // get PRNG object using (KDF2 sr0 = new KDF2(GetDigest(m_cprParams.Digest))) { // seed PRNG with r' sr0.Initialize(rPrimeBytes); // generate random sequence mrBytes = new byte[c2Len]; sr0.Generate(mrBytes); } // XOR with c2 to obtain (m||r) for (int i = 0; i < c2Len; i++) { mrBytes[i] ^= c2[i]; } // compute H(m||r) m_dgtEngine.BlockUpdate(mrBytes, 0, mrBytes.Length); byte[] hmr = new byte[m_dgtEngine.DigestSize]; m_dgtEngine.DoFinal(hmr, 0); // compute Conv(H(m||r)) c1Vec = CCA2Conversions.Encode(m_N, m_T, hmr); // check that Conv(H(m||r)) = z if (!c1Vec.Equals(z)) { throw new CryptoAsymmetricException("PointchevalCipher:Decrypt", "Bad Padding: Invalid ciphertext!", new ArgumentException()); } // split (m||r) to obtain m int kDiv8 = m_K >> 3; byte[][] mr = ByteUtils.Split(mrBytes, c2Len - kDiv8); // return plain text m return(mr[0]); }
protected virtual void Ssl3Complete(IDigest d, byte[] ipad, byte[] opad, int padLength) { byte[] master_secret = mContext.SecurityParameters.masterSecret; d.BlockUpdate(master_secret, 0, master_secret.Length); d.BlockUpdate(ipad, 0, padLength); byte[] tmp = DigestUtilities.DoFinal(d); d.BlockUpdate(master_secret, 0, master_secret.Length); d.BlockUpdate(opad, 0, padLength); d.BlockUpdate(tmp, 0, tmp.Length); }
public static byte[] DoFinal(IDigest digest, byte[] input) { digest.BlockUpdate(input, 0, input.Length); return(DoFinal(digest)); }
/** * generation of a derived key ala Pkcs12 V1.0. */ private byte[] GenerateDerivedKey( int idByte, int n) { byte[] D = new byte[v]; byte[] dKey = new byte[n]; for (int i = 0; i != D.Length; i++) { D[i] = (byte)idByte; } byte[] S; if ((mSalt != null) && (mSalt.Length != 0)) { S = new byte[v * ((mSalt.Length + v - 1) / v)]; for (int i = 0; i != S.Length; i++) { S[i] = mSalt[i % mSalt.Length]; } } else { S = new byte[0]; } byte[] P; if ((mPassword != null) && (mPassword.Length != 0)) { P = new byte[v * ((mPassword.Length + v - 1) / v)]; for (int i = 0; i != P.Length; i++) { P[i] = mPassword[i % mPassword.Length]; } } else { P = new byte[0]; } byte[] I = new byte[S.Length + P.Length]; Array.Copy(S, 0, I, 0, S.Length); Array.Copy(P, 0, I, S.Length, P.Length); byte[] B = new byte[v]; int c = (n + u - 1) / u; byte[] A = new byte[u]; for (int i = 1; i <= c; i++) { digest.BlockUpdate(D, 0, D.Length); digest.BlockUpdate(I, 0, I.Length); digest.DoFinal(A, 0); for (int j = 1; j != mIterationCount; j++) { digest.BlockUpdate(A, 0, A.Length); digest.DoFinal(A, 0); } for (int j = 0; j != B.Length; j++) { B[j] = A[j % A.Length]; } for (int j = 0; j != I.Length / v; j++) { Adjust(I, j * v, B); } if (i == c) { Array.Copy(A, 0, dKey, (i - 1) * u, dKey.Length - ((i - 1) * u)); } else { Array.Copy(A, 0, dKey, (i - 1) * u, A.Length); } } return(dKey); }
public virtual int GenerateBytes(byte[] outBytes, int outOff, int len) { if ((outBytes.Length - len) < outOff) { throw new DataLengthException("output buffer too small"); } long oBytes = len; int outLen = digest.GetDigestSize(); // // this is at odds with the standard implementation, the // maximum value should be hBits * (2^32 - 1) where hBits // is the digest output size in bits. We can't have an // array with a long index at the moment... // if (oBytes > ((2L << 32) - 1)) { throw new ArgumentException("Output length too large"); } int cThreshold = (int)((oBytes + outLen - 1) / outLen); byte[] dig = new byte[digest.GetDigestSize()]; uint counter = 1; for (int i = 0; i < cThreshold; i++) { digest.BlockUpdate(z, 0, z.Length); // KeySpecificInfo DerSequence keyInfo = new DerSequence( algorithm, new DerOctetString(Pack.UInt32_To_BE(counter))); // OtherInfo Asn1EncodableVector v1 = new Asn1EncodableVector(keyInfo); if (partyAInfo != null) { v1.Add(new DerTaggedObject(true, 0, new DerOctetString(partyAInfo))); } v1.Add(new DerTaggedObject(true, 2, new DerOctetString(Pack.UInt32_To_BE((uint)keySize)))); byte[] other = new DerSequence(v1).GetDerEncoded(); digest.BlockUpdate(other, 0, other.Length); digest.DoFinal(dig, 0); if (len > outLen) { Array.Copy(dig, 0, outBytes, outOff, outLen); outOff += outLen; len -= outLen; } else { Array.Copy(dig, 0, outBytes, outOff, len); } counter++; } digest.Reset(); return((int)oBytes); }
private void DoHash(byte[] input, byte[] output) { mDigest.BlockUpdate(input, 0, input.Length); mDigest.DoFinal(output, 0); }
private void vectorTest( IDigest digest, int count, byte[] resBuf, byte[] input, byte[] expected) { digest.BlockUpdate(input, 0, input.Length); digest.DoFinal(resBuf, 0); if (!AreEqual(resBuf, expected)) { Fail("Vector " + count + " failed got " + Hex.ToHexString(resBuf)); } }
public static void Update(this IDigest digest, byte[] input, int offset, int length) { digest.BlockUpdate(input, offset, length); }
public void BlockUpdate(byte[] input, int inOff, int length) { baseDigest.BlockUpdate(input, inOff, length); }
private void DigestTest(IDigest Digest, byte[] Input, byte[] Expected) { byte[] hash = new byte[Digest.DigestSize]; int index = hash.Length == 64 ? 1 : 0; if (Input.Length != 0) Digest.BlockUpdate(Input, 0, Input.Length); Digest.DoFinal(hash, 0); if (Compare.AreEqual(Expected, hash) == false) throw new Exception("Blake: Expected hash is not equal! Expected: " + HexConverter.ToString(Expected) + " Received: " + HexConverter.ToString(hash)); }
public virtual void BlockUpdate(byte[] input, int inOff, int len) { digest.BlockUpdate(input, inOff, len); }
public byte[] ComputeHashValueOfElementList(XmlElement signatureXmlElement, ArrayList elementXpaths) { XmlDocument xmlDocument; XmlNamespaceManager xmlNamespaceManager; XmlNodeList searchXmlNodeList; XmlElement composedXmlElement; XmlDsigExcC14NTransform xmlTransform; Stream canonicalizedStream; //SHA1 sha1Managed; byte[] retVal; xmlDocument = signatureXmlElement.OwnerDocument; composedXmlElement = xmlDocument.CreateElement("ComposedElement", SignedXml.XmlDsigNamespaceUrl); xmlNamespaceManager = new XmlNamespaceManager(xmlDocument.NameTable); xmlNamespaceManager.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl); xmlNamespaceManager.AddNamespace("xsd", XadesSignedXml.XadesNamespaceUri); foreach (string elementXpath in elementXpaths) { searchXmlNodeList = signatureXmlElement.SelectNodes(elementXpath, xmlNamespaceManager); if (searchXmlNodeList.Count == 0) { throw new CryptographicException("Element " + elementXpath + " not found while calculating hash"); } foreach (XmlNode xmlNode in searchXmlNodeList) { //jbonilla Id attr deprecated //if (((XmlElement)xmlNode).HasAttribute("Id")) //{ // elementIdValues.Add(((XmlElement)xmlNode).Attributes["Id"].Value); // composedXmlElement.AppendChild(xmlNode); //} //else //{ // throw new CryptographicException("Id attribute missing on " + xmlNode.LocalName + " element"); //} composedXmlElement.AppendChild(xmlNode); } } //Initialise the stream to read the node list MemoryStream nodeStream = new MemoryStream(); XmlWriter xw = XmlWriter.Create(nodeStream); composedXmlElement.ChildNodes[0].WriteTo(xw); xw.Flush(); nodeStream.Position = 0; //modificado xmlTransform = new XmlDsigExcC14NTransform(); xmlTransform.LoadInput(nodeStream); canonicalizedStream = (Stream)xmlTransform.GetOutput(typeof(Stream)); //sha1Managed = new SHA1Managed(); //retVal = sha1Managed.ComputeHash(canonicalizedStream); IDigest digest = this.tspSource.GetMessageDigest(); byte[] canonicalizedBytes = Streams.ReadAll(canonicalizedStream); digest.BlockUpdate(canonicalizedBytes, 0, canonicalizedBytes.Length); retVal = DigestUtilities.DoFinal(digest); canonicalizedStream.Close(); return(retVal); }
public void Sign(PDFSignatureAP sigAP, bool encrypt, PDFEncryption Enc) { PdfReader reader = new PdfReader(this.inputPDF); FileStream fs = new FileStream(this.outputPDF, FileMode.Create, FileAccess.Write); PdfStamper st; if (this.myCert == null) //No signature just write meta-data and quit { st = new PdfStamper(reader, fs); } else { st = PdfStamper.CreateSignature(reader, fs, '\0', null, sigAP.Multi); } if (encrypt && Enc != null) { Enc.Encrypt(st); } //st.SetEncryption(PdfWriter.STRENGTH128BITS, "user", "owner", PdfWriter.ALLOW_COPY); st.MoreInfo = this.metadata.getMetaData(); st.XmpMetadata = this.metadata.getStreamedMetaData(); if (this.myCert == null) //No signature just write meta-data and quit { st.Close(); return; } PdfSignatureAppearance sap = st.SignatureAppearance; //sap.SetCrypto(this.myCert.Akp, this.myCert.Chain, null, PdfSignatureAppearance.WINCER_SIGNED); sap.SetCrypto(null, this.myCert.Chain, null, PdfSignatureAppearance.SELF_SIGNED); sap.Reason = sigAP.SigReason; sap.Contact = sigAP.SigContact; sap.Location = sigAP.SigLocation; if (sigAP.Visible) { iTextSharp.text.Rectangle rect = st.Reader.GetPageSize(sigAP.Page); sap.Image = sigAP.RawData == null ? null : iTextSharp.text.Image.GetInstance(sigAP.RawData); sap.Layer2Text = sigAP.CustomText; sap.SetVisibleSignature(new iTextSharp.text.Rectangle(sigAP.SigX, sigAP.SigY, sigAP.SigX + sigAP.SigW, sigAP.SigY + sigAP.SigH), sigAP.Page, null); } ///// PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached")); dic.Reason = sap.Reason; dic.Location = sap.Location; dic.Contact = sap.Contact; dic.Date = new PdfDate(sap.SignDate); sap.CryptoDictionary = dic; int contentEstimated = 15000; // Preallocate excluded byte-range for the signature content (hex encoded) Dictionary <PdfName, int> exc = new Dictionary <PdfName, int>(); exc[PdfName.CONTENTS] = contentEstimated * 2 + 2; sap.PreClose(exc); PdfPKCS7 sgn = new PdfPKCS7(this.myCert.Akp, this.myCert.Chain, null, "SHA1", false); IDigest messageDigest = DigestUtilities.GetDigest("SHA1"); Stream data = sap.GetRangeStream(); 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); DateTime cal = DateTime.Now; byte[] ocsp = null; if (this.myCert.Chain.Length >= 2) { String url = PdfPKCS7.GetOCSPURL(this.myCert.Chain[0]); if (url != null && url.Length > 0) { ocsp = new OcspClientBouncyCastle().GetEncoded(this.myCert.Chain[0], this.myCert.Chain[1], url); } } byte[] sh = sgn.GetAuthenticatedAttributeBytes(hash, cal, ocsp); sgn.Update(sh, 0, sh.Length); byte[] paddedSig = new byte[contentEstimated]; if (this.myCert.Tsc != null) { byte[] encodedSigTsa = sgn.GetEncodedPKCS7(hash, cal, this.myCert.Tsc, ocsp); System.Array.Copy(encodedSigTsa, 0, paddedSig, 0, encodedSigTsa.Length); if (contentEstimated + 2 < encodedSigTsa.Length) { throw new Exception("Not enough space for signature"); } } else { byte[] encodedSig = sgn.GetEncodedPKCS7(hash, cal); System.Array.Copy(encodedSig, 0, paddedSig, 0, encodedSig.Length); if (contentEstimated + 2 < encodedSig.Length) { throw new Exception("Not enough space for signature"); } } PdfDictionary dic2 = new PdfDictionary(); dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true)); sap.Close(dic2); ////// //st.Close(); }
public void BlockUpdate(byte[] input, int inOff, int length) { _hash.BlockUpdate(input, inOff, length); }
public static void Update(this IDigest digest, byte[] input) { digest.BlockUpdate(input, 0, input.Length); }
private bool VerifyEcDsa(IDigest digest, X9ECParameters curveParameter, byte[] buffer, int length, byte[] signature) { int digestSize = digest.GetDigestSize(); ECDomainParameters dParams = new ECDomainParameters( curveParameter.Curve, curveParameter.G, curveParameter.N, curveParameter.H, curveParameter.GetSeed()); ECPoint q = dParams.Curve.CreatePoint(new BigInteger(1, PublicKey, 0, digestSize), new BigInteger(1, PublicKey, digestSize, digestSize), false); ECPublicKeyParameters parameters = new ECPublicKeyParameters(q, dParams); var signer = new ECDsaSigner(); signer.Init(false, parameters); digest.BlockUpdate(buffer, 0, length); byte[] hash = new byte[digest.GetDigestSize()]; digest.DoFinal(hash, 0); return signer.VerifySignature(hash, new BigInteger(1, signature, 0, digestSize), new BigInteger(1, signature, digestSize, digestSize)); }
/// <summary> update the internal digest with the byte array in</summary> public virtual void BlockUpdate( byte[] input, int inOff, int length) { if (preSig == null) { while (length > 0 && messageLength < mBuf.Length) { this.Update(input[inOff]); inOff++; length--; } } if (length > 0) { digest.BlockUpdate(input, inOff, length); } }
public static byte[] DoFinal( IDigest digest, byte[] input) { digest.BlockUpdate(input, 0, input.Length); return DoFinal(digest); }