public void sect193r1()
        {
            string            pathKey  = ECDSA_path + "sect193r1" + "\\key.pem";
            string            pathCert = ECDSA_path + "sect193r1" + "\\cert.pem";
            PrivateKeyManager key      = new PrivateKeyManager();
            CertificateX509   cert     = new CertificateX509();

            key.Load(pathKey);
            cert.Load(pathCert);
            string alg   = "ES256";
            string curve = "sect193r1";

            bulkTest_shouldntWork(key, cert, alg, curve);
        }
Example #2
0
        private void bulkTestWithKeyInfoID(CertificateX509 certificate, PrivateKeyManager key, string pathSigned)
        {
            XmlDSigSigner signer       = new XmlDSigSigner();
            string        pathSignedID = pathSigned + "_id";

            for (int c = 0; c < arrayCanonicalization.Length; c++)
            {
                /**** TEST FILES ****/
                optionsID.DSigSignatureType = dSigType;
                optionsID.Canonicalization  = arrayCanonicalization[c];

                optionsID.XmlSchemaPath = xmlIDSchemaPath;
                bool signedFile = signer.DoSignFileElement(xmlUnsignedIDPathFile, id, key, certificate,
                                                           Path.Combine(xmlSignedPathRoot, pathSignedID + ".xml"), optionsID);
                Assert.IsTrue(signedFile);
                True(signedFile, signer);

                bool verifyFile = false;
                optionsID.XmlSchemaPath = "";
                KeyInfoType keyInfo = KeyInfoTypeUtils.getKeyInfoType(optionsID.KeyInfoType, error);
                if (keyInfo != KeyInfoType.NONE)
                {
                    verifyFile = signer.DoVerifyFile(Path.Combine(xmlSignedPathRoot, pathSignedID + ".xml"), optionsID);
                }
                else
                {
                    verifyFile = signer.DoVerifyFileWithCert(Path.Combine(xmlSignedPathRoot, pathSignedID + ".xml"), certificate,
                                                             optionsID);
                }
                True(verifyFile, signer);

                /**** TEST STRINGS ****/
                optionsID.XmlSchemaPath = xmlIDSchemaPath;
                string signedString     = signer.DoSignElement(xmlUnsignedID, id, key, certificate, optionsID);
                bool   resultSignString = false;

                optionsID.XmlSchemaPath = "";
                if (keyInfo != KeyInfoType.NONE)
                {
                    resultSignString = signer.DoVerify(signedString, optionsID);
                }
                else
                {
                    resultSignString = signer.DoVerifyWithCert(signedString, certificate, optionsID);
                }
                Assert.IsTrue(resultSignString);
                True(resultSignString, signer);
            }
        }
        public virtual void SetUp()
        {
            signer             = new XmlDSigSigner();
            path_RSA_sha1_1024 = Path.Combine(BASE_PATH, "dummycerts", "RSA_sha1_1024");
            //xmlUnsigned = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<Envelope xmlns=\"http://example.org/envelope\">"
            //		+ "  <Body>" + "    Ola mundo" + "  </Body>" + "</Envelope>";
            //dSigType = "ENVELOPED ";
            options = new DSigOptions();

            pathKey  = Path.Combine(path_RSA_sha1_1024, "sha1d_key.pem");
            pathCert = Path.Combine(path_RSA_sha1_1024, "sha1_cert.crt");

            key  = new PrivateKeyManager();
            cert = new CertificateX509();
        }
Example #4
0
        public virtual void SetUp()
        {
            cert = new CertificateX509();
            cert.Load(BASE_PATH + "dummycerts\\RSA_sha256_1024\\sha256_cert.crt");
            key = new PrivateKeyManager();
            key.Load(BASE_PATH + "dummycerts\\RSA_sha256_1024\\sha256d_key.pem");

            signer  = new XmlDSigSigner();
            options = new DSigOptions();

            options.IdentifierAttribute = "Id";

            xmlInput = "<envEvento xmlns=\"http://www.portalfiscal.inf.br/nfe\" versao=\"1.00\"><idLote>1</idLote><evento versao=\"1.00\"><infEvento Id=\"ID2102103521011431017000298855005000016601157405784801\"><cOrgao>91</cOrgao><tpAmb>1</tpAmb><CNPJ>31102046000145</CNPJ><chNFe>35210114310170002988550050000166011574057848</chNFe><dhEvento>2021-01-26T11:12:34-03:00</dhEvento><tpEvento>210210</tpEvento><nSeqEvento>1</nSeqEvento><verEvento>1.00</verEvento><detEvento versao=\"1.00\"><descEvento>Ciencia da Operacao</descEvento></detEvento></infEvento></evento></envEvento>";
            xPath    = "#ID2102103521011431017000298855005000016601157405784801";
        }
