Пример #1
0
        /// <summary>
        /// Finalizes the hash computation after the last data is processed by the cryptographic stream object.
        /// </summary>
        /// <returns>
        /// The computed hash code.
        /// </returns>
        protected override byte[] HashFinal()
        {
            // finalize the original hash
            var hashValue = _hashProvider.ComputeHash(new byte[0]);

            // write the outer padding
            _hashProvider.TransformBlock(_outerPadding, 0, BlockSize, _outerPadding, 0);

            // write the inner hash and finalize the hash
            _hashProvider.TransformFinalBlock(hashValue, 0, hashValue.Length);

            var hash = _hashProvider.Hash;

            return(GetTruncatedHash(hash));
        }
Пример #2
0
        public byte[] ComputeHash(byte[] data, byte[] salt)
        {
            byte[] saltedData = Concatenate(data, salt);
            byte[] hashBytes  = hashProvider.ComputeHash(saltedData);

            return(hashBytes);
        }
Пример #3
0
        public bool IsValid(string userName, string password)
        {
            if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
            {
                return(false);
            }

            var passwordHash = HashProvider.ComputeHash(password);

            return(string.Equals(userName, _configuration.UserName) &&
                   string.Equals(passwordHash, _configuration.Password));
        }
Пример #4
0
        /// <summary>
        /// Hashes and encodes the signature for encryption.  Uses the DER (Distinguished Encoding Rules)
        /// and the SHA256 hash provider for encoding generation.
        /// </summary>
        /// <param name="dataBytes">Data to be signed</param>
        /// <param name="params">RSA Parameters used for signature calculation</param>
        /// <returns>Computed signature (pre-encryption)</returns>
        public byte[] EncodeSignature(byte[] dataBytes, RSAParameters @params)
        {
            //Set the intended message length (key length)
            int emLen = @params.N.Length;

            //Compute the hash of the data
            byte[] H = m_hashProvider.ComputeHash(dataBytes);
            //Get the digest encoding information for the hash being used.
            byte[] bytDigestEncoding = DigestEncoding.SHA256();

            //Create the hashed message including the digest info
            byte[] T = new byte[(bytDigestEncoding.Length + m_hLen)];
            bytDigestEncoding.CopyTo(T, 0);
            H.CopyTo(T, bytDigestEncoding.Length);

            H = null;
            bytDigestEncoding = null;

            if (emLen < T.Length + 11)
            {
                throw new CryptographicException("Message too short.");
            }

            //Create the padding string, octet string of 0xff
            byte[] PS = new byte[(emLen - T.Length - 3)];
            for (int i = 0; i <= PS.Length - 1; i++)
            {
                PS[i] = 0xff;
            }

            byte[] result = new byte[emLen];

            //Add the leading identifier bytes
            result[0] = 0x00;
            result[1] = 0x01;

            //Copy the padding string to the result
            PS.CopyTo(result, 2);

            //Add the separator byte
            result[PS.Length + 2] = 0x00;

            //Copy the digest info
            T.CopyTo(result, PS.Length + 3);
            PS = null;
            T  = null;

            return(result);
        }
Пример #5
0
        public async Task <User> AuthenticateAsync(LoginInfo info)
        {
            using (var ctx = dbFactory.NewUserDbContext()) {
                var user = await ctx.Users.FirstOrDefaultAsync(x => x.Username == info.Username);

                var pwSalt = (info?.Password ?? string.Empty) + (user?.Salt ?? string.Empty);
                var pwHash = hashProvider.ComputeHash(pwSalt);

                if (user?.Password != pwHash)
                {
                    user = null;
                }

                return(user);
            }
        }
