Exemplo n.º 1
0
 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);
 }
Exemplo n.º 2
0
		/// <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);
		}
Exemplo n.º 3
0
 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);
 }
Exemplo n.º 5
0
	    /**
	     * 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;
	    }
Exemplo n.º 6
0
        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;
        }
Exemplo n.º 7
0
 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);
 }
Exemplo n.º 8
0
		/// <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 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);
        }
Exemplo n.º 10
0
        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);
        }
Exemplo n.º 11
0
        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);
        }
Exemplo n.º 12
0
        public static byte[] GetHashRaw(Stream data, IDigest digest)
        {
            try {
                //update data
                var  buffer       = new byte[StreamHashComputingBlockSize];
                long count        = data.Length / StreamHashComputingBlockSize;
                var  remainedData = new byte[data.Length % StreamHashComputingBlockSize];
                for (int i = 0; i < count; i++)
                {
                    data.Read(buffer, 0, StreamHashComputingBlockSize);
                    digest.BlockUpdate(buffer, 0, StreamHashComputingBlockSize);
                }
                data.Read(remainedData, 0, remainedData.Length);
                digest.BlockUpdate(remainedData, 0, remainedData.Length);

                //get result
                byte[] result = new byte[digest.GetDigestSize()];
                digest.DoFinal(result, 0);
                return(result);
            } catch (Exception) {
                return(null);
            }
        }
Exemplo n.º 13
0
        public override byte[] GenerateServerKeyExchange()
        {
            mSrpServer.Init(mSrpGroup, mSrpVerifier, TlsUtilities.CreateHash(HashAlgorithm.sha1), mContext.SecureRandom);
            BigInteger B = mSrpServer.GenerateServerCredentials();

            ServerSrpParams srpParams = new ServerSrpParams(mSrpGroup.N, mSrpGroup.G, mSrpSalt, B);

            DigestInputBuffer buf = new DigestInputBuffer();

            srpParams.Encode(buf);

            if (mServerCredentials != null)
            {
                /*
                 * RFC 5246 4.7. digitally-signed element needs SignatureAndHashAlgorithm from TLS 1.2
                 */
                SignatureAndHashAlgorithm signatureAndHashAlgorithm = TlsUtilities.GetSignatureAndHashAlgorithm(
                    mContext, mServerCredentials);

                IDigest d = TlsUtilities.CreateHash(signatureAndHashAlgorithm);

                SecurityParameters securityParameters = mContext.SecurityParameters;
                d.BlockUpdate(securityParameters.clientRandom, 0, securityParameters.clientRandom.Length);
                d.BlockUpdate(securityParameters.serverRandom, 0, securityParameters.serverRandom.Length);
                buf.UpdateDigest(d);

                byte[] hash = new byte[d.GetDigestSize()];
                d.DoFinal(hash, 0);

                byte[] signature = mServerCredentials.GenerateCertificateSignature(hash);

                DigitallySigned signed_params = new DigitallySigned(signatureAndHashAlgorithm, signature);
                signed_params.Encode(buf);
            }

            return(buf.ToArray());
        }
    private byte[] GenerateDerivedKey(int bytesNeeded)
    {
        byte[] array  = new byte[digest.GetDigestSize()];
        byte[] array2 = new byte[bytesNeeded];
        int    num    = 0;

        while (true)
        {
            digest.BlockUpdate(mPassword, 0, mPassword.Length);
            digest.BlockUpdate(mSalt, 0, mSalt.Length);
            digest.DoFinal(array, 0);
            int num2 = (bytesNeeded > array.Length) ? array.Length : bytesNeeded;
            Array.Copy(array, 0, array2, num, num2);
            num         += num2;
            bytesNeeded -= num2;
            if (bytesNeeded == 0)
            {
                break;
            }
            digest.Reset();
            digest.BlockUpdate(array, 0, array.Length);
        }
        return(array2);
    }
