/// <summary>The encryption of a digest it the atomic operation done by the SSCD.</summary>
 /// <remarks>
 /// The encryption of a digest it the atomic operation done by the SSCD. This encryption (RSA, DSA, ...) create the
 /// signature value.
 /// </remarks>
 /// <param name="digest"></param>
 /// <param name="keyEntry"></param>
 /// <returns></returns>
 /// <exception cref="Sharpen.NoSuchAlgorithmException">Sharpen.NoSuchAlgorithmException
 /// 	</exception>
 public virtual byte[] EncryptDigest(Digest digest, IDssPrivateKeyEntry keyEntry)
 {
     return this.EncryptDigest(digest.GetValue(), digest.GetAlgorithm(), keyEntry);
 }
Ejemplo n.º 2
0
        public static byte[] Encrypt(this IDssPrivateKeyEntry keyEntry, byte[] digestValue)
        {
            IBufferedCipher cipher = CipherUtilities.GetCipher(
                keyEntry.GetSignatureAlgorithm().GetPadding());

            cipher.Init(true, ((KSPrivateKeyEntry)keyEntry).PrivateKey);
            return(cipher.DoFinal(digestValue));
        }
 /// <exception cref="Sharpen.NoSuchAlgorithmException"></exception>
 /// <exception cref="System.IO.IOException"></exception>
 public virtual byte[] Sign(Stream stream, DigestAlgorithm digestAlgo, IDssPrivateKeyEntry
      keyEntry)
 {
     if (SignatureAlgorithm.RSA == keyEntry.GetSignatureAlgorithm())
     {
         IDigest digester = DigestUtilities.GetDigest(digestAlgo.GetName());
         byte[] buffer = new byte[4096];
         int count = 0;
         while ((count = stream.Read(buffer, 0, buffer.Length)) > 0)
         {
             digester.BlockUpdate(buffer, 0, count);
         }
         byte[] digestValue = DigestUtilities.DoFinal(digester);
         return EncryptDigest(digestValue, digestAlgo, keyEntry);
     }
     else
     {
         //jbonilla
         throw new System.NotImplementedException("Implementar cuando no es RSA");
         //Sharpen.Signature signature = Sharpen.Signature.GetInstance(keyEntry.GetSignatureAlgorithm
         //    ().GetJavaSignatureAlgorithm(digestAlgo));
         //try
         //{
         //    signature.InitSign(((KSPrivateKeyEntry)keyEntry).GetPrivateKey());
         //    byte[] buffer = new byte[4096];
         //    int count = 0;
         //    while ((count = stream.Read(buffer)) > 0)
         //    {
         //        signature.Update(buffer, 0, count);
         //    }
         //    byte[] signValue = signature.Sign();
         //    return signValue;
         //}
         //catch (SignatureException e)
         //{
         //    throw new RuntimeException(e);
         //}
         //catch (InvalidKeyException e)
         //{
         //    throw new RuntimeException(e);
         //}
     }
 }
Ejemplo n.º 4
0
        public byte[] Sign(Stream stream, DigestAlgorithm digestAlgo, IDssPrivateKeyEntry keyEntry)
        {
            byte[] signedBytes;

            if (keyEntry is KSX509Certificate2Entry)
            {
                var cert = ((KSX509Certificate2Entry)keyEntry).Cert2;

                X509Certificate2Signature signer = new X509Certificate2Signature(cert, digestAlgo.GetName());

                signedBytes = signer.Sign(Streams.ReadAll(stream));

                stream.Close();

                return(signedBytes);
            }

            throw new ArgumentException("Only allowed KSX509Certificate2Entry", "keyEntry");
        }