Пример #6
0
        /// <summary>
        /// Mask generation function.
        /// </summary>
        /// <param name="seed">Seed</param>
        /// <param name="maskLen">Length of generated mask</param>
        /// <param name="hashLength">Length of the hash produced by the supplied hash provider</param>
        /// <param name="hashProvider">Hash provider to use in mask generation</param>
        /// <returns>Generated mask of specified length</returns>
        static internal byte[] OAEPMGF(byte[] seed, int maskLen, int hashLength, IHashProvider hashProvider)
        {
            byte[] result = new byte[maskLen];

            //Determine how many interations we have to do.  We'll be appending
            //m_hLen (hash length) bytes for every iteration, so the size of the generated byte array
            //will be m_hLen * iNum (number of iterations).
            int iNum = (int)Math.Floor(maskLen / hashLength) + 1;

            //Mask that will be truncated to create the final
            //resulting mask returned by this function.
            byte[] bytLongMask = new byte[(iNum * hashLength)];

            byte[] bytAppend = new byte[4];
            byte[] bytTmp    = null;
            int    iPadLen   = 0;

            byte[] bytSeedHash = new byte[hashLength];

            //Padded pseudorandom seed to be hashed.
            byte[] bytPadSeed = new byte[(seed.Length + 4)];
            seed.CopyTo(bytPadSeed, 0);

            for (int i = 0; i <= iNum - 1; i++)
            {
                //Convert the iterator to an Octet String byte array
                bytTmp = Mathematics.I2OSP(i, 4);

                //Calculate the needed padding zeros, and add
                //them to the resulting Array.  Result must be 4 bytes long.
                iPadLen = bytAppend.Length - bytTmp.Length;

                bytTmp.CopyTo(bytAppend, 0);

                //Hash the pseudorandom padded seed and append it to the
                //long version of the mask.
                bytAppend.CopyTo(bytPadSeed, seed.Length);
                bytSeedHash = hashProvider.ComputeHash(bytPadSeed);
                bytSeedHash.CopyTo(bytLongMask, i * hashLength);
            }

            //Copy the first maskLen bytes of bytLongMask to the result
            //and return the result.
            Array.Copy(bytLongMask, result, maskLen);

            return(result);
        }
        public void ResetCertificatePassword(Guid id, ClaimsPrincipal user)
        {
            Certificate cert = certificateRepository.Get <Certificate>(id);

            if (!authorizationLogic.CanViewPrivateKey(cert, user))
            {
                audit.LogSecurityAuditFailure(user, cert, EventCategory.CertificatePasswordReset);
                throw new UnauthorizedAccessException();
            }

            if (!hashProvider.ValidateData(cert.Content, cert.ContentDigest))
            {
                throw new InvalidOperationException("Certificate data is corrupt");
            }

            if (!cert.HasPrivateKey || cert.CertificateStorageFormat != CertificateStorageFormat.Pfx)
            {
                throw new ObjectNotInCorrectStateException("Certificate does not have a private key");
            }

            audit.LogSecurityAuditSuccess(user, cert, EventCategory.CertificatePasswordReset);

            byte[] certBytes = cert.Content;

            X509Certificate2 x509 = new X509Certificate2();

            x509.Import(certBytes, cipher.Decrypt(cert.PfxPassword, cert.PasswordNonce), X509KeyStorageFlags.Exportable);

            string nonce    = keygen.NewSecretBase64(16);
            string password = keygen.NewSecret(64);

            byte[] newBytes = x509.Export(X509ContentType.Pfx, password);

            cert.ContentDigest = hashProvider.ComputeHash(newBytes);
            cert.Content       = newBytes;
            cert.PfxPassword   = cipher.Encrypt(password, nonce);
            cert.PasswordNonce = nonce;

            certificateRepository.Update <Certificate>(cert);
        }
Пример #8
0
Файл: Utils.cs Проект: vebin/soa
        /// <summary>
        /// Mask generation function.
        /// </summary>
        /// <param name="seed">Seed</param>
        /// <param name="maskLen">Length of generated mask</param>
        /// <param name="hashLength">Length of the hash produced by the supplied hash provider</param>
        /// <param name="hashProvider">Hash provider to use in mask generation</param>
        /// <returns>Generated mask of specified length</returns>
        static internal byte[] OAEPMGF(byte[] seed, int maskLen, int hashLength, IHashProvider hashProvider)
        {
            byte[] result = new byte[maskLen];

            //Determine how many interations we have to do.  We'll be appending 
            //m_hLen (hash length) bytes for every iteration, so the size of the generated byte array 
            //will be m_hLen * iNum (number of iterations).
            int iNum = (int)Math.Floor(maskLen / hashLength) + 1;

            //Mask that will be truncated to create the final 
            //resulting mask returned by this function.
            byte[] bytLongMask = new byte[(iNum * hashLength)];

            byte[] bytAppend = new byte[4];
            byte[] bytTmp = null;
            int iPadLen = 0;
            byte[] bytSeedHash = new byte[hashLength];

            //Padded pseudorandom seed to be hashed.
            byte[] bytPadSeed = new byte[(seed.Length + 4)];
            seed.CopyTo(bytPadSeed, 0);

            for (int i = 0; i <= iNum - 1; i++)
            {
                //Convert the iterator to an Octet String byte array
                bytTmp = Mathematics.I2OSP(i, 4);

                //Calculate the needed padding zeros, and add 
                //them to the resulting Array.  Result must be 4 bytes long.
                iPadLen = bytAppend.Length - bytTmp.Length;

                bytTmp.CopyTo(bytAppend, 0);

                //Hash the pseudorandom padded seed and append it to the 
                //long version of the mask.
                bytAppend.CopyTo(bytPadSeed, seed.Length);
                bytSeedHash = hashProvider.ComputeHash(bytPadSeed);
                bytSeedHash.CopyTo(bytLongMask, i * hashLength);
            }

            //Copy the first maskLen bytes of bytLongMask to the result
            //and return the result.
            Array.Copy(bytLongMask, result, maskLen);

            return result;

        }
