Exemple #1
0
 public static new Streebog512 Create(string algorithmName)
 => (Streebog512)CryptoConfig.CreateFromName(algorithmName);
        internal static bool IsSupportedAlgorithm([NotNull] this SecurityKey key, [NotNull] string algorithm)
        {
            // Note: SecurityKey currently doesn't support IsSupportedAlgorithm.
            // To work around this limitation, this static extension tries to
            // determine whether the given security key supports the specified
            // algorithm via CryptoConfig when available or using a pre-defined table.
            var symmetricSecurityKey = key as SymmetricSecurityKey;

            if (symmetricSecurityKey != null)
            {
#if DNX451
                try {
                    var instance = CryptoConfig.CreateFromName(algorithm);
                    if (instance is SymmetricAlgorithm || instance is KeyedHashAlgorithm)
                    {
                        return(true);
                    }
                }

                // Ignore the InvalidOperationException thrown by CryptoConfig.
                catch (InvalidOperationException) { }
#endif
                switch (algorithm)
                {
                case SecurityAlgorithms.HmacSha256Signature:
                case SecurityAlgorithms.HMAC_SHA256:
                case SecurityAlgorithms.HMAC_SHA384:
                case SecurityAlgorithms.HMAC_SHA512:
                    return(true);

                case SecurityAlgorithms.Aes128Encryption:
                case SecurityAlgorithms.Aes128KeyWrap:
                    return(symmetricSecurityKey.KeySize >= 128 &&
                           symmetricSecurityKey.KeySize <= 256);

                case SecurityAlgorithms.Aes192Encryption:
                case SecurityAlgorithms.Aes192KeyWrap:
                    return(symmetricSecurityKey.KeySize >= 192 &&
                           symmetricSecurityKey.KeySize <= 256);

                case SecurityAlgorithms.Aes256Encryption:
                case SecurityAlgorithms.Aes256KeyWrap:
                    return(symmetricSecurityKey.KeySize == 256);

                default:
                    return(false);
                }
            }

            else if (key is AsymmetricSecurityKey)
            {
#if DNX451
                try {
                    var instance = CryptoConfig.CreateFromName(algorithm);
                    if (instance is AsymmetricAlgorithm || instance is SignatureDescription)
                    {
                        return(true);
                    }
                }

                // Ignore the InvalidOperationException thrown by CryptoConfig.
                catch (InvalidOperationException) { }
#endif

                switch (algorithm)
                {
                case SecurityAlgorithms.RsaSha256Signature:
                case SecurityAlgorithms.RsaSha384Signature:
                case SecurityAlgorithms.RsaSha512Signature:
                case SecurityAlgorithms.RSA_SHA256:
                case SecurityAlgorithms.RSA_SHA384:
                case SecurityAlgorithms.RSA_SHA512:
                case SecurityAlgorithms.RsaOaepKeyWrap:
                case SecurityAlgorithms.RsaV15KeyWrap: {
                    if (key is RsaSecurityKey)
                    {
                        return(true);
                    }

                    var x509SecurityKey = key as X509SecurityKey;
                    if (x509SecurityKey != null)
                    {
#if DNX451
                        return(x509SecurityKey.Certificate.PublicKey.Key is RSA);
#else
                        return(x509SecurityKey.Certificate.GetRSAPublicKey() != null);
#endif
                    }

                    return(false);
                }

#if DNXCORE50
                // Note: the ECDsa type exists on .NET 4.5.1 but not on Mono 4.3.
                // To prevent this code path from throwing an exception
                // on Mono, the following algorithms are ignored on DNX451.
                case SecurityAlgorithms.ECDSA_SHA256:
                case SecurityAlgorithms.ECDSA_SHA384:
                case SecurityAlgorithms.ECDSA_SHA512: {
                    if (key is ECDsaSecurityKey)
                    {
                        return(true);
                    }

                    var x509SecurityKey = key as X509SecurityKey;
                    if (x509SecurityKey != null)
                    {
                        return(x509SecurityKey.Certificate.GetECDsaPublicKey() != null);
                    }

                    return(false);
                }
#endif

                default:
                    return(false);
                }
            }

            // If the security key doesn't inherit from SymmetricSecurityKey
            // or AsymmetricSecurityKey, it must be treated as an invalid key
            // and false must be returned to indicate that it cannot be used
            // with the specified algorithm.
            return(false);
        }
        /// <summary>
        /// Verifies the manifest against it's recorded signature
        /// </summary>
        /// <returns><c>true</c>, if manifest was verifyed, <c>false</c> otherwise.</returns>
        /// <param name="manifest">Manifest.</param>
        protected bool VerifyPackage(AppletPackage package)
        {
            // First check: Hash - Make sure the HASH is ok
            if (Convert.ToBase64String(SHA256.Create().ComputeHash(package.Manifest)) != Convert.ToBase64String(package.Meta.Hash))
            {
                throw new InvalidOperationException($"Package contents of {package.Meta.Id} appear to be corrupt!");
            }

            if (package.Meta.Signature != null)
            {
                this.m_tracer.TraceInfo("Will verify package {0}", package.Meta.Id.ToString());

                // Get the public key - first, is the publisher in the trusted publishers store?
                var x509Store = new X509Store(StoreName.TrustedPublisher, StoreLocation.LocalMachine);
                try
                {
                    x509Store.Open(OpenFlags.ReadOnly);
                    var cert = x509Store.Certificates.Find(X509FindType.FindByThumbprint, package.Meta.PublicKeyToken, false);

                    // Not in the central store, perhaps the cert is embedded?
                    if (cert.Count == 0)
                    {
                        // Embedded CER
                        if (package.PublicKey != null)
                        {
                            // Attempt to load
                            cert = new X509Certificate2Collection(new X509Certificate2(package.PublicKey));

                            // The embedded certificate is not in trusted publisher store and/or not valid
                            if (!ApplicationContext.Current.Configuration.GetSection <AppletConfigurationSection>().Security.TrustedPublishers.Contains(cert[0].Thumbprint) && !cert[0].Verify())
                            {
                                if (!ApplicationContext.Current.Confirm(String.Format(Strings.locale_untrustedPublisherPrompt, package.Meta.Names.First().Value, this.ExtractDNPart(cert[0].Subject, "CN"))))
                                {
                                    return(false);
                                }
                                else
                                {
                                    ApplicationContext.Current.Configuration.GetSection <AppletConfigurationSection>().Security.TrustedPublishers.Add(cert[0].Thumbprint);
                                    ApplicationContext.Current.SaveConfiguration();
                                }
                            }
                        }
                        else
                        {
                            this.m_tracer.TraceError($"Cannot find public key of publisher information for {package.Meta.PublicKeyToken} or the local certificate is invalid");
                            throw new SecurityException(Strings.locale_invalidSignature);
                        }
                    }

                    // Certificate is not yet valid or expired
                    if ((cert[0].NotAfter <DateTime.Now || cert[0].NotBefore> DateTime.Now) &&
                        !ApplicationContext.Current.Confirm(String.Format(Strings.locale_certificateExpired, this.ExtractDNPart(cert[0].Subject, "CN"), cert[0].NotAfter)))
                    {
                        this.m_tracer.TraceError($"Cannot find public key of publisher information for {package.Meta.PublicKeyToken} or the local certificate is invalid");
                        throw new SecurityException(Strings.locale_invalidSignature);
                    }

                    RSACryptoServiceProvider rsa = cert[0].PublicKey.Key as RSACryptoServiceProvider;

                    var retVal = rsa.VerifyData(package.Manifest, CryptoConfig.MapNameToOID("SHA1"), package.Meta.Signature);
                    if (!retVal)
                    {
                        throw new SecurityException(Strings.locale_invalidSignature);
                    }
                    return(retVal);
                }
                finally
                {
                    x509Store.Close();
                }
            }
            else if (ApplicationContext.Current.Configuration.GetSection <AppletConfigurationSection>().Security.AllowUnsignedApplets)
            {
                return(ApplicationContext.Current.Confirm(String.Format(Strings.locale_unsignedAppletPrompt, package.Meta.Names.First().Value)));
            }
            else
            {
                this.m_tracer.TraceError("Package {0} v.{1} (publisher: {2}) is not signed and cannot be installed", package.Meta.Id, package.Meta.Version, package.Meta.Author);
                throw new SecurityException(String.Format(Strings.locale_unsignedAppletsNotAllowed, package.Meta.Id));
            }
        }
        public static string CreateSignature(string subject, string storeNameValue, string storeLocationValue)
        {
            SHA1Managed sha1             = null;
            RSACryptoServiceProvider csp = null;
            //try
            //{
            // This would be the subject which should be part of header, please note that this string is used for find the certificate on client machine
            //string subject = "Workspace.ceb.com";
            // current (universal) date time value has to be attached while creating the signature
            string message = string.Format("{0}{1}", Utils.Constants.WorkspaceSignature, string.Format("{0:d/M/yyyyHH:mm}", DateTime.Now.ToUniversalTime()));

            message = message.Replace("-", "/");
            // Find the certificate we'll use to sign
            AsymmetricAlgorithm privateKey = null;
            //Get Private Key from Applciation object. If its null, then open the X509 store and get private key.
            //privateKey = HttpContext.Current.Application[Utils.Constants.PrivateKeyFromCertificate] as AsymmetricAlgorithm;
            //if (privateKey == null)
            //{
            StoreName     storeName;
            StoreLocation storeLocation;

            //try to parse
            Enum.TryParse(storeNameValue, true, out storeName);
            if (!Enum.IsDefined(typeof(StoreName), storeName)) //If it was failed to parse then the variable storeName is not set as defined
            {
                throw new Exception(Utils.Constants.CertStoreNameNotFoundExceptionMessage);
            }

            //try to parse
            Enum.TryParse(storeLocationValue, true, out storeLocation);
            if (!Enum.IsDefined(typeof(StoreLocation), storeLocation)) //If it was failed to parse then the variable storeLocation is not set as defined
            {
                throw new Exception(Utils.Constants.CertStoreLocationNotFoundExceptionMessage);
            }

            // Access Personal (MY) certificate store of current user
            X509Store my = new X509Store(storeName, storeLocation);

            my.Open(OpenFlags.ReadOnly);
            foreach (X509Certificate2 cert in my.Certificates)
            {
                if (cert.Subject.Contains(subject))
                {
                    // We found it.
                    privateKey = cert.PrivateKey;
                    break;
                }
            }
            //}
            // Get its associated CSP and private key
            csp = (RSACryptoServiceProvider)privateKey;

            if (csp == null)
            {
                //throw new Exception(Utils.Constants.CertNotFoundExceptionMessage);
            }
            // Hash the data
            sha1 = new SHA1Managed();
            UnicodeEncoding encoding = new UnicodeEncoding();

            byte[] data = encoding.GetBytes(message);
            byte[] hash = sha1.ComputeHash(data);
            // Sign the hash
            byte[] encryptedData = csp.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));
            return(Convert.ToBase64String(encryptedData));
        }