Ejemplo n.º 5
0
 /// <exception cref="Sharpen.NoSuchAlgorithmException"></exception>
 /// <exception cref="System.IO.IOException"></exception>
 public virtual byte[] Sign(Stream stream, DigestAlgorithm digestAlgo, IDssPrivateKeyEntry
                            keyEntry)
 {
     if (SignatureAlgorithm.RSA == keyEntry.GetSignatureAlgorithm())
     {
         IDigest digester = DigestUtilities.GetDigest(digestAlgo.GetName());
         byte[]  buffer   = new byte[4096];
         int     count    = 0;
         while ((count = stream.Read(buffer, 0, buffer.Length)) > 0)
         {
             digester.BlockUpdate(buffer, 0, count);
         }
         byte[] digestValue = DigestUtilities.DoFinal(digester);
         return(EncryptDigest(digestValue, digestAlgo, keyEntry));
     }
     else
     {
         //jbonilla
         throw new System.NotImplementedException("Implementar cuando no es RSA");
         //Sharpen.Signature signature = Sharpen.Signature.GetInstance(keyEntry.GetSignatureAlgorithm
         //    ().GetJavaSignatureAlgorithm(digestAlgo));
         //try
         //{
         //    signature.InitSign(((KSPrivateKeyEntry)keyEntry).GetPrivateKey());
         //    byte[] buffer = new byte[4096];
         //    int count = 0;
         //    while ((count = stream.Read(buffer)) > 0)
         //    {
         //        signature.Update(buffer, 0, count);
         //    }
         //    byte[] signValue = signature.Sign();
         //    return signValue;
         //}
         //catch (SignatureException e)
         //{
         //    throw new RuntimeException(e);
         //}
         //catch (InvalidKeyException e)
         //{
         //    throw new RuntimeException(e);
         //}
     }
 }
Ejemplo n.º 6
0
        public byte[] Sign(Stream stream, DigestAlgorithm digestAlgo, IDssPrivateKeyEntry keyEntry)
        {
            byte[] signedBytes;

            if (keyEntry is KSX509Certificate2Entry)
            {
                var cert = ((KSX509Certificate2Entry)keyEntry).Cert2;

                X509Certificate2Signature signer = new X509Certificate2Signature(cert, digestAlgo.GetName());

                signedBytes = signer.Sign(Streams.ReadAll(stream));

                stream.Close();

                return signedBytes;
            }

            throw new ArgumentException("Only allowed KSX509Certificate2Entry", "keyEntry");
        }
Ejemplo n.º 7
0
        /// <exception cref="Sharpen.NoSuchAlgorithmException"></exception>
        public override byte[] EncryptDigest(byte[] digestValue, DigestAlgorithm digestAlgo
                                             , IDssPrivateKeyEntry keyEntry)
        {
            try
            {
                DigestInfo digestInfo = new DigestInfo(digestAlgo.GetAlgorithmIdentifier(), digestValue
                                                       );

                //Sharpen.Cipher cipher = Sharpen.Cipher.GetInstance(keyEntry.GetSignatureAlgorithm
                //    ().GetPadding());

                IBufferedCipher cipher = CipherUtilities.GetCipher(keyEntry.GetSignatureAlgorithm
                                                                       ().GetPadding());

                //cipher.Init(Sharpen.Cipher.ENCRYPT_MODE, ((KSPrivateKeyEntry)keyEntry).GetPrivateKey
                //    ());

                cipher.Init(true, ((KSPrivateKeyEntry)keyEntry).PrivateKey);

                return(cipher.DoFinal(digestInfo.GetDerEncoded()));
            }

            /*catch (NoSuchPaddingException e)
             * {
             *  throw new RuntimeException(e);
             * }*/
            catch (InvalidKeyException e)
            {
                throw new RuntimeException(e);
            }

            /*catch (IllegalBlockSizeException e)
             * {
             *  throw new RuntimeException(e);
             * }
             * catch (BadPaddingException)
             * {
             *  // More likely the password is not good.
             *  throw new BadPasswordException(BadPasswordException.MSG.PKCS12_BAD_PASSWORD);
             * }*/
        }
 /// <summary>The encryption of a digest it the atomic operation done by the SSCD.</summary>
 /// <remarks>
 /// The encryption of a digest it the atomic operation done by the SSCD. This encryption (RSA, DSA, ...) create the
 /// signature value.
 /// </remarks>
 /// <param name="digestValue"></param>
 /// <param name="digestAlgo"></param>
 /// <param name="keyEntry"></param>
 /// <returns></returns>
 /// <exception cref="Sharpen.NoSuchAlgorithmException"></exception>
 public abstract byte[] EncryptDigest(byte[] digestValue, DigestAlgorithm digestAlgo
     , IDssPrivateKeyEntry keyEntry);
        /// <exception cref="Sharpen.NoSuchAlgorithmException"></exception>
        public override byte[] EncryptDigest(byte[] digestValue, DigestAlgorithm digestAlgo
                                             , IDssPrivateKeyEntry keyEntry)
        {
            try
            {
                ByteArrayOutputStream digestInfo = new ByteArrayOutputStream();
                //jbonilla: cambio de enum a clase.
                if (digestAlgo.Equals(DigestAlgorithm.SHA1))
                {
                    digestInfo.Write(Constants.SHA1_DIGEST_INFO_PREFIX);
                }
                else
                {
                    if (digestAlgo.Equals(DigestAlgorithm.SHA256))
                    {
                        digestInfo.Write(Constants.SHA256_DIGEST_INFO_PREFIX);
                    }
                    else
                    {
                        if (digestAlgo.Equals(DigestAlgorithm.SHA256))
                        {
                            digestInfo.Write(Constants.SHA512_DIGEST_INFO_PREFIX);
                        }
                    }
                }
                digestInfo.Write(digestValue);
                //Sharpen.Cipher cipher = Sharpen.Cipher.GetInstance(keyEntry.GetSignatureAlgorithm
                //    ().GetPadding());
                IBufferedCipher cipher = CipherUtilities.GetCipher(keyEntry.GetSignatureAlgorithm
                                                                       ().GetPadding());

                //cipher.Init(Sharpen.Cipher.ENCRYPT_MODE, ((KSPrivateKeyEntry)keyEntry).GetPrivateKey
                //    ());
                cipher.Init(true, ((KSPrivateKeyEntry)keyEntry).PrivateKey);
                return(cipher.DoFinal(digestInfo.ToByteArray()));
            }
            catch (IOException e)
            {
                // Writing in a ByteArrayOutputStream. Should never happens.
                throw new RuntimeException(e);
            }

            /*catch (NoSuchPaddingException e)
             * {
             *  throw new RuntimeException(e);
             * }*/
            catch (InvalidKeyException e)
            {
                throw new RuntimeException(e);
            }

            /*catch (IllegalBlockSizeException e)
             * {
             *  throw new RuntimeException(e);
             * }
             * catch (BadPaddingException)
             * {
             *  // More likely the password is not good.
             *  throw new BadPasswordException(BadPasswordException.MSG.PKCS12_BAD_PASSWORD);
             * }*/
        }
