Inheritance: System.Exception
        public static RSACryptoServiceProvider GetRSACryptoServiceProviderFromPublicKey(X509Certificate2 x509Certificate2)
        {
            if (x509Certificate2 == null)
            {
                throw new ArgumentException("x509Certificate2");
            }
            if (x509Certificate2.PublicKey == null)
            {
                throw new ArgumentException("x509Certificate2.PublicKey.Key must be populated.");
            }

            try
            {
                var rsa = x509Certificate2.PublicKey.Key as RSACryptoServiceProvider;
                if (rsa != null)
                {
                    return rsa;
                }
            }
            catch (Exception ex)
            {
                var outerEx = new CryptographicException(string.Format("X509Certificate2 with thumbprint '{0}' indicates that HasPrivateKey is TRUE, but the service or account may not have access to the private key or the private key may be missing or corrupted.", x509Certificate2.Thumbprint.ToLower()), ex);
                throw outerEx;
            }
            throw new CryptographicException(string.Format("X509Certificate2 with thumbprint '{0}' does not have a valid RSA public key.", x509Certificate2.Thumbprint.ToLower()));
        }
        public void Should_Include_Operation_In_Message() {
            // Arrange
            var cryptographicException = new CryptographicException("Message");

            // Act
            var certificateException = new CertificateException("Opperation", StoreName.TrustedPeople, StoreLocation.CurrentUser, cryptographicException);

            // Assert
            certificateException.Message.ShouldContain("Message");
        }
        public void Should_Set_InnerException() {
            // Arrange
            var cryptographicException = new CryptographicException("Message");

            // Act
            var certificateException = new CertificateException("Opperation", StoreName.TrustedPeople, StoreLocation.CurrentUser, cryptographicException);

            // Assert
            certificateException.InnerException.ShouldNotBeNull();
            certificateException.InnerException.ShouldEqual(cryptographicException);
        }
        public void Should_Have_A_Descriptive_Message() {
            // Arrange
            var cryptographicException = new CryptographicException("Message");
            var messageRegex = new Regex("A cryptographic error was encountered completing the (.+) operation on the (.+) store in the (.+) location: (.+)", RegexOptions.Compiled);

            // Act
            var certificateException = new CertificateException("Opperation", StoreName.TrustedPeople, StoreLocation.CurrentUser, cryptographicException);

            // Assert
            messageRegex.IsMatch(certificateException.Message).ShouldBeTrue();
        }
        public Tuple<byte[], string> SignHash(byte[] hashedBytes, string algorithm)
        {
            if (hashedBytes == null)
            {
                throw new ArgumentNullException(nameof(hashedBytes));
            }
            if (algorithm == null)
            {
                throw new ArgumentNullException(nameof(algorithm));
            }
            algorithm = BasicHasherAlgorithms.VerifyAndMapToAlogrithm(algorithm);

#if DEBUG
            var hashHex = hashedBytes.ToHexString();
            Console.WriteLine("Signing\t" + hashHex + "\t" + algorithm);
#endif

            byte[] signedHash = null;
            try
            {
                signedHash = _privateKey.SignHash(hashedBytes, CryptoConfig.MapNameToOID(algorithm));
            }
            catch (CryptographicException ex)
            {
                if (ex.Message == "Bad Hash.")
                {
                    var cryptoEx = new CryptographicException("Bad Hash; Use BasicHasher.GetMd5HashBytes() to generate a proper hash before calling this method.");
                }
                else
                {
                    throw;
                }
            }
            
            string res2;
            if (_encoding == EncodingOption.Base64String)
            {
                res2 = Convert.ToBase64String(signedHash);
            }
            else if (_encoding == EncodingOption.HexString)
            {
                res2 = signedHash.ToHexString();
            }
            else
            {
                throw new NotImplementedException(_encoding.ToString());
            }            
#if DEBUG
            Console.WriteLine("Signed\t" + hashHex + "\t" + algorithm + "\tresult\t" + res2);
#endif
            return new Tuple<byte[], string>(signedHash, res2);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Does not throw on api error. Returns default(bool?) and sets "exception" instead. 
        /// </summary>
        public bool? Verify(X509VerificationFlags flags, out Exception exception)
        {
            exception = null;

            CERT_CHAIN_POLICY_PARA para = new CERT_CHAIN_POLICY_PARA()
            {
                cbSize = Marshal.SizeOf<CERT_CHAIN_POLICY_PARA>(),
                dwFlags = (int)flags,
            };

            CERT_CHAIN_POLICY_STATUS status = new CERT_CHAIN_POLICY_STATUS()
            {
                cbSize = Marshal.SizeOf<CERT_CHAIN_POLICY_STATUS>(),
            };

            if (!Interop.crypt32.CertVerifyCertificateChainPolicy(ChainPolicy.CERT_CHAIN_POLICY_BASE, _chain, ref para, ref status))
            {
                int errorCode = Marshal.GetLastWin32Error();
                exception = new CryptographicException(errorCode);
                return default(bool?);
            }
            return status.dwError == 0;
        }
Exemplo n.º 7
0
 public static CryptographicException/*!*/ Create(RubyClass/*!*/ self, [DefaultProtocol, DefaultParameterValue(null)]MutableString message) {
     CryptographicException result = new CryptographicException(RubyExceptions.MakeMessage(ref message, "Not enought data."));
     RubyExceptionData.InitializeException(result, message);
     return result;
 }
Exemplo n.º 8
0
        /// <summary>
        /// Initialize the provider
        /// </summary>
        void IValidator.Init( XmlNode config )
        {
            //  get the xml node that holds the key (might be empty)
            XmlNode keyNode = config.SelectSingleNode( "key" );

            //  look for key in xml
            _key = ExtractKeyFromNode( keyNode );

            //  we've tried to find key in "key" nodes, we should have a good key now; check to be sure
            if ( null == _key )
            {
                string error = ApplicationUpdateManager.TraceWrite( "[KeyValidator.Init]", "RES_CouldNotFindCryptographicKey" );

                CryptographicException ce = new CryptographicException( error );
                ExceptionManager.Publish( ce );
                throw ce;
            }
        }
Exemplo n.º 9
0
 internal virtual void PrepareSession()
 {
     if (this.WebSession == null)
     {
         this.WebSession = new WebRequestSession();
     }
     if (this.SessionVariable != null)
     {
         base.SessionState.PSVariable.Set(this.SessionVariable, this.WebSession);
     }
     if (this.Credential != null)
     {
         NetworkCredential networkCredential = this.Credential.GetNetworkCredential();
         this.WebSession.Credentials = networkCredential;
         this.WebSession.UseDefaultCredentials = false;
     }
     else if (this.UseDefaultCredentials != 0)
     {
         this.WebSession.UseDefaultCredentials = true;
     }
     if (this.CertificateThumbprint != null)
     {
         X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
         store.Open(OpenFlags.OpenExistingOnly);
         X509Certificate2Collection certificates2 = store.Certificates.Find(X509FindType.FindByThumbprint, this.CertificateThumbprint, false);
         if (certificates2.Count == 0)
         {
             CryptographicException exception = new CryptographicException(WebCmdletStrings.ThumbprintNotFound);
             throw exception;
         }
         X509Certificate2Enumerator enumerator = certificates2.GetEnumerator();
         while (enumerator.MoveNext())
         {
             X509Certificate current = enumerator.Current;
             this.WebSession.AddCertificate(current);
         }
     }
     if (this.Certificate != null)
     {
         this.WebSession.AddCertificate(this.Certificate);
     }
     if (this.UserAgent != null)
     {
         this.WebSession.UserAgent = this.UserAgent;
     }
     if (null != this.Proxy)
     {
         WebProxy proxy = new WebProxy(this.Proxy) {
             BypassProxyOnLocal = false
         };
         if (this.ProxyCredential != null)
         {
             proxy.Credentials = this.ProxyCredential.GetNetworkCredential();
             proxy.UseDefaultCredentials = false;
         }
         else if (this.ProxyUseDefaultCredentials != 0)
         {
             proxy.UseDefaultCredentials = true;
         }
         this.WebSession.Proxy = proxy;
     }
     if (-1 < this.MaximumRedirection)
     {
         this.WebSession.MaximumRedirection = this.MaximumRedirection;
     }
     if (this.Headers != null)
     {
         foreach (string str in this.Headers.Keys)
         {
             this.WebSession.Headers[str] = (string) this.Headers[str];
         }
     }
 }
 public CertificateException(string operation, StoreName storeName, StoreLocation storeLocation,
     CryptographicException innerException)
     : base(string.Format(CryptographicMessageFormat, storeName, storeLocation, innerException.Message, operation), innerException) { }
Exemplo n.º 11
0
        private static void HandleCryptoException(CryptographicException e)
        {
            string template = GetTemplate("ERROR");

            /*
             * The string returned in this sample is mostly to demonstrate
             * how to retrieve the exception properties.  Your application
             * should display user-friendly messages.
             */

            string content = String.Format(
                "\nA Cryptographic error occurred. Check to make sure that you have a certificate (.p12) file at the location supplied in the configuration file.  Error Message:'{0}'\n\nStack Trace:" +
                "'{1}'.", e.Message, e.StackTrace);

            Console.WriteLine(template, content);
        }
Exemplo n.º 12
0
        internal virtual void PrepareSession()
        {
            // make sure we have a valid WebRequestSession object to work with
            if (null == WebSession)
            {
                WebSession = new WebRequestSession();
            }

            if (null != SessionVariable)
            {
                // save the session back to the PS environment if requested
                PSVariableIntrinsics vi = SessionState.PSVariable;
                vi.Set(SessionVariable, WebSession);
            }

            //
            // handle credentials
            //
            if (null != Credential)
            {
                // get the relevant NetworkCredential
                NetworkCredential netCred = Credential.GetNetworkCredential();
                WebSession.Credentials = netCred;

                // supplying a credential overrides the UseDefaultCredentials setting
                WebSession.UseDefaultCredentials = false;
            }
            else if (UseDefaultCredentials)
            {
                WebSession.UseDefaultCredentials = true;
            }


            if (null != CertificateThumbprint)
            {
                X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates;
                X509Certificate2Collection tbCollection = (X509Certificate2Collection)collection.Find(X509FindType.FindByThumbprint, CertificateThumbprint, false);
                if (tbCollection.Count == 0)
                {
                    CryptographicException ex = new CryptographicException(WebCmdletStrings.ThumbprintNotFound);
                    throw ex;
                }
                foreach (X509Certificate2 tbCert in tbCollection)
                {
                    X509Certificate certificate = (X509Certificate)tbCert;
                    WebSession.AddCertificate(certificate);
                }
            }

            if (null != Certificate)
            {
                WebSession.AddCertificate(Certificate);
            }

            //
            // handle the user agent
            //
            if (null != UserAgent)
            {
                // store the UserAgent string
                WebSession.UserAgent = UserAgent;
            }

            if (null != Proxy)
            {
                WebProxy webProxy = new WebProxy(Proxy);
                webProxy.BypassProxyOnLocal = false;
                if (null != ProxyCredential)
                {
                    webProxy.Credentials = ProxyCredential.GetNetworkCredential();
                }
                else if (ProxyUseDefaultCredentials)
                {
                    // If both ProxyCredential and ProxyUseDefaultCredentials are passed,
                    // UseDefaultCredentials will overwrite the supplied credentials.
                    webProxy.UseDefaultCredentials = true;
                }
                WebSession.Proxy = webProxy;
            }

            if (-1 < MaximumRedirection)
            {
                WebSession.MaximumRedirection = MaximumRedirection;
            }

            // store the other supplied headers
            if (null != Headers)
            {
                foreach (string key in Headers.Keys)
                {
                    // add the header value (or overwrite it if already present)
                    WebSession.Headers[key] = Headers[key].ToString();
                }
            }
        }
        public string SignMd5Hash(byte[] hashedBytes)
        {
            byte[] signedHash = null;
            try
            {
                signedHash = _privateKey.SignHash(hashedBytes, CryptoConfig.MapNameToOID("MD5"));
            }
            catch(CryptographicException ex)
            {
                if(ex.Message == "Bad Hash.")
                {
                    var cryptoEx = new CryptographicException("Bad Hash; Use BasicHasher.GetMd5HashBytes() to generate a proper hash before calling this method.");
                }
                else
                {
                    throw;
                }
            }

            if (_encoding == EncodingOption.Base64String)
            {
                return Convert.ToBase64String(signedHash);
            }
            else if (_encoding == EncodingOption.HexString)
            {
                return signedHash.ToHexString();
            }
            else
            {
                throw new NotImplementedException(_encoding.ToString());
            }
            //return signedHash.ToHexString();
        }