Exemplo n.º 15
0
        public override byte[] GenerateServerKeyExchange()
        {
            mSrpServer.Init(mSrpGroup, mSrpVerifier, TlsUtilities.CreateHash(2), mContext.SecureRandom);
            BigInteger        b = mSrpServer.GenerateServerCredentials();
            ServerSrpParams   serverSrpParams   = new ServerSrpParams(mSrpGroup.N, mSrpGroup.G, mSrpSalt, b);
            DigestInputBuffer digestInputBuffer = new DigestInputBuffer();

            serverSrpParams.Encode((Stream)(object)digestInputBuffer);
            if (mServerCredentials != null)
            {
                SignatureAndHashAlgorithm signatureAndHashAlgorithm = TlsUtilities.GetSignatureAndHashAlgorithm(mContext, mServerCredentials);
                IDigest            digest             = TlsUtilities.CreateHash(signatureAndHashAlgorithm);
                SecurityParameters securityParameters = mContext.SecurityParameters;
                digest.BlockUpdate(securityParameters.clientRandom, 0, securityParameters.clientRandom.Length);
                digest.BlockUpdate(securityParameters.serverRandom, 0, securityParameters.serverRandom.Length);
                digestInputBuffer.UpdateDigest(digest);
                byte[] array = new byte[digest.GetDigestSize()];
                digest.DoFinal(array, 0);
                byte[]          signature       = mServerCredentials.GenerateCertificateSignature(array);
                DigitallySigned digitallySigned = new DigitallySigned(signatureAndHashAlgorithm, signature);
                digitallySigned.Encode((Stream)(object)digestInputBuffer);
            }
            return(((MemoryStream)digestInputBuffer).ToArray());
        }
        /// <summary> Generate a signature for the message we've been loaded with using
        /// the key we were initialised with.
        /// </summary>
        public virtual byte[] GenerateSignature()
        {
            if (emBits < (8 * hLen + 8 * sLen + 9))
            {
                throw new DataLengthException("encoding error");
            }

            digest.DoFinal(mDash, mDash.Length - hLen - sLen);

            if (sLen != 0)
            {
                random.NextBytes(salt);
                salt.CopyTo(mDash, mDash.Length - sLen);
            }

            byte[] h = new byte[hLen];

            digest.BlockUpdate(mDash, 0, mDash.Length);

            digest.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);
        }
Exemplo n.º 17
0
        private void DoFinalTest(IDigest digest)
        {
            byte[] hash = new byte[digest.DigestSize];

            digest.DoFinal(hash, 0);

            for (int i = 0; i <= digest.DigestSize; ++i)
            {
                byte[] expected = new byte[2 * digest.DigestSize];
                Array.Copy(hash, 0, expected, i, hash.Length);
                byte[] outBytes = new byte[2 * digest.DigestSize];

                digest.DoFinal(outBytes, i);

                if (Compare.AreEqual(expected, outBytes) == false)
                    throw new Exception("Keccak DoFinal: Expected hash is not equal! Expected: " + HexConverter.ToString(expected) + " Received: " + HexConverter.ToString(outBytes));
            }
        }
Exemplo n.º 18
0
        private void TestDigestDoFinal(IDigest digest)
        {
            byte[] hash = new byte[digest.GetDigestSize()];
            digest.DoFinal(hash, 0);

            for (int i = 0; i <= digest.GetDigestSize(); ++i)
            {
                byte[] cmp = new byte[2 * digest.GetDigestSize()];
                Array.Copy(hash, 0, cmp, i, hash.Length);

                byte[] buf = new byte[2 * digest.GetDigestSize()];
                digest.DoFinal(buf, i);

                if (!Arrays.AreEqual(cmp, buf))
                {
                    Fail("sha3 offset DoFinal on " + digest.AlgorithmName);
                }
            }
        }
Exemplo n.º 19
0
        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);
        }
Exemplo n.º 20
0
		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));
		}
Exemplo n.º 21
0
        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)));
        }
Exemplo n.º 22
0
        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");
        }