Ejemplo n.º 10
0
 /// <summary>The encryption of a digest it the atomic operation done by the SSCD.</summary>
 /// <remarks>
 /// The encryption of a digest it the atomic operation done by the SSCD. This encryption (RSA, DSA, ...) create the
 /// signature value.
 /// </remarks>
 /// <param name="digest"></param>
 /// <param name="keyEntry"></param>
 /// <returns></returns>
 /// <exception cref="Sharpen.NoSuchAlgorithmException">Sharpen.NoSuchAlgorithmException
 ///     </exception>
 public virtual byte[] EncryptDigest(Digest digest, IDssPrivateKeyEntry keyEntry)
 {
     return(this.EncryptDigest(digest.GetValue(), digest.GetAlgorithm(), keyEntry));
 }
Ejemplo n.º 11
0
 /// <summary>The encryption of a digest it the atomic operation done by the SSCD.</summary>
 /// <remarks>
 /// The encryption of a digest it the atomic operation done by the SSCD. This encryption (RSA, DSA, ...) create the
 /// signature value.
 /// </remarks>
 /// <param name="digestValue"></param>
 /// <param name="digestAlgo"></param>
 /// <param name="keyEntry"></param>
 /// <returns></returns>
 /// <exception cref="Sharpen.NoSuchAlgorithmException"></exception>
 public abstract byte[] EncryptDigest(byte[] digestValue, DigestAlgorithm digestAlgo
                                      , IDssPrivateKeyEntry keyEntry);