Exemple #5
0
        public bool VerifyData(byte[] dataToCheck, byte[] signedData)
        {
            var key = (RSACryptoServiceProvider)Certyficate.PublicKey.Key;

            return(key.VerifyData(dataToCheck, CryptoConfig.MapNameToOID("SHA256"), signedData));
        }
Exemple #6
0
 public static string ToMd5(string clearString)
 {
     byte[] bytes = Encoding.Unicode.GetBytes(clearString);
     return(BitConverter.ToString(((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(bytes)));
 }
 public static void AddAlgorithm_EmptyString_Throws()
 {
     AssertExtensions.Throws <ArgumentException>(null, () => CryptoConfig.AddAlgorithm(typeof(CryptoConfigTests), string.Empty));
 }
Exemple #8
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SymmetricCryptoService"/> class.
 /// </summary>
 /// <param name="options">The options.</param>
 public CryptoHash(string key, HashAlgorithm algorithm)
 {
     this._encryptionOptions = new CryptoConfig(true, key);
     this._algorithm = algorithm;
 }
 public static void AddAlgorithm_CreateFromName_ReturnsMapped()
 {
     CryptoConfig.AddAlgorithm(typeof(AesCryptoServiceProvider), "AESFancy");
     Assert.Equal(typeof(AesCryptoServiceProvider).FullName, CryptoConfig.CreateFromName("AESFancy").GetType().FullName);
 }
 public static void AddAlgorithm_NonVisibleType()
 {
     AssertExtensions.Throws <ArgumentException>("algorithm", () => CryptoConfig.AddAlgorithm(typeof(AESFancy), "AESFancy"));
 }
 public static void AddOID_NullNames_Throws()
 {
     AssertExtensions.Throws <ArgumentNullException>("names", () => CryptoConfig.AddOID(string.Empty, null));
 }
 public static void AddOID_NullOid_Throws()
 {
     AssertExtensions.Throws <ArgumentNullException>("oid", () => CryptoConfig.AddOID(null, string.Empty));
 }
 public static void AddOID_EmptyNamesArray()
 {
     CryptoConfig.AddOID("1.3.14.3.2.28", new string[0]);
     // There is no verifiable behavior in this case. We only check that we don't throw.
 }
Exemple #14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SymmetricCryptoService"/> class.
 /// </summary>
 /// <param name="options">The options.</param>
 public CryptoSym(string key, SymmetricAlgorithm algorithm)
 {
     _encryptionOptions = new CryptoConfig(true, key);
     _algorithm = algorithm;
 }
 public static void AddAlgorithm_EmptyNamesArray()
 {
     CryptoConfig.AddAlgorithm(typeof(AesCryptoServiceProvider), new string[0]);
     // There is no verifiable behavior in this case. We only check that we don't throw.
 }
		/// <summary>
		///     Parses a string in the format of <see cref="Encode" /> and returns an <see cref="EncryptedItem" /> with the
		///     component parts.
		/// </summary>
		/// <param name="input">a string from a prior <see cref="Encode" /></param>
		/// <returns>a populated <see cref="EncryptedItem" /></returns>
		public static EncryptedItem Parse(string input)
		{
			Match m = _prefixPattern.Match(input);
			if (! m.Success)
			{
				throw new CryptographicException("the ciphertext string does not begin with a suitably formatted algorithm marker, e.g. {AES-256-CBC}");
			}
			var config = new CryptoConfig(m.Groups[1].Value, int.Parse(m.Groups[2].Value));
			if (m.Groups[3].Success)
			{
				config.Mode = (CipherMode) Enum.Parse(typeof (CipherMode), m.Groups[3].Value);
			}
			if (m.Groups[4].Success)
			{
				config.Padding = (PaddingMode) Enum.Parse(typeof (PaddingMode), m.Groups[4].Value);
			}
			string remainder = input.Substring(m.Length);
			return new EncryptedItem(config, Convert.FromBase64String(remainder));
		}
 public static void AddAlgorithm_NullAlgorithm_Throws()
 {
     AssertExtensions.Throws <ArgumentNullException>("algorithm", () => CryptoConfig.AddAlgorithm(null, string.Empty));
 }
 public static void AddOID_EmptyString_Throws()
 {
     AssertExtensions.Throws <ArgumentException>(null, () => CryptoConfig.AddOID(string.Empty, string.Empty));
 }
 public static void AddAlgorithm_NullNames_Throws()
 {
     AssertExtensions.Throws <ArgumentNullException>("names", () => CryptoConfig.AddAlgorithm(typeof(CryptoConfigTests), null));
 }
Exemple #20
0
 public static X509Chain Create()
 {
     return((X509Chain)CryptoConfig.CreateFromName("X509Chain"));
 }
Exemple #21
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "")
            {
                MessageBox.Show("Fields cannot be blank!");
            }
            else
            {
                #region AES

                string UserEncrypted = AesCryp.Encrypt(textBox1.Text);

                string GenerateAesKey = RandomString();
                AesCryp.Key = GenerateAesKey;
                string PasswordEncrypted = AesCryp.Encrypt(textBox2.Text);
                string ResetEncrypted    = AesCryp.Encrypt(textBox3.Text);
                AesCryp.Key = "5j2gfx0y5m9mb1x6ejtz384p9b4hf5nq";
                string EncryptedAesKey = AesCryp.Encrypt(GenerateAesKey);


                #endregion AES

                #region MD5

                string username        = UserEncrypted;
                byte[] encodedPassword = new UTF8Encoding().GetBytes(username);
                byte[] hash            = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(encodedPassword);
                string encoded         = BitConverter.ToString(hash).Replace("-", string.Empty).ToLower();

                #endregion MD5

                if (Directory.Exists(@"Users\" + encoded))
                {
                    #region UserExistsWindow

                    MessageBox.Show("User Already Exists");

                    #endregion UserExistsWindow
                }
                else
                {
                    #region CreateSaltFile

                    Directory.CreateDirectory(@"Users\" + encoded);

                    int    mySalt        = SaltHash.CreateRandomSalt();
                    string stringsalt    = mySalt.ToString();
                    string saltencrypted = AesCryp.Encrypt(stringsalt);

                    File.WriteAllText("Users\\" + encoded + "\\salt.txt", saltencrypted);

                    #endregion CreateSaltFile

                    #region SaltHash

                    string readSalt    = File.ReadAllText("Users\\" + encoded + "\\salt.txt");
                    string decryptSalt = AesCryp.Decrypt(readSalt);
                    int    x           = 0;
                    Int32.TryParse(decryptSalt, out x);

                    SaltHash usr = new SaltHash(UserEncrypted, x);
                    string   strHashedUsername = usr.ComputeSaltedHash();

                    SaltHash pwd = new SaltHash(PasswordEncrypted, x);
                    string   strHashedPassword = pwd.ComputeSaltedHash();

                    SaltHash rst            = new SaltHash(ResetEncrypted, x);
                    string   strHashedReset = rst.ComputeSaltedHash();

                    string encryptUsername = AesCryp.Encrypt(strHashedUsername);

                    #endregion SaltHash

                    #region Create&Write

                    File.WriteAllText("Users\\" + encoded + "\\password.txt", strHashedPassword);
                    File.WriteAllText("Users\\" + encoded + "\\reset.txt", strHashedReset);

                    File.AppendAllText("Users\\" + encoded + "\\salt.txt", Environment.NewLine);
                    File.AppendAllText("Users\\" + encoded + "\\salt.txt", EncryptedAesKey);

                    File.AppendAllText("Users\\" + encoded + "\\salt.txt", Environment.NewLine);
                    File.AppendAllText("Users\\" + encoded + "\\salt.txt", encryptUsername);

                    Directory.CreateDirectory("Users\\" + encoded + "\\Combos");

                    MessageBox.Show("User Created Succefully!");

                    #endregion Create&Write
                }
            }
        }
Exemple #22
0
 new static public RC2 Create(String AlgName)
 {
     return((RC2)CryptoConfig.CreateFromName(AlgName));
 }
Exemple #23
0
        internal GenericHashResult ComputeFileHash(Enums.HashAlgorithm hashAlgorithm, string filePathToComputeHash,
                                                   long offset = 0, long count = 0)
        {
            if (!File.Exists(filePathToComputeHash))
            {
                return(new GenericHashResult()
                {
                    Success = false,
                    Message = $"{MessageStrings.Common_FileNotFound} \"{filePathToComputeHash}\"."
                });
            }

            GenericHashResult result  = null;
            HashAlgorithm     hashAlg = null;

#if CORERT
            switch (hashAlgorithm)
            {
            case Enums.HashAlgorithm.MD5:
                hashAlg = MD5.Create();
                break;

            case Enums.HashAlgorithm.SHA1:
                hashAlg = SHA1.Create();
                break;

            case Enums.HashAlgorithm.SHA256:
                hashAlg = SHA256.Create();
                break;

            case Enums.HashAlgorithm.SHA384:
                hashAlg = SHA384.Create();
                break;

            case Enums.HashAlgorithm.SHA512:
                hashAlg = SHA512.Create();
                break;

            case Enums.HashAlgorithm.BCrypt:
            default:
                break;
            }
#else
            hashAlg = (HashAlgorithm)CryptoConfig.CreateFromName(hashAlgorithm.ToString());
#endif

            try
            {
                byte[] hash = null;

                using (var fStream = new FileStream(filePathToComputeHash, FileMode.Open, FileAccess.Read, FileShare.None))
                {
                    //offset = (offset == 0 ? 0 : offset);
                    count            = (count == 0 ? fStream.Length : count);
                    fStream.Position = offset;
                    var buffer = new byte[(1024 * 4)];
                    var amount = (count - offset);

                    using (hashAlg)
                    {
                        var percentageDone = 0;

                        while (amount > 0)
                        {
                            var bytesRead = fStream.Read(buffer, 0, (int)Math.Min(buffer.Length, amount));

                            if (bytesRead > 0)
                            {
                                amount -= bytesRead;

                                if (amount > 0)
                                {
                                    hashAlg.TransformBlock(buffer, 0, bytesRead, buffer, 0);
                                }
                                else
                                {
                                    hashAlg.TransformFinalBlock(buffer, 0, bytesRead);
                                }

                                var tmpPercentageDone = (int)(fStream.Position * 100 / count);

                                if (tmpPercentageDone != percentageDone)
                                {
                                    percentageDone = tmpPercentageDone;

                                    RaiseOnHashProgress(percentageDone, (percentageDone != 100 ? $"Computing hash ({percentageDone}%)..." : $"Hash computed ({percentageDone}%)."));
                                }
                            }
                            else
                            {
                                throw new InvalidOperationException();
                            }
                        }

                        hash = hashAlg.Hash;
                    }
                }

                result = new GenericHashResult()
                {
                    Success    = true,
                    Message    = MessageStrings.Hash_ComputeSuccess,
                    HashString = Encoding.HighPerformanceHexadecimal.ToHexString(hash),
                    HashBytes  = hash
                };
            }
            catch (Exception ex)
            {
                result = new GenericHashResult()
                {
                    Success = false,
                    Message = ex.ToString()
                };
            }

            return(result);
        }
Exemple #24
0
 static public AsymmetricAlgorithm Create(String algName)
 {
     return((AsymmetricAlgorithm)CryptoConfig.CreateFromName(algName));
 }
Exemple #25
0
        internal GenericHashResult ComputeHash(Enums.HashAlgorithm hashAlgorithm, byte[] bytesToComputeHash,
                                               int offset = 0, int count = 0)
        {
            if (bytesToComputeHash == null || bytesToComputeHash.Length <= 0)
            {
                return(new GenericHashResult()
                {
                    Success = false,
                    Message = MessageStrings.Hash_InputRequired
                });
            }

            GenericHashResult result = null;

            try
            {
                HashAlgorithm hashAlg = null;

#if CORERT
                switch (hashAlgorithm)
                {
                case Enums.HashAlgorithm.MD5:
                    hashAlg = MD5.Create();
                    break;

                case Enums.HashAlgorithm.SHA1:
                    hashAlg = SHA1.Create();
                    break;

                case Enums.HashAlgorithm.SHA256:
                    hashAlg = SHA256.Create();
                    break;

                case Enums.HashAlgorithm.SHA384:
                    hashAlg = SHA384.Create();
                    break;

                case Enums.HashAlgorithm.SHA512:
                    hashAlg = SHA512.Create();
                    break;

                case Enums.HashAlgorithm.BCrypt:
                default:
                    break;
                }
#else
                hashAlg = (HashAlgorithm)CryptoConfig.CreateFromName(hashAlgorithm.ToString());
#endif

                using (hashAlg)
                {
                    //offset = (offset == 0 ? 0 : offset);
                    count = (count == 0 ? bytesToComputeHash.Length : count);

                    var hash = hashAlg.ComputeHash(bytesToComputeHash, offset, count);

                    result = new GenericHashResult()
                    {
                        Success    = true,
                        Message    = MessageStrings.Hash_ComputeSuccess,
                        HashBytes  = hash,
                        HashString = Encoding.HighPerformanceHexadecimal.ToHexString(hash)
                    };
                }
            }
            catch (Exception ex)
            {
                return(new GenericHashResult()
                {
                    Success = false,
                    Message = ex.ToString()
                });
            }

            return(result);
        }
Exemple #26
0
        public bool verifyotp()
        {
            if (skipotp)
            {
                return(true);
            }
            // check if is a fmuv2 and bootloader >= 4 else fail;
            // 9 = fmuv2
            // 5 = px4 1.x
            if (board_type == 9) // &&up.bl_rev >= 4
            {
                try
                {
                    // get the device sn
                    byte[] sn = __get_sn();

                    string line = "";

                    line = "SN: ";
                    for (int s = 0; s < sn.Length; s += 1)
                    {
                        line += sn[s].ToString("X2");
                    }
                    print(line);

                    // 20 bytes - sha1
                    Array.Resize(ref sn, 20);

                    if (ByteArrayCompare(sn, new byte[] { 0x00, 0x23, 0x00, 0x30, 0x35, 0x32, 0x47, 0x18, 0x36, 0x34, 0x30, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }))
                    {
                        print("Libre bootloader");
                    }

                    object obj  = new otp();
                    byte[] test = __read_otp();

                    ByteArrayToStructure(test, ref obj);

                    otp otp = (otp)obj;

                    print("id: " + otp.id_type.ToString("X"));
                    print("vid: " + otp.vid.ToString("X"));
                    print("pid: " + otp.pid.ToString("X"));

                    if (otp.h1 == 'P' &&
                        otp.h2 == 'X' &&
                        otp.h3 == '4' &&
                        otp.h4 == '\0')
                    {
                        // no vendor checks yet
                        byte[] sig = otp.signature;

                        line = "";

                        for (int s = 0; s < 512; s += 1)
                        {
                            line += test[s].ToString("X2");
                            if (s % 16 == 15)
                            {
                                print(line);
                                line = "";
                            }
                        }

                        /*
                         *                                  byte[] PEMbuffer = Convert.FromBase64String(@"");
                         */
                        //   RSACryptoServiceProvider rsa = DecodeRsaPrivateKey(PEMbuffer);

                        //   RSAParameters rsapublic = rsa.ExportParameters(false);

                        foreach (var cert in certs)
                        {
                            byte[] pubpem = Convert.FromBase64String(cert.Value);

                            AsymmetricKeyParameter asymmetricKeyParameter = PublicKeyFactory.CreateKey(pubpem);
                            RsaKeyParameters       rsaKeyParameters       = (RsaKeyParameters)asymmetricKeyParameter;
                            RSAParameters          rsaParameters          = new RSAParameters();
                            rsaParameters.Modulus  = rsaKeyParameters.Modulus.ToByteArrayUnsigned();
                            rsaParameters.Exponent = rsaKeyParameters.Exponent.ToByteArrayUnsigned();
                            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                            rsa.ImportParameters(rsaParameters);

                            bool valid = rsa.VerifyHash(sn, CryptoConfig.MapNameToOID("SHA1"), otp.signature);

                            if (valid)
                            {
                                print("Valid Key");
                                return(true);
                            }
                        }

                        print("Invalid Key");
                        throw new InvalidKeyException("Invalid Board");
                    }
                    else
                    {
                        print("Failed Header Check");
                        throw new FormatException("Failed Header Check");
                    }
                }
                catch
                {
                    print("Failed to read Certificate of Authenticity");
                    throw;
                }
            }

            // not board type 9
            return(true);
        }
 public static void AddOID_NotSupported()
 {
     Assert.Throws <PlatformNotSupportedException>(() => CryptoConfig.AddOID(string.Empty, string.Empty));
 }
Exemple #28
0
 /// <include file='doc\KeyedHashAlgorithm.uex' path='docs/doc[@for="KeyedHashAlgorithm.Create1"]/*' />
 new static public KeyedHashAlgorithm Create(String algName)
 {
     return((KeyedHashAlgorithm)CryptoConfig.CreateFromName(algName));
 }
 public static void AddAlgorithm_NotSupported()
 {
     Assert.Throws <PlatformNotSupportedException>(() => CryptoConfig.AddAlgorithm(typeof(CryptoConfigTests), string.Empty));
 }
Exemple #30
0
 /// <summary>
 /// Default options
 /// </summary>
 public CryptoSym()
 {
     _encryptionOptions = new CryptoConfig();
     _algorithm = CryptographyUtils.CreateSymmAlgoTripleDes();
 }
        public static void EncodeOID_Compat()
        {
            string actual = CryptoConfig.EncodeOID("-1.2.-3").ByteArrayToHex();

            Assert.Equal("0602DAFD", actual); // Negative values not checked
        }
Exemple #32
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SymmetricCryptoService"/> class.
 /// </summary>
 /// <param name="options">The options.</param>
 public CryptoSym(CryptoConfig options, SymmetricAlgorithm algorithm)
 {
     _encryptionOptions = options;
     _algorithm = algorithm;
 }
Exemple #33
0
 new static public SHA512 Create(String hashName)
 {
     return((SHA512)CryptoConfig.CreateFromName(hashName));
 }
Exemple #34
0
 /// <summary>
 /// Default options
 /// </summary>
 public CryptoHash()
 {
     this._encryptionOptions = new CryptoConfig();
     this._algorithm = CryptographyUtils.CreateHashAlgoMd5();
 }
Exemple #35
0
 public byte[] SingDate(byte[] dataToSign)
 {
     return(Provider.SignData(dataToSign, CryptoConfig.MapNameToOID(Algorithm)));
 }
Exemple #36
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SymmetricCryptoService"/> class.
 /// </summary>
 /// <param name="options">The options.</param>
 public CryptoHash(CryptoConfig options, HashAlgorithm algorithm)
 {
     this._encryptionOptions = options;
     this._algorithm = algorithm;
 }
 public static void AddOID_MapNameToOID_ReturnsMapped()
 {
     CryptoConfig.AddOID("1.3.14.3.2.28", "SHAFancy");
     Assert.Equal("1.3.14.3.2.28", CryptoConfig.MapNameToOID("SHAFancy"));
 }