Exemplo n.º 23
0
        byte[] ParseServerKeyExchange(out ECCurve curve, IPublicKey pkey)
        {
            byte[] msg = ReadHandshakeMessageExpected(
                SSL.SERVER_KEY_EXCHANGE);
            if (msg.Length < 4)
            {
                throw new SSLException(
                          "Invalid ServerKeyExchange message");
            }
            if (msg[0] != 0x03)
            {
                throw new SSLException("Unsupported unnamed curve");
            }
            curve = SSL.GetCurveByID(IO.Dec16be(msg, 1));
            int plen = msg[3];
            int off  = 4;

            if (msg.Length - off < plen)
            {
                throw new SSLException(
                          "Invalid ServerKeyExchange message");
            }
            byte[] point = new byte[plen];
            Array.Copy(msg, off, point, 0, plen);
            off += plen;
            int slen = off;

            int hashId, sigId;

            if (Version >= SSL.TLS12)
            {
                if (msg.Length - off < 2)
                {
                    throw new SSLException(
                              "Invalid ServerKeyExchange message");
                }
                hashId = msg[off++];
                if (hashId == 0)
                {
                    throw new SSLException(
                              "Invalid hash identifier");
                }
                sigId = msg[off++];
            }
            else
            {
                if (pkey is RSAPublicKey)
                {
                    hashId = 0;
                    sigId  = 1;
                }
                else if (pkey is ECPublicKey)
                {
                    hashId = 2;
                    sigId  = 3;
                }
                else
                {
                    throw new SSLException(
                              "Unsupported signature key type");
                }
            }

            if (msg.Length - off < 2)
            {
                throw new SSLException(
                          "Invalid ServerKeyExchange message");
            }
            int sigLen = IO.Dec16be(msg, off);

            off += 2;
            if (sigLen != msg.Length - off)
            {
                throw new SSLException(
                          "Invalid ServerKeyExchange message");
            }
            byte[] sig = new byte[sigLen];
            Array.Copy(msg, off, sig, 0, sigLen);

            byte[] hv;
            if (hashId == 0)
            {
                MD5  md5  = new MD5();
                SHA1 sha1 = new SHA1();
                md5.Update(clientRandom);
                md5.Update(serverRandom);
                md5.Update(msg, 0, slen);
                sha1.Update(clientRandom);
                sha1.Update(serverRandom);
                sha1.Update(msg, 0, slen);
                hv = new byte[36];
                md5.DoFinal(hv, 0);
                sha1.DoFinal(hv, 16);
            }
            else
            {
                IDigest h = SSL.GetHashByID(hashId);
                h.Update(clientRandom);
                h.Update(serverRandom);
                h.Update(msg, 0, slen);
                hv = h.DoFinal();
            }

            bool ok;

            if (sigId == 1)
            {
                RSAPublicKey rpk = pkey as RSAPublicKey;
                if (rpk == null)
                {
                    throw new SSLException(
                              "Wrong public key type for RSA");
                }
                if (hashId == 0)
                {
                    ok = RSA.VerifyND(rpk, hv, sig);
                }
                else
                {
                    byte[] head1, head2;

                    switch (hashId)
                    {
                    case 1:
                        head1 = RSA.PKCS1_MD5;
                        head2 = RSA.PKCS1_MD5_ALT;
                        break;

                    case 2:
                        head1 = RSA.PKCS1_SHA1;
                        head2 = RSA.PKCS1_SHA1_ALT;
                        break;

                    case 3:
                        head1 = RSA.PKCS1_SHA224;
                        head2 = RSA.PKCS1_SHA224_ALT;
                        break;

                    case 4:
                        head1 = RSA.PKCS1_SHA256;
                        head2 = RSA.PKCS1_SHA256_ALT;
                        break;

                    case 5:
                        head1 = RSA.PKCS1_SHA384;
                        head2 = RSA.PKCS1_SHA384_ALT;
                        break;

                    case 6:
                        head1 = RSA.PKCS1_SHA512;
                        head2 = RSA.PKCS1_SHA512_ALT;
                        break;

                    default:
                        throw new SSLException(
                                  "Unsupported hash algorithm: "
                                  + hashId);
                    }
                    ok = RSA.Verify(rpk, head1, head2, hv, sig);
                }
            }
            else if (sigId == 3)
            {
                ECPublicKey epk = pkey as ECPublicKey;
                if (epk == null)
                {
                    throw new SSLException(
                              "Wrong public key type for ECDSA");
                }
                ok = ECDSA.Verify(epk, hv, sig);
            }
            else
            {
                throw new SSLException(
                          "Unsupported signature type: " + sigId);
            }

            if (!ok)
            {
                throw new SSLException(
                          "Invalid signature on ServerKeyExchange");
            }
            return(point);
        }
        /// <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;
        }
Exemplo n.º 25
0
    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);
    }
Exemplo n.º 26
0
 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;
 }
Exemplo n.º 27
0
        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));
            }
        }
Exemplo n.º 28
0
 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;
 }