Ejemplo n.º 12
0
        /// <exception cref="Sharpen.NoSuchAlgorithmException"></exception>
        public override byte[] EncryptDigest(byte[] digestValue, DigestAlgorithm digestAlgo
            , IDssPrivateKeyEntry keyEntry)
        {
            try
            {
                ByteArrayOutputStream digestInfo = new ByteArrayOutputStream();
                //jbonilla: cambio de enum a clase.
                if (digestAlgo.Equals(DigestAlgorithm.SHA1))
                {
                    digestInfo.Write(Constants.SHA1_DIGEST_INFO_PREFIX);
                }
                else
                {
                    if (digestAlgo.Equals(DigestAlgorithm.SHA256))
                    {
                        digestInfo.Write(Constants.SHA256_DIGEST_INFO_PREFIX);
                    }
                    else
                    {
                        if (digestAlgo.Equals(DigestAlgorithm.SHA256))
                        {
                            digestInfo.Write(Constants.SHA512_DIGEST_INFO_PREFIX);
                        }
                    }
                }
                digestInfo.Write(digestValue);
                //Sharpen.Cipher cipher = Sharpen.Cipher.GetInstance(keyEntry.GetSignatureAlgorithm
                //    ().GetPadding());
                IBufferedCipher cipher = CipherUtilities.GetCipher(keyEntry.GetSignatureAlgorithm
                    ().GetPadding());

                //cipher.Init(Sharpen.Cipher.ENCRYPT_MODE, ((KSPrivateKeyEntry)keyEntry).GetPrivateKey
                //    ());
                cipher.Init(true, ((KSPrivateKeyEntry)keyEntry).PrivateKey);
                return cipher.DoFinal(digestInfo.ToByteArray());
            }
            catch (IOException e)
            {
                // Writing in a ByteArrayOutputStream. Should never happens.
                throw new RuntimeException(e);
            }
            /*catch (NoSuchPaddingException e)
            {
                throw new RuntimeException(e);
            }*/
            catch (InvalidKeyException e)
            {
                throw new RuntimeException(e);
            }
            /*catch (IllegalBlockSizeException e)
            {
                throw new RuntimeException(e);
            }
            catch (BadPaddingException)
            {
                // More likely the password is not good.
                throw new BadPasswordException(BadPasswordException.MSG.PKCS12_BAD_PASSWORD);
            }*/
        }
Ejemplo n.º 13
0
        /// <exception cref="Sharpen.NoSuchAlgorithmException"></exception>
        public override byte[] EncryptDigest(byte[] digestValue, DigestAlgorithm digestAlgo
            , IDssPrivateKeyEntry keyEntry)
        {
            try
            {
                DigestInfo digestInfo = new DigestInfo(digestAlgo.GetAlgorithmIdentifier(), digestValue
                    );

                //Sharpen.Cipher cipher = Sharpen.Cipher.GetInstance(keyEntry.GetSignatureAlgorithm
                //    ().GetPadding());

                IBufferedCipher cipher = CipherUtilities.GetCipher(keyEntry.GetSignatureAlgorithm
                    ().GetPadding());

                //cipher.Init(Sharpen.Cipher.ENCRYPT_MODE, ((KSPrivateKeyEntry)keyEntry).GetPrivateKey
                //    ());

                cipher.Init(true, ((KSPrivateKeyEntry)keyEntry).PrivateKey);

                return cipher.DoFinal(digestInfo.GetDerEncoded());
            }
            /*catch (NoSuchPaddingException e)
            {
                throw new RuntimeException(e);
            }*/
            catch (InvalidKeyException e)
            {
                throw new RuntimeException(e);
            }
            /*catch (IllegalBlockSizeException e)
            {
                throw new RuntimeException(e);
            }
            catch (BadPaddingException)
            {
                // More likely the password is not good.
                throw new BadPasswordException(BadPasswordException.MSG.PKCS12_BAD_PASSWORD);
            }*/
        }
