示例#1
0
 public Certificate(ulong id, DateTime issueDate, DateTime expireDate, HashFunctionType hashFunction)
 {
     this.id           = id;
     this.issueDate    = issueDate;
     this.expireDate   = expireDate;
     this.hashFunction = hashFunction;
 }
示例#2
0
 public HashFunctionIdent(HashFunctionType hashFuncType, string displayName, string DERIdent, int length)
 {
     this.type         = hashFuncType;
     this.diplayName   = displayName;
     this.DERIdent     = DERIdent;
     this.digestLength = length;
 }
示例#3
0
        public CACertificate(ulong id, string authorityName, DateTime issueDate, DateTime expireDate,
                             HashFunctionType hashFunction = HashFunctionType.SHA1, uint ip = 0, byte[] ip6 = null)
            : base(id, issueDate, expireDate, hashFunction)
        {
            // assign type

            BinaryList cr = new BinaryList();

            // make header

            cr.Append(id, issueDate, expireDate);

            // hash function
            cr.Append((byte)((byte)hashFunction << 4));
            this.hashFunction = hashFunction;

            // CA Name
            this.name = authorityName;
            cr.Append((byte)(authorityName.Length), Encoding.ASCII.GetBytes(authorityName));

            // public key
            rsa         = RSA.Create();// new RSACryptoServiceProvider(2048);
            rsa.KeySize = 2048;
            RSAParameters dRSAKey = rsa.ExportParameters(true);


            cr.Append((byte)dRSAKey.Exponent.Length, dRSAKey.Exponent, (ushort)dRSAKey.Modulus.Length, dRSAKey.Modulus);


            publicRawData = cr.ToArray();

            privateRawData = DC.Merge(dRSAKey.D, dRSAKey.DP, dRSAKey.DQ, dRSAKey.InverseQ, dRSAKey.P, dRSAKey.Q);
        }
        /// <summary>
        /// Encrypt a string using dual encryption method. Returns an encrypted text.
        /// </summary>
        /// <param name="toEncrypt">String to be encrypted</param>
        /// <param name="key">Unique key for encryption/decryption</param>m>
        /// <param name="type"> Type of Hash function to be used. </param>
        /// <param name="hashKey"> optional key to be used with HMACSHA256 algorithm </param>
        /// <returns>Returns encrypted string.</returns>
        public static string Encrypt(string toEncrypt, string key, HashFunctionType type = HashFunctionType.MD5, byte[] hashKey = null)
        {
#if NETFX_CORE
            try
            {
                byte[] keyHash = Hash(key, type, hashKey);


                // Create a buffer that contains the encoded message to be encrypted.
                var toDecryptBuffer = CryptographicBuffer.ConvertStringToBinary(toEncrypt, BinaryStringEncoding.Utf8);

                // Open a symmetric algorithm provider for the specified algorithm.
                var aes = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);

                //Since all hashing functions have fixed length some algorithms do not suit to be used as key hashers
                //ie SHA1 will throw an error since its size is 160 bit while Aes requires 16 byte block size (or multiples of 16)
                if (keyHash.Length % aes.BlockLength != 0)
                {
                    //if SHA1 used for encryption please not its block size is 160 bit
                    throw new ArgumentException("Hash function hashed with invalid key block size: " + keyHash.Length);
                }
                // Create a symmetric key.
                var symetricKey = aes.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(keyHash));

                // The input key must be securely shared between the sender of the cryptic message
                // and the recipient. The initialization vector must also be shared but does not
                // need to be shared in a secure manner. If the sender encodes a message string
                // to a buffer, the binary encoding method must also be shared with the recipient.
                var buffEncrypted = CryptographicEngine.Encrypt(symetricKey, toDecryptBuffer, null);

                // Convert the encrypted buffer to a string (for display).
                // We are using Base64 to convert bytes to string since you might get unmatched characters
                // in the encrypted buffer that we cannot convert to string with UTF8.
                var strEncrypted = CryptographicBuffer.EncodeToBase64String(buffEncrypted);

                return(strEncrypted);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                throw new Exception("[EncryptionProvider] Error Encrypting a string");
            }
#else
            throw new System.PlatformNotSupportedException();
#endif
        }