Exemplo n.º 29
0
        /**
         * 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);
        }
Exemplo n.º 30
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;
		}
Exemplo n.º 31
0
 private void DigestDoFinal(byte[] result)
 {
     digest.DoFinal(result, 0);
 }
Exemplo n.º 32
0
 public int DoFinal(byte[] output, int outOff)
 {
     return(_digest.DoFinal(output, outOff));
 }
Exemplo n.º 33
0
        private static void CheckEd25519phVector(string sSK, string sPK, string sM, string sCTX, string sSig, string text)
        {
            byte[] sk = Hex.Decode(sSK);
            byte[] pk = Hex.Decode(sPK);

            byte[] pkGen = new byte[Ed25519.PublicKeySize];
            Ed25519.GeneratePublicKey(sk, 0, pkGen, 0);
            Assert.IsTrue(Arrays.AreEqual(pk, pkGen), text);

            byte[] m   = Hex.Decode(sM);
            byte[] ctx = Hex.Decode(sCTX);
            byte[] sig = Hex.Decode(sSig);

            byte[] badsig = Arrays.Clone(sig);
            badsig[Ed25519.SignatureSize - 1] ^= 0x80;

            byte[] sigGen = new byte[Ed25519.SignatureSize];

            {
                IDigest prehash = Ed25519.CreatePrehash();
                prehash.BlockUpdate(m, 0, m.Length);

                byte[] ph = new byte[Ed25519.PrehashSize];
                prehash.DoFinal(ph, 0);

                Ed25519.SignPrehash(sk, 0, ctx, ph, 0, sigGen, 0);
                Assert.IsTrue(Arrays.AreEqual(sig, sigGen), text);

                Ed25519.SignPrehash(sk, 0, pk, 0, ctx, ph, 0, sigGen, 0);
                Assert.IsTrue(Arrays.AreEqual(sig, sigGen), text);

                bool shouldVerify = Ed25519.VerifyPrehash(sig, 0, pk, 0, ctx, ph, 0);
                Assert.IsTrue(shouldVerify, text);

                bool shouldNotVerify = Ed25519.VerifyPrehash(badsig, 0, pk, 0, ctx, ph, 0);
                Assert.IsFalse(shouldNotVerify, text);
            }

            {
                IDigest ph = Ed25519.CreatePrehash();
                ph.BlockUpdate(m, 0, m.Length);

                Ed25519.SignPrehash(sk, 0, ctx, ph, sigGen, 0);
                Assert.IsTrue(Arrays.AreEqual(sig, sigGen), text);
            }

            {
                IDigest ph = Ed25519.CreatePrehash();
                ph.BlockUpdate(m, 0, m.Length);

                Ed25519.SignPrehash(sk, 0, pk, 0, ctx, ph, sigGen, 0);
                Assert.IsTrue(Arrays.AreEqual(sig, sigGen), text);
            }

            {
                IDigest ph = Ed25519.CreatePrehash();
                ph.BlockUpdate(m, 0, m.Length);

                bool shouldVerify = Ed25519.VerifyPrehash(sig, 0, pk, 0, ctx, ph);
                Assert.IsTrue(shouldVerify, text);
            }

            {
                IDigest ph = Ed25519.CreatePrehash();
                ph.BlockUpdate(m, 0, m.Length);

                bool shouldNotVerify = Ed25519.VerifyPrehash(badsig, 0, pk, 0, ctx, ph);
                Assert.IsFalse(shouldNotVerify, text);
            }
        }
Exemplo n.º 34
0
        // 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);
            }
        }
Exemplo n.º 35
0
 public int DoFinal(byte[] output, int outOff)
 {
     return(_hash.DoFinal(output, outOff));
 }
		private static void Hash(IDigest d, byte[] input, byte[] output)
		{
			d.BlockUpdate(input, 0, input.Length);
			d.DoFinal(output, 0);
		}
Exemplo n.º 37
0
        /// <summary> Generate a signature for the loaded message using the key we were
        /// initialised with.
        /// </summary>
        public virtual byte[] GenerateSignature()
        {
            int digSize = digest.GetDigestSize();

            int t     = 0;
            int delta = 0;

            if (trailer == TrailerImplicit)
            {
                t     = 8;
                delta = block.Length - digSize - 1;
                digest.DoFinal(block, delta);
                block[block.Length - 1] = (byte)TrailerImplicit;
            }
            else
            {
                t     = 16;
                delta = block.Length - digSize - 2;
                digest.DoFinal(block, delta);
                block[block.Length - 2] = (byte)((uint)trailer >> 8);
                block[block.Length - 1] = (byte)trailer;
            }

            byte header = 0;
            int  x      = (digSize + messageLength) * 8 + t + 4 - keyBits;

            if (x > 0)
            {
                int mR = messageLength - ((x + 7) / 8);
                header = (byte)(0x60);

                delta -= mR;

                Array.Copy(mBuf, 0, block, delta, mR);
            }
            else
            {
                header = (byte)(0x40);
                delta -= messageLength;

                Array.Copy(mBuf, 0, block, delta, messageLength);
            }

            if ((delta - 1) > 0)
            {
                for (int i = delta - 1; i != 0; i--)
                {
                    block[i] = (byte)0xbb;
                }
                block[delta - 1] ^= (byte)0x01;
                block[0]          = (byte)0x0b;
                block[0]         |= header;
            }
            else
            {
                block[0]  = (byte)0x0a;
                block[0] |= header;
            }

            byte[] b = cipher.ProcessBlock(block, 0, block.Length);

            ClearBlock(mBuf);
            ClearBlock(block);

            return(b);
        }
Exemplo n.º 38
0
        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");
            }
        }
Exemplo n.º 39
0
        /**
         * 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);
        }
Exemplo n.º 40
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));
			}
		}
Exemplo n.º 41
0
        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);
        }
Exemplo n.º 42
0
        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();
        }
Exemplo n.º 43
0
        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]);
        }
 public static byte[] Digest(this IDigest digest)
 {
     byte[] result = new byte[digest.GetDigestSize()];
     digest.DoFinal(result, 0);
     return(result);
 }
Exemplo n.º 45
0
 public static byte[] DoFinal(IDigest digest)
 {
     byte[] array = new byte[digest.GetDigestSize()];
     digest.DoFinal(array, 0);
     return(array);
 }
Exemplo n.º 46
0
        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));
        }
Exemplo n.º 47
0
        // TODO Move this when other JCE tests are ported from Java

        /**
         * signature with a "forged signature" (sig block not at end of plain text)
         */
        private void doTestBadSig()//PrivateKey priv, PublicKey pub)
        {
//			Signature           sig = Signature.getInstance("SHA1WithRSAEncryption", "BC");
            ISigner sig = SignerUtilities.GetSigner("SHA1WithRSAEncryption");
//			KeyPairGenerator    fact;
//			KeyPair             keyPair;
//			byte[]              data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };

//			fact = KeyPairGenerator.getInstance("RSA", "BC");
            RsaKeyPairGenerator fact = new RsaKeyPairGenerator();

//			fact.initialize(768, new SecureRandom());
            RsaKeyGenerationParameters factParams = new RsaKeyGenerationParameters(
//				BigInteger.ValueOf(0x11), new SecureRandom(), 768, 25);
                BigInteger.ValueOf(3), new SecureRandom(), 768, 25);

            fact.Init(factParams);

//			keyPair = fact.generateKeyPair();
//
//			PrivateKey  signingKey = keyPair.getPrivate();
//			PublicKey   verifyKey = keyPair.getPublic();
            AsymmetricCipherKeyPair keyPair = fact.GenerateKeyPair();

            AsymmetricKeyParameter priv = keyPair.Private;
            AsymmetricKeyParameter pub  = keyPair.Public;

//			testBadSig(signingKey, verifyKey);



//			MessageDigest sha1 = MessageDigest.getInstance("SHA1", "BC");
            IDigest sha1 = DigestUtilities.GetDigest("SHA1");

//			Cipher signer = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
//			IBufferedCipher signer = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding");
            IAsymmetricBlockCipher signer = new Pkcs1Encoding(new RsaEngine());

//			signer.init(Cipher.ENCRYPT_MODE, priv);
            signer.Init(true, priv);

//			byte[] block = new byte[signer.getBlockSize()];
//			byte[] block = new byte[signer.GetBlockSize()];
            byte[] block = new byte[signer.GetInputBlockSize()];

//			sha1.update((byte)0);
            sha1.Update(0);

//			byte[] sigHeader = Hex.decode("3021300906052b0e03021a05000414");
            byte[] sigHeader = Hex.Decode("3021300906052b0e03021a05000414");
//			System.arraycopy(sigHeader, 0, block, 0, sigHeader.length);
            Array.Copy(sigHeader, 0, block, 0, sigHeader.Length);

//			sha1.digest(block, sigHeader.length, sha1.getDigestLength());
            sha1.DoFinal(block, sigHeader.Length);

//			System.arraycopy(sigHeader, 0, block,
//				sigHeader.length + sha1.getDigestLength(), sigHeader.length);
            Array.Copy(sigHeader, 0, block,
                       sigHeader.Length + sha1.GetDigestSize(), sigHeader.Length);

//			byte[] sigBytes = signer.doFinal(block);
            byte[] sigBytes = signer.ProcessBlock(block, 0, block.Length);

//			Signature verifier = Signature.getInstance("SHA1WithRSA", "BC");
            ISigner verifier = SignerUtilities.GetSigner("SHA1WithRSA");

//			verifier.initVerify(pub);
            verifier.Init(false, pub);

//			verifier.update((byte)0);
            verifier.Update(0);

//			if (verifier.verify(sig))
            if (verifier.VerifySignature(sigBytes))
            {
//				fail("bad signature passed");
                Fail("bad signature passed");
            }
        }