Example #5
0
        private void bulkTestWithKeyInfoXPath(CertificateX509 certificate, PrivateKeyManager key, string pathSigned)
        {
#if NETCORE
            //******Net Core no tiene habilitado usar la transform xpath******//
            Assert.IsTrue(true);
#else
            XmlDSigSigner signer = new XmlDSigSigner();

            string pathSignedXPath = pathSigned + "_xPAth";
            for (int c = 0; c < arrayCanonicalization.Length; c++)
            {
                /**** TEST FILES ****/
                optionsXPath.DSigSignatureType = dSigType;
                optionsXPath.Canonicalization  = arrayCanonicalization[c];
                bool signedFile = signer.DoSignFileElement(xmlUnsignedXPathFile, xPath, key, certificate,
                                                           Path.Combine(xmlSignedPathRoot, pathSignedXPath + ".xml"), optionsXPath);
                Assert.IsTrue(signedFile);
                True(signedFile, signer);

                bool        verifyFile = false;
                KeyInfoType keyInfo    = KeyInfoTypeUtils.getKeyInfoType(optionsXPath.KeyInfoType, error);
                if (keyInfo != KeyInfoType.NONE)
                {
                    verifyFile = signer.DoVerifyFile(Path.Combine(xmlSignedPathRoot, pathSignedXPath + ".xml"), optionsXPath);
                }
                else
                {
                    verifyFile = signer.DoVerifyFileWithCert(Path.Combine(xmlSignedPathRoot, pathSignedXPath + ".xml"), certificate,
                                                             optionsXPath);
                }
                //True(verifyFile, signer);

                /**** TEST STRINGS ****/

                string signedString     = signer.DoSignElement(xmlUnsignedXPath, xPath, key, certificate, optionsXPath);
                bool   resultSignString = false;
                if (keyInfo != KeyInfoType.NONE)
                {
                    resultSignString = signer.DoVerify(signedString, optionsXPath);
                }
                else
                {
                    resultSignString = signer.DoVerifyWithCert(signedString, certificate, optionsXPath);
                }
                //True(resultSignString, signer);
            }
#endif
        }
        public void prime192v2()
        {
            string            pathKey  = Path.Combine(ECDSA_path, "prime192v2", "key.pem");
            string            pathCert = Path.Combine(ECDSA_path, "prime192v2", "cert.pem");
            PrivateKeyManager key      = new PrivateKeyManager();
            CertificateX509   cert     = new CertificateX509();

            key.Load(pathKey);
            cert.Load(pathCert);
            string alg   = "ES256";
            string curve = "prime192v2";

#if NETCORE
            bulkTest_shouldntWork(key, cert, alg, curve);
#else
            bulkTest_shouldWork(key, cert, alg, curve);
#endif
        }
Example #7
0
        private void bulkTest(string pathCert, string pathKey, string pathSigned, bool ispkcs12, bool encrypted)
        {
            for (int k = 0; k < arrayKeyInfoType.Length; k++)
            {
                options.KeyInfoType      = arrayKeyInfoType[k];
                optionsXPath.KeyInfoType = arrayKeyInfoType[k];
                optionsID.KeyInfoType    = arrayKeyInfoType[k];
                CertificateX509 cert = new CertificateX509();
                if (ispkcs12)
                {
                    cert.LoadPKCS12(pathCert, alias, password);
                }
                else
                {
                    cert.Load(pathCert);
                }
                PrivateKeyManager key = new PrivateKeyManager();

                if (ispkcs12)
                {
                    key.LoadPKCS12(pathKey, alias, password);
                }
                else
                {
                    key.Load(pathKey);
                }

                /*if (ispkcs12)
                 * {
                 *      key.LoadPKCS12(pathKey, alias, password);
                 * }
                 * else if(encrypted)
                 * {
                 *      key.LoadEncrypted(pathKey, password);
                 * }else
                 * {
                 *      key.Load(pathKey);
                 * }*/

                bulkTestWithKeyInfo(cert, key, pathSigned);
                bulkTestWithKeyInfoXPath(cert, key, pathSigned);
                bulkTestWithKeyInfoID(cert, key, pathSigned);
            }
        }