示例#5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="HashTable{TKey, TValue}"/> class
        /// </summary>
        /// <param name="hashFunction">Custom hash function
        /// (default <see cref="object.GetHashCode"/> will be used if not given)</param>
        /// <param name="allocatedSize">Hash table size in the beginning</param>
        public HashTable(
            HashFunctionType <TKey> hashFunction = null,
            int allocatedSize = 1)
        {
            if (allocatedSize <= 0)
            {
                throw new ArgumentException("Size must be >= 1");
            }

            this.hashFunction = hashFunction ?? GetDefaultHashCode <TKey>;

            this.size    = 0;
            this.buckets = new ListStuff.List <TableElement> [allocatedSize];

            for (int i = 0; i < this.buckets.Length; ++i)
            {
                this.buckets[i] = new ListStuff.List <TableElement>();
            }
        }
        /// <summary>
        /// Decrypt a string using dual encryption method. Return a Decrypted clear string
        /// </summary>
        /// <param name="cipherString">Encrypted string</param>
        /// <param name="key">Unique key for encryption/decryption</param>
        /// <param name="type"> Type of Hash function to be used. </param>
        /// <param name="hashKey"> optional key to be used with HMACSHA256 algorithm </param>
        /// <returns>Returns decrypted text.</returns>
        public static string Decrypt(string cipherString, string key, HashFunctionType type = HashFunctionType.MD5, byte[] hashKey = null)
        {
#if NETFX_CORE
            try
            {
                byte[] keyHash = Hash(key, type, hashKey);

                // Create a buffer that contains the encoded message to be decrypted.
                IBuffer toDecryptBuffer = CryptographicBuffer.DecodeFromBase64String(cipherString);

                // Open a symmetric algorithm provider for the specified algorithm.
                SymmetricKeyAlgorithmProvider aes = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);

                //Since all hashing functions have fixed length some algorithms do not suit to be used as key hashers
                //ie SHA1 will throw an error since its size is 160 bit while Aes requires 16 byte block size (or multiples of 16)
                if (keyHash.Length % aes.BlockLength != 0)
                {
                    //if SHA1 used for encryption please not its block size is 160 bit
                    throw new ArgumentException("Hash function hashed with invalid key block size: " + keyHash.Length);
                }
                // Create a symmetric key.
                var symetricKey = aes.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(keyHash));

                var buffDecrypted = CryptographicEngine.Decrypt(symetricKey, toDecryptBuffer, null);

                string strDecrypted = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, buffDecrypted);

                return(strDecrypted);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                throw new Exception("[EncryptionProvider] Error Decrypting a string");
            }
#else
            throw new System.PlatformNotSupportedException();
#endif
        }
        /// <summary>
        /// Hashes given string using specified algorithm.
        /// </summary>
        /// <param name="toHash"> String to be hashed. </param>
        /// <param name="type"> Type of Hash function to be used. </param>
        /// <param name="hashKey"> optional key to be used with HMACSHA256 algorithm </param>
        /// <returns></returns>
        private static byte[] Hash(string toHash, HashFunctionType type = HashFunctionType.MD5, byte[] hashKey = null)
        {
            byte[] keyByteArray = System.Text.Encoding.UTF8.GetBytes(toHash);
            switch (type)
            {
            case HashFunctionType.MD5:
                var md5Algorithm = MD5.Create();
                return(md5Algorithm.ComputeHash(keyByteArray));

            case HashFunctionType.SHA1:
                var sha1Algorithm = SHA1.Create();
                return(sha1Algorithm.ComputeHash(keyByteArray));

            case HashFunctionType.HMACSHA256:
                HMACSHA256 hmac = hashKey != null ?
                                  new HMACSHA256(hashKey) : new HMACSHA256();
                return(hmac.ComputeHash(keyByteArray));

            default:
                System.Diagnostics.Debug.WriteLine("Unrecognized Hash function type: " + type);
                throw new ArgumentException("Unrecognized Hash function type: " + type);
            }
        }