Exemplo n.º 48
0
 private void CycleSeed()
 {
     _msgDigest.BlockUpdate(_dgtSeed, 0, _dgtSeed.Length);
     IncrementCounter(_seedCtr++);
     _msgDigest.DoFinal(_dgtSeed, 0);
 }
Exemplo n.º 49
0
        /**
         * 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);
        }
Exemplo n.º 50
0
 public static byte[] DoFinal(
     IDigest digest)
 {
     byte[] b = new byte[digest.GetDigestSize()];
     digest.DoFinal(b, 0);
     return b;
 }
Exemplo n.º 51
0
        virtual public bool ReadKey(PdfDictionary enc, byte[] password)
        {
            if (password == null)
            {
                password = new byte[0];
            }
            byte[] oValue  = DocWriter.GetISOBytes(enc.Get(PdfName.O).ToString());
            byte[] uValue  = DocWriter.GetISOBytes(enc.Get(PdfName.U).ToString());
            byte[] oeValue = DocWriter.GetISOBytes(enc.Get(PdfName.OE).ToString());
            byte[] ueValue = DocWriter.GetISOBytes(enc.Get(PdfName.UE).ToString());
            byte[] perms   = DocWriter.GetISOBytes(enc.Get(PdfName.PERMS).ToString());

            PdfNumber pValue = (PdfNumber)enc.Get(PdfName.P);

            this.oeKey = oeValue;
            this.ueKey = ueValue;
            this.perms = perms;

            this.ownerKey = oValue;
            this.userKey  = uValue;

            this.permissions = pValue.LongValue;

            bool    isUserPass = false;
            IDigest md         = DigestUtilities.GetDigest("SHA-256");

            md.BlockUpdate(password, 0, Math.Min(password.Length, 127));
            md.BlockUpdate(oValue, VALIDATION_SALT_OFFSET, SALT_LENGHT);
            md.BlockUpdate(uValue, 0, OU_LENGHT);
            byte[]            hash        = DigestUtilities.DoFinal(md);
            bool              isOwnerPass = CompareArray(hash, oValue, 32);
            AESCipherCBCnoPad ac;

            if (isOwnerPass)
            {
                md.BlockUpdate(password, 0, Math.Min(password.Length, 127));
                md.BlockUpdate(oValue, KEY_SALT_OFFSET, SALT_LENGHT);
                md.BlockUpdate(uValue, 0, OU_LENGHT);
                md.DoFinal(hash, 0);
                ac  = new AESCipherCBCnoPad(false, hash);
                key = ac.ProcessBlock(oeValue, 0, oeValue.Length);
            }
            else
            {
                md.BlockUpdate(password, 0, Math.Min(password.Length, 127));
                md.BlockUpdate(uValue, VALIDATION_SALT_OFFSET, SALT_LENGHT);
                md.DoFinal(hash, 0);
                isUserPass = CompareArray(hash, uValue, 32);
                if (!isUserPass)
                {
                    throw new BadPasswordException(MessageLocalization.GetComposedMessage("bad.user.password"));
                }
                md.BlockUpdate(password, 0, Math.Min(password.Length, 127));
                md.BlockUpdate(uValue, KEY_SALT_OFFSET, SALT_LENGHT);
                md.DoFinal(hash, 0);
                ac  = new AESCipherCBCnoPad(false, hash);
                key = ac.ProcessBlock(ueValue, 0, ueValue.Length);
            }
            ac = new AESCipherCBCnoPad(false, key);
            byte[] decPerms = ac.ProcessBlock(perms, 0, perms.Length);
            if (decPerms[9] != (byte)'a' || decPerms[10] != (byte)'d' || decPerms[11] != (byte)'b')
            {
                throw new BadPasswordException(MessageLocalization.GetComposedMessage("bad.user.password"));
            }
            permissions = (decPerms[0] & 0xff) | ((decPerms[1] & 0xff) << 8)
                          | ((decPerms[2] & 0xff) << 16) | ((decPerms[2] & 0xff) << 24);
            encryptMetadata = decPerms[8] == (byte)'T';
            return(isOwnerPass);
        }
Exemplo n.º 52
0
        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);*/
        }