Example #8
0
        /******** EXTERNAL OBJECT PUBLIC METHODS - END ********/

        private bool doSignFilePKCS12(string xmlFilePath, PrivateKeyManager key, CertificateX509 certificate, string dSigType, string canonicalizationType, string outputPath, string keyInfoType, string xmlSchemaPath)
        {
            if (TransformsWrapperUtils.getTransformsWrapper(dSigType, this.error) != TransformsWrapper.ENVELOPED)
            {
                error.setError("DS009", "Not implemented DSigType");
                return(false);
            }
            if (!SignatureUtils.validateExtensionXML(xmlFilePath))
            {
                this.error.setError("DS010", "Not XML file");
                return(false);
            }
            if (!certificate.Inicialized)
            {
                this.error.setError("DS011", "Certificate not loaded");
                return(false);
            }
            if (SecurityUtils.compareStrings(certificate.getPublicKeyAlgorithm(), "ECDSA"))
            {
                this.error.setError("DS004", "XML signature with ECDSA keys is not implemented on Net Framework");
                return(false);
            }

            XmlDocument xmlDoc = SignatureUtils.documentFromFile(xmlFilePath, xmlSchemaPath, this.error);

            if (this.HasError())
            {
                return(false);
            }
            string result = Sign(xmlDoc, key, certificate, dSigType, canonicalizationType, keyInfoType, "", "");

            if (result == null || SecurityUtils.compareStrings("", result))
            {
                this.error.setError("DS012", "Error generating signature");
                return(false);
            }
            else
            {
                // string prefix = "<?xml version=”1.0″ encoding=”UTF-8″ ?>".Trim();
                string prefix = "";
                return(SignatureUtils.writeToFile(result, outputPath, prefix, this.error));
            }
        }
Example #9
0
        public bool DoVerifyWithCert(string xmlSigned, CertificateX509 certificate, DSigOptions options)
        {
            this.error.cleanError();
            if (!certificate.Inicialized)
            {
                this.error.setError("DS003", "Certificate not loaded");
                return(false);
            }
            if (SecurityUtils.compareStrings(certificate.getPublicKeyAlgorithm(), "ECDSA"))
            {
                this.error.setError("DS004", "XML signature with ECDSA keys is not implemented on Net Framework");
                return(false);
            }
            XmlDocument xmlDoc = SignatureUtils.documentFromString(xmlSigned, options.XmlSchemaPath, this.error);

            if (this.HasError())
            {
                return(false);
            }
            return(verify(xmlDoc, certificate, options.IdentifierAttribute));
        }