Ejemplo n.º 14
0
        static void Main(string[] args)
        {
            string pathToSign      = Path.Combine("Resources", "test.pdf");
            string pathCertificate = Path.Combine("Resources", "test.p12");
            string pathSigned      = "test.pdf.p7m";

            Document             toBeSigned = new FileDocument(pathToSign);
            Pkcs12SignatureToken token      = new Pkcs12SignatureToken("password", pathCertificate);
            IDssPrivateKeyEntry  privateKey = token.GetKeys()[0];

            SignatureParameters parameters = new SignatureParameters();

            parameters.SignaturePackaging = SignaturePackaging.ENVELOPING;
            parameters.SigningCertificate = privateKey.GetCertificate();
            parameters.CertificateChain   = privateKey.GetCertificateChain();
            parameters.SigningDate        = DateTime.Now;
            parameters.DigestAlgorithm    = DigestAlgorithm.SHA256;

            CAdESService service = new CAdESService();

            parameters.SignatureFormat = EU.Europa.EC.Markt.Dss.Signature.SignatureFormat.CAdES_BES;

            /* CERTIFIED TIMESTAMP
             * var ocspSource1 = new OnlineOcspSource();
             * var crlSource1 = new FileCacheCrlSource();
             * var crlOnline1 = new OnlineCrlSource();
             * crlOnline1.IntermediateAcUrl = @"http://www.eci.bce.ec/CRL/cacrl.crl";
             * crlSource1.CachedSource = crlOnline1;
             * var verifier1 = new OCSPAndCRLCertificateVerifier(crlSource1, ocspSource1);
             * var estado = verifier1.Check(privateKey.GetCertificate(), privateKey.GetCertificateChain()[1], DateTime.Now);
             */

            /*
             * //parameters.SignatureFormat = SignatureFormat.CAdES_T; //Se añade TSA.
             * parameters.SignatureFormat = EU.Europa.EC.Markt.Dss.Signature.SignatureFormat.CAdES_C; //Se añade CRL y OCSP.
             * //parameters.SignatureFormat = SignatureFormat.CAdES_X; //No se añade nada más al código.
             * //parameters.SignatureFormat = EU.Europa.EC.Markt.Dss.Signature.SignatureFormat.CAdES_XL; //No se añade nada más al código.
             *
             * string urlTss = @"http://tsp.iaik.tugraz.at/tsp/TspRequest";
             * string username = "";
             * string password = "";
             *
             *
             * OnlineTspSource tspSource = new OnlineTspSource(urlTss, username, password);
             * service.TspSource = tspSource;
             *
             * OnlineOcspSource ocspSource = new OnlineOcspSource();
             * TrustedListCertificateVerifier verifier = new TrustedListCertificateVerifier();
             * FileCacheCrlSource crlSource = new FileCacheCrlSource();
             * OnlineCrlSource crlOnline = new OnlineCrlSource();
             * crlOnline.IntermediateAcUrl = @"http://www.eci.bce.ec/CRL/cacrl.crl";
             * //@"http://www.eci.bce.ec/CRL/pruebas/cacrl.crl"
             *
             * crlSource.CachedSource = crlOnline;
             * verifier.CrlSource = crlSource;
             * verifier.OcspSource = ocspSource;
             *
             * ValidationContext validationContext = verifier.ValidateCertificate(parameters.SigningCertificate, DateTime.Now,
             *  new EU.Europa.EC.Markt.Dss.Validation.Certificate.CompositeCertificateSource(
             *      new EU.Europa.EC.Markt.Dss.Validation.Certificate.ListCertificateSource(parameters.CertificateChain)), null, null);
             *
             * service.Verifier = verifier;
             */

            /* DOUBLE-SIGN
             * Document contentInCMS = null;
             *
             * try
             * {
             *  CmsSignedData cmsData = new CmsSignedData(toBeSigned.OpenStream());
             *  if (cmsData != null && cmsData.SignedContent != null
             *      && cmsData.SignedContent.GetContent() != null)
             *  {
             *      Stream buf = new MemoryStream();
             *      cmsData.SignedContent.Write(buf);
             *      buf.Seek(0, SeekOrigin.Begin);
             *      contentInCMS = new InMemoryDocument(Streams.ReadAll(buf));
             *  }
             * }
             * catch (CmsException)
             * {
             * }
             *
             * Stream iStream = service.ToBeSigned(contentInCMS ?? toBeSigned, parameters);
             * byte[] signatureValue = token.Sign(iStream, parameters.DigestAlgorithm, privateKey);
             *
             * // We invoke the service to sign the document with the signature value obtained in the previous step.
             * Document signedDocument = contentInCMS != null
             *  ? service.AddASignatureToDocument(toBeSigned, parameters, signatureValue)
             *  : service.SignDocument(toBeSigned, parameters, signatureValue);
             *
             * FileStream fs = new FileStream(pathParaFirmado, FileMode.OpenOrCreate);
             * Streams.PipeAll(signedDocument.OpenStream(), fs);
             * fs.Close();
             * return;
             */

            Document signedDocument = service.SignDocument(toBeSigned, parameters,
                                                           (hashbytes) => privateKey.Encrypt(hashbytes));

            FileStream fs = new FileStream(pathSigned, FileMode.OpenOrCreate);

            Streams.PipeAll(signedDocument.OpenStream(), fs);
            fs.Close();

            return;

            // Already signed document
            Document document = new FileDocument(pathSigned);

            SignedDocumentValidator validator;

            validator = SignedDocumentValidator.FromDocument(document);
            //validator.CertificateVerifier = verifier;
            validator.ExternalContent = document;

            ValidationReport     report = validator.ValidateDocument();
            SignatureInformation info   = report.SignatureInformationList[0];

            Console.WriteLine("--> Final_Conclusion: ");
            Console.WriteLine(info.FinalConclusion); // --> AdES
            Console.ReadKey();
        }
Ejemplo n.º 15
0
 public Document SignDocument(Document document, SignatureParameters parameters, IDssPrivateKeyEntry privateKey)
 {
     return(SignDocumentInternal(document, parameters,
                                 (bytes) => privateKey.Encrypt(bytes)));
 }