Exemplo n.º 53
0
 private void DoHash(byte[] input, byte[] output)
 {
     mDigest.BlockUpdate(input, 0, input.Length);
     mDigest.DoFinal(output, 0);
 }
Exemplo n.º 54
0
        private static void DoSignPdfFile(PdfStamper stamper, ConversionProfile profile, JobPasswords jobPasswords)
        {
            Signature signing = profile.PdfSettings.Signature;

            if (!signing.Enabled) //Leave without signing
            {
                return;
            }

            Logger.Debug("Start signing file.");

            signing.CertificateFile = Path.GetFullPath(signing.CertificateFile);

            if (string.IsNullOrEmpty(jobPasswords.PdfSignaturePassword))
            {
                Logger.Error("Launched signing without certification password.");
                throw new ProcessingException("Launched signing without certification password.", 12204);
            }
            if (IsValidCertificatePassword(signing.CertificateFile, jobPasswords.PdfSignaturePassword) == false)
            {
                Logger.Error("Canceled signing. The password for certificate '" + signing.CertificateFile + "' is wrong.");
                throw new ProcessingException("Canceled signing. The password for certificate '" + signing.CertificateFile + "' is wrong.", 12200);
            }
            if (CertificateHasPrivateKey(signing.CertificateFile, jobPasswords.PdfSignaturePassword) == false)
            {
                Logger.Error("Canceled signing. The certificate '" + signing.CertificateFile + "' has no private key.");
                throw new ProcessingException(
                          "Canceled signing. The certificate '" + signing.CertificateFile + "' has no private key.", 12201);
            }

            var    fsCert = new FileStream(signing.CertificateFile, FileMode.Open);
            var    ks     = new Pkcs12Store(fsCert, jobPasswords.PdfSignaturePassword.ToCharArray());
            string alias  = null;

            foreach (string al in ks.Aliases)
            {
                if (ks.IsKeyEntry(al) && ks.GetKey(al).Key.IsPrivate)
                {
                    alias = al;
                    break;
                }
            }
            fsCert.Close();
            ICipherParameters pk = ks.GetKey(alias).Key;

            X509CertificateEntry[] x = ks.GetCertificateChain(alias);
            var chain = new X509Certificate[x.Length];

            for (int k = 0; k < x.Length; ++k)
            {
                chain[k] = x[k].Certificate;
            }

            ITSAClient tsc = null;

            if (!string.IsNullOrEmpty(signing.TimeServerUrl.Trim()))
            {
                if (!signing.TimeServerIsSecured)
                {
                    tsc = new TSAClientBouncyCastle(signing.TimeServerUrl);
                }
                else
                {
                    tsc = new TSAClientBouncyCastle(signing.TimeServerUrl, signing.TimeServerLoginName, signing.TimeServerPassword);
                }
            }

            PdfSignatureAppearance psa = stamper.SignatureAppearance;

            if (tsc == null)
            {
                psa.SetCrypto(pk, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
            }
            else
            {
                psa.SetCrypto(null, chain, null, PdfSignatureAppearance.SELF_SIGNED);
            }

            if (!profile.PdfSettings.Signature.AllowMultiSigning)
            {
                //Lock PDF, except for annotations and form filling (irrelevant for PDFCreator)
                psa.CertificationLevel = PdfSignatureAppearance.CERTIFIED_FORM_FILLING_AND_ANNOTATIONS;
            }

            psa.Reason   = signing.SignReason;
            psa.Contact  = signing.SignContact;
            psa.Location = signing.SignLocation;

            if (signing.DisplaySignatureInDocument)
            {
                int signPage = SignPageNr(stamper, signing);

                psa.SetVisibleSignature(new Rectangle(signing.LeftX, signing.LeftY, signing.RightX, signing.RightY),
                                        signPage, null);
            }

            var dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached"));

            dic.Reason           = psa.Reason;
            dic.Location         = psa.Location;
            dic.Contact          = psa.Contact;
            dic.Date             = new PdfDate(psa.SignDate);
            psa.CryptoDictionary = dic;

            const int contentEstimated = 15000;
            // Preallocate excluded byte-range for the signature content (hex encoded)
            var exc = new Dictionary <PdfName, int>();

            exc[PdfName.CONTENTS] = contentEstimated * 2 + 2;
            psa.PreClose(exc);
            const string hashAlgorithm = "SHA1"; //Always use HashAlgorithm "SHA1"
            var          sgn           = new PdfPKCS7(pk, chain, null, hashAlgorithm, false);
            IDigest      messageDigest = DigestUtilities.GetDigest(hashAlgorithm);
            Stream       data          = psa.GetRangeStream();
            var          buf           = new byte[8192];
            int          n;

            while ((n = data.Read(buf, 0, buf.Length)) > 0)
            {
                messageDigest.BlockUpdate(buf, 0, n);
            }
            var hash = new byte[messageDigest.GetDigestSize()];

            messageDigest.DoFinal(hash, 0);
            byte[] ocsp = null;
            if (chain.Length >= 2)
            {
                String url = PdfPKCS7.GetOCSPURL(chain[0]);
                if (!string.IsNullOrEmpty(url))
                {
                    ocsp = new OcspClientBouncyCastle().GetEncoded(chain[0], chain[1], url);
                }
            }
            DateTime cal = psa.SignDate;

            byte[] sh = sgn.GetAuthenticatedAttributeBytes(hash, cal, ocsp);
            sgn.Update(sh, 0, sh.Length);

            var paddedSig = new byte[contentEstimated];

            if (tsc != null)
            {
                byte[] encodedSigTsa = null;
                try
                {
                    encodedSigTsa = sgn.GetEncodedPKCS7(hash, cal, tsc, ocsp);
                    Array.Copy(encodedSigTsa, 0, paddedSig, 0, encodedSigTsa.Length);
                }
                catch (Exception ex)
                {
                    throw new ProcessingException(
                              ex.GetType() + " while connecting to timeserver (can't connect to timeserver): " + ex.Message, 12205);
                }
                if (contentEstimated + 2 < encodedSigTsa.Length)
                {
                    throw new ProcessingException(
                              "Not enough space for signature", 12202);
                }
            }
            else
            {
                byte[] encodedSig = sgn.GetEncodedPKCS7(hash, cal);
                Array.Copy(encodedSig, 0, paddedSig, 0, encodedSig.Length);
                if (contentEstimated + 2 < encodedSig.Length)
                {
                    throw new ProcessingException("Not enough space for signature", 12203);
                }
            }

            var dic2 = new PdfDictionary();

            dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true));
            psa.Close(dic2);
        }