Example #10
0
        public bool DoVerifyFileWithCert(string xmlFilePath, CertificateX509 certificate, DSigOptions options)
        {
            this.error.cleanError();
            if (!certificate.Inicialized)
            {
                this.error.setError("DS005", "Certificate not loaded");
            }
            if (SecurityUtils.compareStrings(certificate.getPublicKeyAlgorithm(), "ECDSA"))
            {
                this.error.setError("DS006", "XML signature with ECDSA keys is not implemented on Net Framework");
                return(false);
            }
            if (!SignatureUtils.validateExtensionXML(xmlFilePath))
            {
                this.error.setError("DS007", "The file is not an xml file");
                return(false);
            }
            XmlDocument xmlDoc = SignatureUtils.documentFromFile(xmlFilePath, options.XmlSchemaPath, this.error);

            return(verify(xmlDoc, certificate, options.IdentifierAttribute));
        }
        public void TestSignBase64()
        {
            CertificateX509 newCert = new CertificateX509();
            bool            loaded  = newCert.FromBase64(base64);

            Assert.IsTrue(loaded);
            True(loaded, newCert);
            PrivateKeyManager key = new PrivateKeyManager();
            bool privateLoaded    = key.Load(pathKey);

            Assert.IsTrue(privateLoaded);
            True(privateLoaded, key);
            XmlDSigSigner signer = new XmlDSigSigner();
            bool          result = signer.DoSignFile(xmlUnsignedPath, key, newCert, xmlSignedPathRoot + pathSigned, options);

            Assert.IsTrue(result);
            True(result, signer);
            bool verify = signer.DoVerifyFile(xmlSignedPathRoot + pathSigned, options);

            Assert.IsTrue(verify);
            True(verify, signer);
        }
        public bool DoVerify(CertificateX509 cert, string plainText, string signature)
        {
            /******** INPUT VERIFICATION - BEGIN ********/
            if (cert == null)
            {
                error.setError("AE009", "Certificate cannot be null");
                return(false);
            }
            if (plainText == null || plainText.Length == 0 || SecurityUtils.compareStrings("", plainText))
            {
                error.setError("AE010", "The plainText value to verify cannot be empty");
                return(false);
            }
            if (signature == null || signature.Length == 0 || SecurityUtils.compareStrings("", signature))
            {
                error.setError("AE011", "The signature value to verify cannot be empty");
                return(false);
            }
            /******** INPUT VERIFICATION - END ********/


            EncodingUtil eu = new EncodingUtil();

            byte[] inputText = eu.getBytes(plainText);
            if (eu.HasError())
            {
                this.error = eu.GetError();
                return(false);
            }
            bool result = false;

            using (Stream inputStream = new MemoryStream(inputText))
            {
                result = Verify(cert, inputStream, signature);
            }
            return(result);
        }
Example #13
0
        /******** EXTERNAL OBJECT PUBLIC METHODS - BEGIN ********/

        public bool DoSignFile(string xmlFilePath, PrivateKeyManager key, CertificateX509 certificate, string outputPath, DSigOptions options)
        {
            this.error.cleanError();
            return(doSignFilePKCS12(xmlFilePath, key, certificate, options.DSigSignatureType, options.Canonicalization, outputPath, options.KeyInfoType, options.XmlSchemaPath));
        }
 public string DoDecrypt_WithPublicKey(string hashAlgorithm, string asymmetricEncryptionPadding, CertificateX509 certificate, string encryptedInput)
 {
     if (this.HasError())
     {
         return("");
     }
     return(DoDecryptInternal(hashAlgorithm, asymmetricEncryptionPadding, certificate, false, encryptedInput));
 }
        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);
        }