示例#8
0
    public DomainCertificate(ulong id, string domain, CACertificate authority, DateTime issueDate,
                             DateTime expireDate, HashFunctionType hashFunction = HashFunctionType.SHA1, uint ip = 0, byte[] ip6 = null)
        : base(id, issueDate, expireDate, hashFunction)
    {
        // assign type

        var cr = new BinaryList();

        // id
        cr.AddUInt64(id);

        // ip
        this.ip  = ip;
        this.ip6 = ip6;

        cr.AddUInt32(ip);


        if (ip6?.Length == 16)
        {
            cr.AddUInt8Array(ip6);
        }
        else
        {
            cr.AddUInt8Array(new byte[16]);
        }


        cr.AddDateTime(issueDate)
        .AddDateTime(expireDate);

        // domain
        this.domain = domain;
        cr.AddUInt8((byte)(domain.Length))
        .AddUInt8Array(Encoding.ASCII.GetBytes(domain));

        // CA
        this.caName = authority.Name;
        cr.AddUInt8((byte)(authority.Name.Length))
        .AddUInt8Array(Encoding.ASCII.GetBytes(authority.Name));

        this.authorityName = authority.Name;

        // CA Index
        //co.KeyIndex = authority.KeyIndex;
        this.caId = authority.Id;
        cr.AddUInt64(caId);


        // public key
        rsa         = RSA.Create();// new RSACryptoServiceProvider(2048);
        rsa.KeySize = 2048;
        RSAParameters dRSAKey = rsa.ExportParameters(true);

        cr.AddUInt8((byte)dRSAKey.Exponent.Length)
        .AddUInt8Array(dRSAKey.Exponent)
        .AddUInt16((ushort)dRSAKey.Modulus.Length)
        .AddUInt8Array(dRSAKey.Modulus);


        publicRawData = cr.ToArray();

        // private key
        this.privateRawData = DC.Merge(dRSAKey.D, dRSAKey.DP, dRSAKey.DQ, dRSAKey.InverseQ, dRSAKey.P, dRSAKey.Q);

        this.signature = authority.Sign(publicRawData);
    }
示例#9
0
    public UserCertificate(ulong id, string username, DomainCertificate domainCertificate, DateTime issueDate,
                           DateTime expireDate, HashFunctionType hashFunction = HashFunctionType.SHA1, uint ip = 0, byte[] ip6 = null)
        : base(id, issueDate, expireDate, hashFunction)
    {
        // assign type
        var cr = new BinaryList();

        //id
        cr.AddUInt64(id);

        // ip
        this.ip  = ip;
        this.ip6 = ip6;

        cr.AddUInt32(ip);


        if (ip6?.Length == 16)
        {
            cr.AddUInt8Array(ip6);
        }
        else
        {
            cr.AddUInt8Array(new byte[16]);
        }


        // dates
        this.issueDate  = DateTime.UtcNow;
        this.expireDate = expireDate;

        cr.AddDateTime(issueDate)
        .AddDateTime(expireDate);


        // domain
        this.domainId = domainCertificate.Id;
        cr.AddUInt64(domainCertificate.Id);
        this.domain = domainCertificate.Domain;
        cr.AddUInt8((byte)domainCertificate.Domain.Length)
        .AddUInt8Array(Encoding.ASCII.GetBytes(domainCertificate.Domain));


        // username
        this.username = username;

        cr.AddUInt8((byte)(username.Length))
        .AddUInt8Array(Encoding.ASCII.GetBytes(username));

        // hash function (SHA1)
        cr.AddUInt8((byte)((byte)hashFunction << 4));// (byte)0x10);

        // public key

        rsa         = RSA.Create();// new RSACryptoServiceProvider(2048);
        rsa.KeySize = 2048;
        // write public certificate file

        var key = rsa.ExportParameters(true);

        publicRawData = new BinaryList().AddUInt8((byte)key.Exponent.Length)
                        .AddUInt8Array(key.Exponent)
                        .AddUInt16((ushort)key.Modulus.Length)
                        .AddUInt8Array(key.Modulus).ToArray();


        // sign it
        this.signature = domainCertificate.Sign(publicRawData);


        // store private info
        privateRawData = DC.Merge(key.D, key.DP, key.DQ, key.InverseQ, key.P, key.Q, signature);
    }
示例#10
0
 public HMAC(HashFunctionType type)
 {
     HashType = type;
 }