Exemplo n.º 55
0
        public virtual void UpdateWithRecoveredMessage(
            byte[] signature)
        {
            byte[] block = cipher.ProcessBlock(signature, 0, signature.Length);

            //
            // adjust block size for leading zeroes if necessary
            //
            if (block.Length < (keyBits + 7) / 8)
            {
                byte[] tmp = new byte[(keyBits + 7) / 8];

                Array.Copy(block, 0, tmp, tmp.Length - block.Length, block.Length);
                ClearBlock(block);
                block = tmp;
            }

            int tLength;

            if (((block[block.Length - 1] & 0xFF) ^ 0xBC) == 0)
            {
                tLength = 1;
            }
            else
            {
                int sigTrail = ((block[block.Length - 2] & 0xFF) << 8) | (block[block.Length - 1] & 0xFF);

                if (IsoTrailers.NoTrailerAvailable(digest))
                {
                    throw new ArgumentException("unrecognised hash in signature");
                }

                if (sigTrail != IsoTrailers.GetTrailer(digest))
                {
                    throw new InvalidOperationException("signer initialised with wrong digest for trailer " + sigTrail);
                }

                tLength = 2;
            }

            //
            // calculate H(m2)
            //
            byte[] m2Hash = new byte[hLen];
            digest.DoFinal(m2Hash, 0);

            //
            // remove the mask
            //
            byte[] dbMask = MaskGeneratorFunction1(block, block.Length - hLen - tLength, hLen, block.Length - hLen - tLength);
            for (int i = 0; i != dbMask.Length; i++)
            {
                block[i] ^= dbMask[i];
            }

            block[0] &= 0x7f;

            //
            // find out how much padding we've got
            //
            int mStart = 0;

            while (mStart < block.Length)
            {
                if (block[mStart++] == 0x01)
                {
                    break;
                }
            }

            if (mStart >= block.Length)
            {
                ClearBlock(block);
            }

            fullMessage = (mStart > 1);

            recoveredMessage = new byte[dbMask.Length - mStart - saltLength];

            Array.Copy(block, mStart, recoveredMessage, 0, recoveredMessage.Length);
            recoveredMessage.CopyTo(mBuf, 0);

            preSig     = signature;
            preBlock   = block;
            preMStart  = mStart;
            preTLength = tLength;
        }
Exemplo n.º 56
0
        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 (Evaluate.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 (Evaluate.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 (Evaluate.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 (Evaluate.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 (Evaluate.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);*/
        }