Пример #9
0
        /// <summary>
        /// Adds padding to the input data and returns the padded data.
        /// </summary>
        /// <param name="dataBytes">Data to be padded prior to encryption</param>
        /// <param name="params">RSA Parameters used for padding computation</param>
        /// <returns>Padded message</returns>
        public byte[] EncodeMessage(byte[] dataBytes, RSAParameters @params)
        {
            //Iterator
            int i = 0;

            //Get the size of the data to be encrypted
            m_mLen = dataBytes.Length;

            //Get the size of the public modulus (will serve as max length for cipher text)
            m_k = @params.N.Length;

            if (m_mLen > GetMaxMessageLength(@params))
            {
                throw new CryptographicException("Bad Data.");
            }

            //Generate the random octet seed (same length as hash)
            BigInteger biSeed = new BigInteger();

            biSeed.genRandomBits(m_hLen * 8, new Random());
            byte[] bytSeed = biSeed.getBytesRaw();

            //Make sure all of the bytes are greater than 0.
            for (i = 0; i <= bytSeed.Length - 1; i++)
            {
                if (bytSeed[i] == 0x00)
                {
                    //Replacing with the prime byte 17, no real reason...just picked at random.
                    bytSeed[i] = 0x17;
                }
            }

            //Mask the seed with MFG Function(SHA1 Hash)
            //This is the mask to be XOR'd with the DataBlock below.
            byte[] dbMask = Mathematics.OAEPMGF(bytSeed, m_k - m_hLen - 1, m_hLen, m_hashProvider);

            //Compute the length needed for PS (zero padding) and
            //fill a byte array to the computed length
            int psLen = GetMaxMessageLength(@params) - m_mLen;

            //Generate the SHA1 hash of an empty L (Label).  Label is not used for this
            //application of padding in the RSA specification.
            byte[] lHash = m_hashProvider.ComputeHash(System.Text.Encoding.UTF8.GetBytes(string.Empty.ToCharArray()));

            //Create a dataBlock which will later be masked.  The
            //data block includes the concatenated hash(L), PS,
            //a 0x01 byte, and the message.
            int dbLen = m_hLen + psLen + 1 + m_mLen;

            byte[] dataBlock = new byte[dbLen];

            int cPos = 0;

            //Current position

            //Add the L Hash to the data blcok
            for (i = 0; i <= lHash.Length - 1; i++)
            {
                dataBlock[cPos] = lHash[i];
                cPos           += 1;
            }

            //Add the zero padding
            for (i = 0; i <= psLen - 1; i++)
            {
                dataBlock[cPos] = 0x00;
                cPos           += 1;
            }

            //Add the 0x01 byte
            dataBlock[cPos] = 0x01;
            cPos           += 1;

            //Add the message
            for (i = 0; i <= dataBytes.Length - 1; i++)
            {
                dataBlock[cPos] = dataBytes[i];
                cPos           += 1;
            }

            //Create the masked data block.
            byte[] maskedDB = Mathematics.BitwiseXOR(dbMask, dataBlock);

            //Create the seed mask
            byte[] seedMask = Mathematics.OAEPMGF(maskedDB, m_hLen, m_hLen, m_hashProvider);

            //Create the masked seed
            byte[] maskedSeed = Mathematics.BitwiseXOR(bytSeed, seedMask);

            //Create the resulting cipher - starting with a 0 byte.
            byte[] result = new byte[@params.N.Length];
            result[0] = 0x00;

            //Add the masked seed
            maskedSeed.CopyTo(result, 1);

            //Add the masked data block
            maskedDB.CopyTo(result, maskedSeed.Length + 1);

            return(result);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="MerkleNode"/> class.
 /// </summary>
 /// <param name="hashProvider">The hash provider.</param>
 /// <param name="left">The left child node.</param>
 /// <param name="right">The right child node.</param>
 internal MerkleNode(IHashProvider hashProvider, MerkleNodeBase left, MerkleNodeBase right)
 {
     this.right    = right;
     this.left     = left;
     this.nodeHash = hashProvider.ComputeHash(left.Hash.GetHashBytes().Concat(right.Hash.GetHashBytes()).ToArray());
 }
Пример #11
0
 public IEnumerable <string> GetHashes(IHashProvider DefaultHashProvider)
 {
     //TODO: This class should handle caching of the data.
     //._content is used for performance reasons (as we do not need to copy the byte array).
     return(from file in ContainedFiles select DefaultHashProvider.ComputeHash(file.GetContent()));
 }