Example #1
0
        public void TestWrongBase64()
        {
            CertificateX509 cert = new CertificateX509();

            cert.FromBase64(base64Wrong);
            Assert.IsTrue(cert.HasError());
        }
Example #2
0
        public void TestExport()
        {
            CertificateX509 cert = new CertificateX509();

            cert.Load(path);
            string base64res = cert.ToBase64();

            Assert.IsTrue(SecurityUtils.compareStrings(base64res, base64string));
            Assert.IsFalse(cert.HasError());
        }
        private bool Verify(Certificate certificate, Stream input, string signature)
        {
            CertificateX509 cert = (CertificateX509)certificate;

            if (cert.HasError())
            {
                this.error = cert.GetError();
                return(false);
            }
            string hashAlgorithm = "";

            if (SecurityUtils.compareStrings(cert.getPublicKeyHash(), "ECDSA"))
            {
                hashAlgorithm = "SHA1";
            }
            else
            {
                hashAlgorithm = cert.getPublicKeyHash();
            }
            AsymmetricSigningAlgorithm asymmetricSigningAlgorithm = AsymmetricSigningAlgorithmUtils
                                                                    .GetAsymmetricSigningAlgorithm(cert.getPublicKeyAlgorithm(), this.error);

            if (this.HasError())
            {
                return(false);
            }
            ISigner signer = AsymmetricSigningAlgorithmUtils.GetSigner(asymmetricSigningAlgorithm, GetHash(hashAlgorithm),
                                                                       this.error);

            if (this.HasError())
            {
                return(false);
            }
            SetUpSigner(signer, input, cert.getPublicKeyParameterForSigning(), false);
            if (this.HasError())
            {
                return(false);
            }
            byte[] signatureBytes = null;
            try
            {
                signatureBytes = Base64.Decode(signature);
            }
            catch (Exception e)
            {
                error.setError("AE019", e.Message);
                return(false);
            }

            if (signatureBytes == null || signatureBytes.Length == 0)
            {
                this.error.setError("AE020", "Error reading signature");
                return(false);
            }
            bool result = false;

            try
            {
                result = signer.VerifySignature(signatureBytes);
            }
            catch (Exception e)
            {
                error.setError("AE021", e.Message);
                return(false);
            }
            return(result);
        }
        /********EXTERNAL OBJECT PUBLIC METHODS  - END ********/


        /// <summary>
        /// Encrypts the string encoded plain text
        /// </summary>
        /// <param name="asymmetricEncryptionAlgorithm">string AsymmetricEncryptionAlgorithm enum, algorithm name</param>
        /// <param name="hashAlgorithm">string HashAlgorithm enum, algorithm name</param>
        /// <param name="asymmetricEncryptionPadding">string AsymmetricEncryptionPadding enum, padding name</param>
        /// <param name="keyPath">string path to key/certificate</param>
        /// <param name="isPrivate">boolean true if key is private, false if it is public</param>
        /// <param name="alias">string keystore/certificate pkcs12 format alias</param>
        /// <param name="password">Srting keysore/certificate pkcs12 format alias</param>
        /// <param name="plainText">string to encrypt</param>
        /// <returns>string Base64 encrypted plainText text</returns>
        private string DoEncryptInternal(string hashAlgorithm, string asymmetricEncryptionPadding, Key key, bool isPrivate, string plainText)
        {
            this.error.cleanError();

            HashAlgorithm hash = HashAlgorithmUtils.getHashAlgorithm(hashAlgorithm, this.error);
            AsymmetricEncryptionPadding padding = AsymmetricEncryptionPaddingUtils.getAsymmetricEncryptionPadding(asymmetricEncryptionPadding, this.error);

            if (this.error.existsError())
            {
                return("");
            }

            string asymmetricEncryptionAlgorithm = "";
            AsymmetricKeyParameter asymKey       = null;

            if (isPrivate)
            {
                PrivateKeyManager keyMan = (PrivateKeyManager)key;
                if (!keyMan.HasPrivateKey || keyMan.HasError())
                {
                    this.error = keyMan.GetError();
                    return("");
                }
                asymmetricEncryptionAlgorithm = keyMan.getPrivateKeyAlgorithm();

                asymKey = keyMan.getPrivateKeyParameterForEncryption();
                if (keyMan.HasError())
                {
                    this.error = keyMan.GetError();
                    return("");
                }
            }
            else
            {
                CertificateX509 cert = (CertificateX509)key;
                if (!cert.Inicialized || cert.HasError())
                {
                    this.error = cert.GetError();
                    return("");
                }
                asymmetricEncryptionAlgorithm = cert.getPublicKeyAlgorithm();
                asymKey = cert.getPublicKeyParameterForEncryption();
                if (cert.HasError())
                {
                    this.error = cert.GetError();
                    return("");
                }
            }

            AsymmetricEncryptionAlgorithm algorithm = AsymmetricEncryptionAlgorithmUtils
                                                      .getAsymmetricEncryptionAlgorithm(asymmetricEncryptionAlgorithm, this.error);

            try
            {
                return(doEncrypt(algorithm, hash, padding, asymKey, plainText));
            }
            catch (InvalidCipherTextException)
            {
                this.error.setError("AE036", "Algoritmo inválido" + algorithm);

                return("");
            }
        }
        private bool DoVerify(string token, string expectedAlgorithm, PrivateClaims privateClaims, JWTOptions options, bool verifyClaims, bool verifyRegClaims)
        {
            this.error.cleanError();
            if (options.HasError())
            {
                this.error = options.GetError();
                return(false);
            }
            JWTAlgorithm expectedJWTAlgorithm = JWTAlgorithmUtils.getJWTAlgorithm(expectedAlgorithm, this.error);

            if (this.HasError())
            {
                return(false);
            }

            /***Hack to support 1024 RSA key lengths - BEGIN***/
            AsymmetricSignatureProvider.DefaultMinimumAsymmetricKeySizeInBitsForVerifyingMap["RS256"] = 1024;
            AsymmetricSignatureProvider.DefaultMinimumAsymmetricKeySizeInBitsForVerifyingMap["RS512"] = 1024;
            AsymmetricSignatureProvider.DefaultMinimumAsymmetricKeySizeInBitsForVerifyingMap["RS384"] = 1024;
            /***Hack to support 1024 RSA key lengths - END***/

            /***Hack to support 192 ECDSA key lengths - BEGIN***/
            AsymmetricSignatureProvider.DefaultMinimumAsymmetricKeySizeInBitsForVerifyingMap["EcdsaSha256"] = 112;
            AsymmetricSignatureProvider.DefaultMinimumAsymmetricKeySizeInBitsForVerifyingMap["EcdsaSha512"] = 112;
            AsymmetricSignatureProvider.DefaultMinimumAsymmetricKeySizeInBitsForVerifyingMap["EcdsaSha384"] = 112;
            /***Hack to support 192 ECDSA key lengths - END***/

            /***Hack to support 192 ECDSA key lengths - BEGIN***/
            AsymmetricSignatureProvider.DefaultMinimumAsymmetricKeySizeInBitsForVerifyingMap["ES256"] = 112;
            AsymmetricSignatureProvider.DefaultMinimumAsymmetricKeySizeInBitsForVerifyingMap["ES512"] = 112;
            AsymmetricSignatureProvider.DefaultMinimumAsymmetricKeySizeInBitsForVerifyingMap["ES384"] = 112;
            /***Hack to support 192 ECDSA key lengths - END***/


            JwtSecurityTokenHandler handler  = new JwtSecurityTokenHandler();
            JwtSecurityToken        jwtToken = new JwtSecurityToken(token);

            if (isRevoqued(jwtToken, options))
            {
                return(false);
            }
            if (verifyRegClaims)
            {
                if (!validateRegisteredClaims(jwtToken, options))
                {
                    return(false);
                }
            }
            if (verifyClaims)
            {
                if (!verifyPrivateClaims(jwtToken, privateClaims, options) || !VerifyHeader(jwtToken, options))
                {
                    return(false);
                }
            }
            //if validates all registered claims and it is not on revocation list
            TokenValidationParameters parms = new TokenValidationParameters();

            parms.ValidateLifetime = false;
            parms.ValidateAudience = false;
            parms.ValidateIssuer   = false;
            parms.ValidateActor    = false;
            JWTAlgorithm alg = JWTAlgorithmUtils.getJWTAlgorithm_forVerification(jwtToken.Header.Alg, this.error);

            if (this.HasError())
            {
                return(false);
            }
            if (JWTAlgorithmUtils.getJWTAlgorithm(jwtToken.Header.Alg, this.error) != expectedJWTAlgorithm || this.HasError())
            {
                this.error.setError("JW008", "Expected algorithm does not match token algorithm");
                return(false);
            }
            SecurityKey genericKey = null;

            if (JWTAlgorithmUtils.isPrivate(alg))
            {
                CertificateX509 cert = options.GetCertificate();
                if (cert.HasError())
                {
                    this.error = cert.GetError();
                    return(false);
                }
                if (SecurityUtils.compareStrings(cert.getPublicKeyAlgorithm(), "RSA"))
                {
                    try {
                        genericKey = new RsaSecurityKey((RSA)cert.getPublicKeyJWT());
                    }
                    catch (Exception)
                    {
                        this.error = cert.GetError();
                        return(false);
                    }
                }
                else if (SecurityUtils.compareStrings(cert.getPublicKeyAlgorithm(), "ECDSA"))
                {
                    try
                    {
                        genericKey = new ECDsaSecurityKey((ECDsa)cert.getPublicKeyJWT());
                    }
                    catch (Exception)
                    {
                        this.error = cert.GetError();
                        return(false);
                    }
                }
                else
                {
                    this.error.setError("JW013", "Not recognized key algorithm");
                    return(false);
                }
            }
            else
            {
                SymmetricSecurityKey symKey = new SymmetricSecurityKey(options.getSecret());
                genericKey = symKey;
            }
            genericKey.KeyId = "256";

            SigningCredentials signingCredentials = JWTAlgorithmUtils.getSigningCredentials(alg, genericKey, this.error);

            parms.IssuerSigningKey = genericKey;
            SecurityToken validatedToken;

            try
            {
                handler.ValidateToken(token, parms, out validatedToken);
            }
            catch (Exception e)
            {
                this.error.setError("JW004", e.Message);

                return(false);
            }
            return(true);
        }