Example #16
0
        private string Sign(XmlDocument xmlInput, PrivateKeyManager key, CertificateX509 certificate,
                            string dSigType, string canonicalizationType, string keyInfoType, string xpath, string id)
        {
            bool flag = inicializeInstanceVariables(key, certificate);

            if (!flag)
            {
                return("");
            }

            SignatureElementType signatureElementType;

            if (!SecurityUtils.compareStrings(xpath, ""))
            {
                if (xpath[0] == '#')
                {
                    signatureElementType = SignatureElementType.id;
                    if (id == null || SecurityUtils.compareStrings(id, ""))
                    {
                        this.error.setError("DS021", "identifier attribute name missing");
                        return("");
                    }
                }
                else
                {
                    signatureElementType = SignatureElementType.path;
                }
            }
            else
            {
                signatureElementType = SignatureElementType.document;
            }

            /***WHITESPACES***/
            xmlInput.PreserveWhitespace = true;
            CanonicalizerWrapper canon = CanonicalizerWrapperUtils.getCanonicalizerWrapper(canonicalizationType, this.error);


            CanonicalizerWrapper canonW = CanonicalizerWrapperUtils.getCanonicalizerWrapper(canonicalizationType, this.error);

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

            Reference reference = new Reference();

            XmlNode   parentNode;
            SignedXml signedXml;

            switch (signatureElementType)
            {
            case SignatureElementType.path:
                XmlNode    pathNode    = SignatureUtils.getNodeFromPath(xmlInput, xpath, this.error);
                XmlElement pathElement = pathNode as XmlElement;
                if (this.HasError() || pathElement == null)
                {
                    return("");
                }
                parentNode = pathNode.ParentNode;



                signedXml = new SignedXml(pathElement);
                XmlDsigXPathTransform XPathTransform = CreateXPathTransform(xpath);
                reference.Uri = pathNode.NamespaceURI;
                reference.AddTransform(XPathTransform);
                break;

            case SignatureElementType.id:
                XmlNode    idNode    = SignatureUtils.getNodeFromID(xmlInput, id, xpath, this.error);
                XmlElement idElement = idNode as XmlElement;

                if (this.HasError() || idElement == null)
                {
                    return("");
                }

                reference.Uri = xpath;
                signedXml     = new SignedXml(idElement);
                parentNode    = idNode.ParentNode;
                break;

            default:
                signedXml     = new SignedXml(xmlInput);
                parentNode    = xmlInput.DocumentElement;
                reference.Uri = "";
                break;
            }

            signedXml.SigningKey = this.privateKey;
            signedXml.SignedInfo.CanonicalizationMethod = CanonicalizerWrapperUtils.getCanonicalizationMethodAlorithm(canonW, this.error);
            if (this.HasError())
            {
                return("");
            }

            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();

            reference.AddTransform(env);

            addCanonTransform(reference, canonW);

            signedXml.AddReference(reference);

            KeyInfo keyInfo = createKeyInfo(certificate, keyInfoType);

            if (keyInfo != null)
            {
                signedXml.KeyInfo = keyInfo;
            }
            try
            {
                signedXml.ComputeSignature();
            }
            catch (Exception)
            {
                this.error.setError("DS023", "Error on signing");
                return("");
            }
            XmlElement xmlDigitalSignature = null;

            try
            {
                xmlDigitalSignature = signedXml.GetXml();
            }
            catch (Exception)
            {
                this.error.setError("DS028", "Error at signing");
                return("");
            }



            parentNode.AppendChild(xmlDigitalSignature);
            // xmlInput.DocumentElement.AppendChild(xmlInput.ImportNode(xmlDigitalSignature, true));


            return(SignatureUtils.XMLDocumentToString(xmlInput, this.error));
        }
Example #17
0
        private string doSignElementPKCS12(string xmlInput, string xPath, PrivateKeyManager key, CertificateX509 certificate, string dSigType, string canonicalizationType, string keyInfoType, string xmlSchemaPath, string id)
        {
            if (TransformsWrapperUtils.getTransformsWrapper(dSigType, this.error) != TransformsWrapper.ENVELOPED)
            {
                error.setError("DS017", "Not implemented DSigType");
                return("");
            }
            if (!certificate.Inicialized)
            {
                this.error.setError("DS018", "Certificate not loaded");
                return("");
            }
            if (SecurityUtils.compareStrings(certificate.getPublicKeyAlgorithm(), "ECDSA"))
            {
                this.error.setError("DS004", "XML signature with ECDSA keys is not implemented on Net Framework");
                return("");
            }
            XmlDocument xmlDoc = SignatureUtils.documentFromString(xmlInput, xmlSchemaPath, this.error);

            if (this.HasError())
            {
                return("");
            }
            return(Sign(xmlDoc, key, certificate, dSigType, canonicalizationType, keyInfoType, xPath, id));
        }
Example #18
0
 private void bulkTest(PrivateKeyManager key, CertificateX509 cert, string hashAlgorithm)
 {
     bulkTestText(key, cert, hashAlgorithm);
     bulkTestFile(key, cert, hashAlgorithm);
 }
        /********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("");
            }
        }
Example #20
0
 public string DoSign(string xmlInput, PrivateKeyManager key, CertificateX509 certificate, DSigOptions options)
 {
     this.error.cleanError();
     return(doSignPKCS12(xmlInput, key, certificate, options.DSigSignatureType, options.Canonicalization, options.KeyInfoType, options.XmlSchemaPath));
 }
Example #21
0
 public string DoSignElement(string xmlInput, string xPath, PrivateKeyManager key, CertificateX509 certificate, DSigOptions options)
 {
     this.error.cleanError();
     return(doSignElementPKCS12(xmlInput, xPath, key, certificate, options.DSigSignatureType, options.Canonicalization, options.KeyInfoType, options.XmlSchemaPath, options.IdentifierAttribute));
 }
        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);
        }
Example #23
0
 public void SetCertificate(CertificateX509 cert)
 {
     this.certificate = cert;
 }