salvando sincoar postgres

This commit is contained in:
cruales 2022-10-27 16:58:46 -05:00
commit 2bf1117b97
8730 changed files with 1177601 additions and 0 deletions

117
.svn/entries Normal file
View File

@ -0,0 +1,117 @@
10
dir
4669
svn://172.17.26.185/COMACO/sources
svn://172.17.26.185/COMACO
2022-04-19T03:16:43.485564Z
4669
usermaia1
a11ad980-3ca8-45f0-88f7-f0e618c262b7
frontend
dir
tools
dir
clients
dir
appletFirma
dir
transport.xsd
file
2022-07-28T03:40:48.334827Z
4f536f6eb1bf511b9104963f7b7a495c
2014-07-18T11:55:42.487555Z
1
jvaca
4147
base
dir
centralwebservices
dir
pom.xml
file
2022-07-28T03:40:48.334827Z
1d49d454883b8d88c61293062edf98e0
2014-12-31T05:29:42.479725Z
3704
cpiedra
26244
reports-jsf
dir

View File

@ -0,0 +1,687 @@
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.fp</groupId>
<artifactId>FlipBean</artifactId>
<name>Maia</name>
<version>2.1</version>
<packaging>pom</packaging>
<properties>
<project.build.sourceEncoding>ISO-8859-1</project.build.sourceEncoding>
<cfg.path>/app/maia</cfg.path>
</properties>
<modules>
<module>base</module>
<module>clients</module>
<module>frontend</module>
</modules>
<issueManagement>
<system>Mantis</system>
<url>http://190.57.146.125/mantis</url>
</issueManagement>
<developers>
<developer>
<id>flipbean</id>
<name>Flipbean</name>
<email>flipbean.s.a@gmail.com</email>
<roles>
<role>Project Manager</role>
<role>Architect</role>
</roles>
</developer>
</developers>
<scm>
<connection>scm:svn:svn+ssh://maia/repo/fuentes/sources</connection>
<url>http://192.168.2.201/svn/fuentes/sources</url>
</scm>
<organization>
<name>MAIA</name>
<url>http://190.57.146.125/tech</url>
</organization>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<fork>true</fork>
<encoding>${project.build.sourceEncoding}</encoding>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<!--plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.1.2</version>
<configuration>
<finalName>${project.artifactId}-src</finalName>
<attach>true</attach>
</configuration>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-ejb-plugin</artifactId>
<version>2.3</version>
<configuration>
<ejbVersion>3.0</ejbVersion>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId>
<version>3.0</version>
</plugin>
</plugins>
<extensions>
<extension>
<groupId>org.apache.maven.wagon</groupId>
<artifactId>wagon-ssh-external</artifactId>
<version>2.2</version>
</extension>
</extensions>
</build>
<reporting>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>2.4</version>
<reportSets>
<reportSet>
<reports>
<report>cim</report>
<report>dependencies</report>
<report>dependency-convergence</report>
<report>dependency-management</report>
<report>index</report>
<report>issue-tracking</report>
<report>license</report>
<report>mailing-list</report>
<report>plugin-management</report>
<report>project-team</report>
<report>scm</report>
<report>summary</report>
</reports>
</reportSet>
<reportSet></reportSet>
</reportSets>
</plugin>
<plugin>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.8</version>
<configuration>
<source>1.5</source>
<locale>es_EC</locale>
<stylesheetfile>${cfg.path}/stylesheet.css</stylesheetfile>
<doclet> gr.spinellis.umlgraph.doclet.UmlGraphDoc
</doclet>
<docletArtifact>
<groupId>gr.spinellis</groupId>
<artifactId>UmlGraph</artifactId>
<version>4.4</version>
</docletArtifact>
<additionalparam> -inferrel -inferdep -quiet -hide java.*
-collpackages java.util.* -qualify -postfixpackage
-nodefontsize 9 -nodefontpackagesize 7 -attributes
-operations -enumerations -enumconstants -visibility
</additionalparam>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-pmd-plugin</artifactId>
<version>2.5</version>
<configuration>
<linkXref>true</linkXref>
<sourceEncoding>ISO-8859-1</sourceEncoding>
<minimumTokens>30</minimumTokens>
<targetJdk>1.5</targetJdk>
<rulesets>
<ruleset>${cfg.path}/Rules.xml</ruleset>
</rulesets>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>2.8</version>
<configuration>
<configLocation>${cfg.path}/checkstyle.xml</configLocation>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>findbugs-maven-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<threshold>low</threshold>
<effort>Max</effort>
<excludeFilterFile>${cfg.path}/findbugs.xml</excludeFilterFile>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-report-plugin</artifactId>
<version>2.10</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jxr-plugin</artifactId>
<version>2.3</version>
</plugin>
</plugins>
</reporting>
<distributionManagement>
<repository>
<id>maia</id>
<url>scpexe://gfiallos@localhost/app/maia/bin</url>
</repository>
<site>
<id>maia</id>
<url>scpexe://root@localhost/srv/www/htdocs/tech</url>
</site>
</distributionManagement>
<profiles>
<profile>
<id>release</id>
<build>
<resources>
<resource>
<targetPath>/app/maia/bin</targetPath>
<directory>bpmlib</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.1.2</version>
<configuration>
<outputDirectory>/app/maia/bin</outputDirectory>
<finalName>${project.artifactId}-src</finalName>
<attach>true</attach>
</configuration>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<maven.test.failure.ignore>true</maven.test.failure.ignore>
</properties>
</profile>
<profile>
<id>jboss</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<maven.test.skip>true</maven.test.skip>
</properties>
</profile>
<profile>
<id>up</id>
<activation>
<activeByDefault>false</activeByDefault>
</activation>
<properties>
<maven.test.skip>true</maven.test.skip>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<outputDirectory>/app/maia/bin</outputDirectory>
<!-- finalName>${project.artifactId}</finalName-->
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<!--<repositories>
<repository>
<releases>
<updatePolicy>always</updatePolicy>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>repo</id>
<name>central</name>
<url>http://190.57.146.125/nexus/content/groups/public/</url>
</repository>
</repositories>-->
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency><!-- add support for ssh/scp -->
<groupId>org.apache.maven.wagon</groupId>
<artifactId>wagon-ssh</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant-launcher</artifactId>
<version>1.7.0</version>
</dependency>
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.7.0</version>
</dependency>
<!--DEPENDENCIA DE HIBERNATE -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.0.1.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-search</artifactId>
<version>4.0.0.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.0.1.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.2.0.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.jboss.spec.javax.ejb</groupId>
<artifactId>jboss-ejb-api_3.1_spec</artifactId>
<version>1.0.1.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.2.3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>xom</groupId>
<artifactId>xom</artifactId>
<version>1.2.5</version>
<scope>provided</scope>
</dependency>
<!--dependencias de XOM -->
<dependency>
<groupId>xalan</groupId>
<artifactId>xalan</artifactId>
<version>2.7.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
<version>2.9.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>xerces</groupId>
<artifactId>xmlParserAPIs</artifactId>
<version>2.6.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>xml-apis</groupId>
<artifactId>xml-apis</artifactId>
<version>1.3.04</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>jdom</groupId>
<artifactId>jdom</artifactId>
<version>1.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>msv</groupId>
<artifactId>xsdlib</artifactId>
<version>20050913</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>msv</groupId>
<artifactId>relaxngDatatype</artifactId>
<version>20050913</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>xpp3</groupId>
<artifactId>xpp3</artifactId>
<version>1.1.3.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>stax</groupId>
<artifactId>stax-api</artifactId>
<version>1.0.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>pull-parser</groupId>
<artifactId>pull-parser</artifactId>
<version>2.1.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.sourceforge.jtds</groupId>
<artifactId>jtds</artifactId>
<version>1.2.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jaspersoft.ireports</groupId>
<artifactId>jaspersoft-ireport</artifactId>
<version>4.7.0</version>
</dependency>
<dependency>
<groupId>com.jaspersoft.ireports</groupId>
<artifactId>ireport-jasperserver</artifactId>
<version>4.7.0</version>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>4.7.0</version>
</dependency>
<dependency>
<groupId>org.codeartisans.thirdparties.swing</groupId>
<artifactId>org-openide-util</artifactId>
<version>8.6.2</version>
</dependency>
<dependency>
<groupId>com.jaspersoft.jasperserver</groupId>
<artifactId>jasperserver-common-ws</artifactId>
<version>4.7.0</version>
</dependency>
<dependency>
<groupId>javax.xml</groupId>
<artifactId>jaxrpc-api</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>commons-digester</groupId>
<artifactId>commons-digester</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
<version>2.1.7</version>
</dependency>
<dependency>
<groupId>oracle</groupId>
<artifactId>JDBC</artifactId>
<version>6.0</version>
</dependency>
<dependency>
<groupId>jaxme</groupId>
<artifactId>jaxme-api</artifactId>
<version>0.3.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1.1</version>
<scope>test</scope>
</dependency>
<!--hast aqui dependencias de XOM -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>jline</groupId>
<artifactId>jline</artifactId>
<version>0.9.94</version>
</dependency>
<dependency>
<groupId>org.codehaus.btm</groupId>
<artifactId>btm</artifactId>
<version>2.1.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mvel</groupId>
<artifactId>mvel2</artifactId>
<version>2.1.Beta3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
<type>jar</type>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
<type>jar</type>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>net.sf.ezmorph</groupId>
<artifactId>ezmorph</artifactId>
<version>1.0.6</version>
<type>jar</type>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-tools</artifactId>
<version>2.0</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.6.4</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- poi-->
<dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>
<version>2.3.0</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.antlr</groupId>
<artifactId>antlr</artifactId>
<version>3.3</version>
<type>jar</type>
<scope>provide</scope>
</dependency>
<dependency>
<groupId>org.antlr</groupId>
<artifactId>antlr-runtime</artifactId>
<version>3.3</version>
<type>jar</type>
<scope>provide</scope>
</dependency>
<dependency>
<groupId>org.antlr</groupId>
<artifactId>stringtemplate</artifactId>
<version>3.2.1</version>
<type>jar</type>
<scope>provide</scope>
</dependency>
<dependency>
<groupId>jboss</groupId>
<artifactId>jboss-ejb-api</artifactId>
<version>4.2.1.GA</version>
<!-- scope>test</scope-->
</dependency>
<dependency>
<groupId>com.fp.base</groupId>
<artifactId>facadeclient</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>com.fp.base</groupId>
<artifactId>facade</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>axis</groupId>
<artifactId>axis</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>axis</groupId>
<artifactId>axis-wsdl4j</artifactId>
<version>1.5.1</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-discovery</groupId>
<artifactId>commons-discovery</artifactId>
<version>0.4</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>wsdl4j</groupId>
<artifactId>wsdl4j</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.4</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>jep</groupId>
<artifactId>jep</artifactId>
<version>2.4.1</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.jboss.spec</groupId>
<artifactId>jboss-javaee-6.0</artifactId>
<version>3.0.0.Final</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<!--/dependencies -->
</project>

View File

@ -0,0 +1,138 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
<xs:element name="header">
<xs:annotation>
<xs:documentation>Cabecera de mensajes</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:sequence>
<xs:element name="user"/>
<xs:element name="company"/>
<xs:element name="module"/>
<xs:element name="transaction"/>
<xs:element name="version"/>
<xs:element name="branch"/>
<xs:element name="office"/>
<xs:element name="channel"/>
<xs:element name="languge"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="SaveRequest">
<xs:annotation>
<xs:documentation>Mensaje de Negocio, Altas y Bajas</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:sequence>
<xs:element ref="header"/>
<xs:element ref="objectID" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="SaveBean">
<xs:annotation>
<xs:documentation>Mensaje de negocio</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:sequence>
<xs:element ref="CAM" minOccurs="0"/>
<xs:element name="modifyRecords" minOccurs="0" maxOccurs="unbounded">
<xs:annotation>
<xs:documentation>Multiregistro A, B</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:sequence>
<xs:element name="BusinessObject">
<xs:complexType>
<xs:sequence>
<xs:element ref="Object" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="modifyObject" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element name="BusinessObject">
<xs:complexType>
<xs:sequence>
<xs:element ref="Object"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="deleteObject" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element name="BuseinessObject">
<xs:complexType>
<xs:sequence>
<xs:element ref="Object"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="deleteRecords" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element name="BusinessObject">
<xs:complexType>
<xs:sequence>
<xs:element ref="Object" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="position"/>
<xs:attribute name="beanAlias"/>
<xs:attribute name="beanName"/>
</xs:complexType>
</xs:element>
<xs:element name="objectID">
<xs:annotation>
<xs:documentation>Objeto de negocio</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:sequence>
<xs:element ref="SaveBean"/>
</xs:sequence>
<xs:attribute name="name" use="required"/>
</xs:complexType>
</xs:element>
<xs:element name="Object">
<xs:annotation>
<xs:documentation>Registros de una tabla</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:sequence>
<xs:element ref="CAM" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="CAM">
<xs:annotation>
<xs:documentation>Campo de un registro</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:attribute name="name" use="required">
<xs:annotation>
<xs:documentation>Nombre de un campo suelto</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="Valor" use="required">
<xs:annotation>
<xs:documentation>Valor del campo</xs:documentation>
</xs:annotation>
</xs:attribute>
</xs:complexType>
</xs:element>
</xs:schema>

68
appletFirma/.svn/entries Normal file
View File

@ -0,0 +1,68 @@
10
dir
4669
svn://172.17.26.185/COMACO/sources/appletFirma
svn://172.17.26.185/COMACO
2015-04-28T07:21:43.253845Z
4061
cpiedra
a11ad980-3ca8-45f0-88f7-f0e618c262b7
lib
dir
src
dir
pom.xml
file
2022-07-28T03:40:24.126723Z
bd2a0d053d394874dc41aafd42d7188b
2014-12-31T05:22:02.287651Z
3703
dcruz
has-props
1497

View File

@ -0,0 +1,5 @@
K 13
svn:mime-type
V 10
text/plain
END

View File

@ -0,0 +1,51 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.fp.firma</groupId>
<artifactId>appletFirma</artifactId>
<version>2.1</version>
<packaging>jar</packaging>
<name>appletFirma</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcmail-jdk15on</artifactId>
<version>1.51</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.49</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-ext-jdk15on</artifactId>
<version>1.49</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk15on</artifactId>
<version>1.49</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.3</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,62 @@
10
dir
4669
svn://172.17.26.185/COMACO/sources/appletFirma/lib
svn://172.17.26.185/COMACO
2014-12-31T05:22:02.287651Z
3703
dcruz
a11ad980-3ca8-45f0-88f7-f0e618c262b7
itextpdf-5.5.3.jar
file
2022-07-28T03:40:23.429719Z
1f8b7633f9f21668d178566e9e85fe7c
2014-12-31T05:22:02.287651Z
3703
dcruz
has-props
2237618

View File

@ -0,0 +1,9 @@
K 14
svn:executable
V 1
*
K 13
svn:mime-type
V 24
application/octet-stream
END

Binary file not shown.

View File

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<project-shared-configuration>
<!--
This file contains additional configuration written by modules in the NetBeans IDE.
The configuration is intended to be shared among all the users of project and
therefore it is assumed to be part of version control checkout.
Without this configuration present, some functionality in the IDE may be limited or fail altogether.
-->
<properties xmlns="http://www.netbeans.org/ns/maven-properties-data/1">
<!--
Properties that influence various parts of the IDE, especially code formatting and the like.
You can copy and paste the single properties, into the pom.xml file and the IDE will pick them up.
That way multiple projects can share the same settings (useful for formatting rules for example).
Any value defined here will override the pom.xml file value but is only applicable to the current project.
-->
<netbeans.hint.jdkPlatform>ORACLE_JDK_1.8</netbeans.hint.jdkPlatform>
</properties>
</project-shared-configuration>

56
appletFirma/pom.xml Normal file
View File

@ -0,0 +1,56 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.fp.firma</groupId>
<artifactId>appletFirma</artifactId>
<version>2.1</version>
<packaging>jar</packaging>
<name>appletFirma</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcmail-jdk15on</artifactId>
<version>1.51</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.49</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-ext-jdk15on</artifactId>
<version>1.49</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk15on</artifactId>
<version>1.49</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.3</version>
</dependency>
<dependency>
<groupId>io.rubrica</groupId>
<artifactId>rubrica</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,34 @@
10
dir
4669
svn://172.17.26.185/COMACO/sources/appletFirma/src
svn://172.17.26.185/COMACO
2015-04-28T07:21:43.253845Z
4061
cpiedra
a11ad980-3ca8-45f0-88f7-f0e618c262b7
test
dir
main
dir

View File

@ -0,0 +1,34 @@
10
dir
4669
svn://172.17.26.185/COMACO/sources/appletFirma/src/main
svn://172.17.26.185/COMACO
2015-04-28T07:21:43.253845Z
4061
cpiedra
a11ad980-3ca8-45f0-88f7-f0e618c262b7
java
dir
resources
dir

View File

@ -0,0 +1,31 @@
10
dir
4669
svn://172.17.26.185/COMACO/sources/appletFirma/src/main/java
svn://172.17.26.185/COMACO
2015-04-28T07:21:43.253845Z
4061
cpiedra
a11ad980-3ca8-45f0-88f7-f0e618c262b7
com
dir

View File

@ -0,0 +1,31 @@
10
dir
4669
svn://172.17.26.185/COMACO/sources/appletFirma/src/main/java/com
svn://172.17.26.185/COMACO
2015-04-28T07:21:43.253845Z
4061
cpiedra
a11ad980-3ca8-45f0-88f7-f0e618c262b7
fp
dir

View File

@ -0,0 +1,31 @@
10
dir
4669
svn://172.17.26.185/COMACO/sources/appletFirma/src/main/java/com/fp
svn://172.17.26.185/COMACO
2015-04-28T07:21:43.253845Z
4061
cpiedra
a11ad980-3ca8-45f0-88f7-f0e618c262b7
firma
dir

View File

@ -0,0 +1,43 @@
10
dir
4669
svn://172.17.26.185/COMACO/sources/appletFirma/src/main/java/com/fp/firma
svn://172.17.26.185/COMACO
2015-04-28T07:21:43.253845Z
4061
cpiedra
a11ad980-3ca8-45f0-88f7-f0e618c262b7
component
dir
applet
dir
keystore
dir
dto
dir
common
dir

View File

@ -0,0 +1,96 @@
10
dir
4669
svn://172.17.26.185/COMACO/sources/appletFirma/src/main/java/com/fp/firma/applet
svn://172.17.26.185/COMACO
2015-04-28T07:21:43.253845Z
4061
cpiedra
a11ad980-3ca8-45f0-88f7-f0e618c262b7
FirmaApplet.java
file
2022-07-28T03:40:23.755721Z
c6fc0b382335939010b5277beb9a38dd
2015-04-28T07:21:43.253845Z
4061
cpiedra
has-props
16793
FirmaApplet.form
file
2022-07-28T03:40:23.755721Z
575cbea3cc9720565e5a28838bc7a45e
2014-12-31T05:22:02.287651Z
3703
dcruz
has-props
7804

View File

@ -0,0 +1,5 @@
K 14
svn:executable
V 1
*
END

View File

@ -0,0 +1,9 @@
K 14
svn:executable
V 1
*
K 13
svn:mime-type
V 10
text/plain
END

View File

@ -0,0 +1,152 @@
<?xml version="1.0" encoding="UTF-8" ?>
<Form version="1.5" maxVersion="1.8" type="org.netbeans.modules.form.forminfo.JAppletFormInfo">
<NonVisualComponents>
<Component class="javax.swing.ButtonGroup" name="grupoRadios">
<AuxValues>
<AuxValue name="JavaCodeGenerator_allCodePost" type="java.lang.String" value="grupoRadios.add(tokenIkey);&#xa;grupoRadios.add(tokenAlladin);&#xa;grupoRadios.add(tokenSD);"/>
</AuxValues>
</Component>
</NonVisualComponents>
<AuxValues>
<AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
<AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
<AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
<AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
<AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
</AuxValues>
<Layout>
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="0" attributes="0">
<EmptySpace max="-2" attributes="0"/>
<Component id="jPanel1" max="32767" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
</Group>
<Group type="102" alignment="0" attributes="0">
<EmptySpace min="-2" pref="41" max="-2" attributes="0"/>
<Component id="tokenIkey" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="tokenAlladin" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="tokenSD" min="-2" max="-2" attributes="0"/>
<EmptySpace max="32767" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
<DimensionLayout dim="1">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="1" attributes="0">
<EmptySpace pref="75" max="32767" attributes="0"/>
<Group type="103" groupAlignment="3" attributes="0">
<Component id="tokenAlladin" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="tokenSD" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="tokenIkey" alignment="3" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace type="separate" max="-2" attributes="0"/>
<Component id="jPanel1" min="-2" max="-2" attributes="0"/>
<EmptySpace min="-2" pref="25" max="-2" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
</Layout>
<SubComponents>
<Container class="javax.swing.JPanel" name="jPanel1">
<Layout>
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" attributes="0">
<Component id="labelArchivoFirma" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" attributes="0">
<EmptySpace min="12" pref="12" max="-2" attributes="0"/>
<Component id="btnFirmarArchivo" min="-2" max="-2" attributes="0"/>
</Group>
<Group type="102" attributes="0">
<Component id="txtRutaArchivo" min="-2" pref="139" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="btnExaminar" min="-2" max="-2" attributes="0"/>
</Group>
</Group>
<EmptySpace max="32767" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
<DimensionLayout dim="1">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="1" attributes="0">
<EmptySpace max="32767" attributes="0"/>
<Group type="103" groupAlignment="3" attributes="0">
<Component id="labelArchivoFirma" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="txtRutaArchivo" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="btnExaminar" alignment="3" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace type="unrelated" max="-2" attributes="0"/>
<Component id="btnFirmarArchivo" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
</Layout>
<SubComponents>
<Component class="javax.swing.JLabel" name="labelArchivoFirma">
<Properties>
<Property name="text" type="java.lang.String" value="Archivo a firmar"/>
</Properties>
</Component>
<Component class="javax.swing.JTextField" name="txtRutaArchivo">
<Properties>
<Property name="editable" type="boolean" value="false"/>
</Properties>
</Component>
<Component class="javax.swing.JButton" name="btnExaminar">
<Properties>
<Property name="text" type="java.lang.String" value="Examinar"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="btnExaminarActionPerformed"/>
</Events>
</Component>
<Component class="javax.swing.JButton" name="btnFirmarArchivo">
<Properties>
<Property name="text" type="java.lang.String" value="Firmar"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="btnFirmarArchivoActionPerformed"/>
</Events>
</Component>
</SubComponents>
</Container>
<Component class="javax.swing.JRadioButton" name="tokenIkey">
<Properties>
<Property name="text" type="java.lang.String" value="iKey 2032"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="tokenIkeyActionPerformed"/>
</Events>
</Component>
<Component class="javax.swing.JRadioButton" name="tokenAlladin">
<Properties>
<Property name="text" type="java.lang.String" value="eTokenPro"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="tokenAlladinActionPerformed"/>
</Events>
</Component>
<Component class="javax.swing.JRadioButton" name="tokenSD">
<Properties>
<Property name="text" type="java.lang.String" value="Security Data"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="tokenSDActionPerformed"/>
</Events>
</Component>
</SubComponents>
</Form>

View File

@ -0,0 +1,152 @@
<?xml version="1.0" encoding="UTF-8" ?>
<Form version="1.5" maxVersion="1.8" type="org.netbeans.modules.form.forminfo.JAppletFormInfo">
<NonVisualComponents>
<Component class="javax.swing.ButtonGroup" name="grupoRadios">
<AuxValues>
<AuxValue name="JavaCodeGenerator_allCodePost" type="java.lang.String" value="grupoRadios.add(tokenIkey);&#xa;grupoRadios.add(tokenAlladin);&#xa;grupoRadios.add(tokenSD);"/>
</AuxValues>
</Component>
</NonVisualComponents>
<AuxValues>
<AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
<AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
<AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
<AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
<AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
</AuxValues>
<Layout>
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="0" attributes="0">
<EmptySpace max="-2" attributes="0"/>
<Component id="jPanel1" max="32767" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
</Group>
<Group type="102" alignment="0" attributes="0">
<EmptySpace min="-2" pref="41" max="-2" attributes="0"/>
<Component id="tokenIkey" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="tokenAlladin" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="tokenSD" min="-2" max="-2" attributes="0"/>
<EmptySpace max="32767" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
<DimensionLayout dim="1">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="1" attributes="0">
<EmptySpace pref="75" max="32767" attributes="0"/>
<Group type="103" groupAlignment="3" attributes="0">
<Component id="tokenAlladin" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="tokenSD" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="tokenIkey" alignment="3" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace type="separate" max="-2" attributes="0"/>
<Component id="jPanel1" min="-2" max="-2" attributes="0"/>
<EmptySpace min="-2" pref="25" max="-2" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
</Layout>
<SubComponents>
<Container class="javax.swing.JPanel" name="jPanel1">
<Layout>
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" attributes="0">
<Component id="labelArchivoFirma" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" attributes="0">
<EmptySpace min="12" pref="12" max="-2" attributes="0"/>
<Component id="btnFirmarArchivo" min="-2" max="-2" attributes="0"/>
</Group>
<Group type="102" attributes="0">
<Component id="txtRutaArchivo" min="-2" pref="139" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="btnExaminar" min="-2" max="-2" attributes="0"/>
</Group>
</Group>
<EmptySpace max="32767" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
<DimensionLayout dim="1">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="1" attributes="0">
<EmptySpace max="32767" attributes="0"/>
<Group type="103" groupAlignment="3" attributes="0">
<Component id="labelArchivoFirma" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="txtRutaArchivo" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="btnExaminar" alignment="3" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace type="unrelated" max="-2" attributes="0"/>
<Component id="btnFirmarArchivo" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
</Layout>
<SubComponents>
<Component class="javax.swing.JLabel" name="labelArchivoFirma">
<Properties>
<Property name="text" type="java.lang.String" value="Archivo a firmar"/>
</Properties>
</Component>
<Component class="javax.swing.JTextField" name="txtRutaArchivo">
<Properties>
<Property name="editable" type="boolean" value="false"/>
</Properties>
</Component>
<Component class="javax.swing.JButton" name="btnExaminar">
<Properties>
<Property name="text" type="java.lang.String" value="Examinar"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="btnExaminarActionPerformed"/>
</Events>
</Component>
<Component class="javax.swing.JButton" name="btnFirmarArchivo">
<Properties>
<Property name="text" type="java.lang.String" value="Firmar"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="btnFirmarArchivoActionPerformed"/>
</Events>
</Component>
</SubComponents>
</Container>
<Component class="javax.swing.JRadioButton" name="tokenIkey">
<Properties>
<Property name="text" type="java.lang.String" value="iKey 2032"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="tokenIkeyActionPerformed"/>
</Events>
</Component>
<Component class="javax.swing.JRadioButton" name="tokenAlladin">
<Properties>
<Property name="text" type="java.lang.String" value="eTokenPro"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="tokenAlladinActionPerformed"/>
</Events>
</Component>
<Component class="javax.swing.JRadioButton" name="tokenSD">
<Properties>
<Property name="text" type="java.lang.String" value="Security Data"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="tokenSDActionPerformed"/>
</Events>
</Component>
</SubComponents>
</Form>

View File

@ -0,0 +1,345 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.fp.firma.applet;
import com.fp.firma.common.CertificateUtils;
import com.fp.firma.common.FirmMessages;
import com.itextpdf.text.Rectangle;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
/**
* Applet de firma electr&oacute;nica a trav&eacute;s de token
* @author dcruz
*/
public class FirmaApplet extends javax.swing.JApplet {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final String PREFIX = "firmado_";
private String rutaArchivoFirmar = "";
private static final Logger logger = Logger.getLogger(FirmaApplet.class .getName());
private String tipoFirma;
/**
* Initializes the applet FirmaApplet
*/
@Override
public void init() {
// FileHandler handler;
// try {
// handler = new FileHandler(System.getProperty("java.io.tmpdir")+"\\applet.txt");
// handler.setFormatter(new SimpleFormatter());
// logger.addHandler(handler);
// } catch (IOException ex) {
// Logger.getLogger(FirmaApplet.class.getName()).log(Level.SEVERE, null, ex);
// } catch (SecurityException ex) {
// Logger.getLogger(FirmaApplet.class.getName()).log(Level.SEVERE, null, ex);
// }
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(FirmaApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(FirmaApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(FirmaApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(FirmaApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the applet */
try {
java.awt.EventQueue.invokeAndWait(new Runnable() {
public void run() {
initComponents();
}
});
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* This method is called from within the init() method to initialize the form. WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
grupoRadios = new javax.swing.ButtonGroup();
jPanel1 = new javax.swing.JPanel();
labelArchivoFirma = new javax.swing.JLabel();
txtRutaArchivo = new javax.swing.JTextField();
btnExaminar = new javax.swing.JButton();
btnFirmarArchivo = new javax.swing.JButton();
tokenIkey = new javax.swing.JRadioButton();
tokenAlladin = new javax.swing.JRadioButton();
tokenSD = new javax.swing.JRadioButton();
grupoRadios.add(tokenIkey);
grupoRadios.add(tokenAlladin);
grupoRadios.add(tokenSD);
labelArchivoFirma.setText("Archivo a firmar");
txtRutaArchivo.setEditable(false);
btnFirmarArchivo.setEnabled(true);
btnExaminar.setEnabled(true);
btnExaminar.setText("Examinar");
btnExaminar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnExaminarActionPerformed(evt);
}
});
btnFirmarArchivo.setText("Firmar");
btnFirmarArchivo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnFirmarArchivoActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(labelArchivoFirma)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(12, 12, 12)
.addComponent(btnFirmarArchivo))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(txtRutaArchivo, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnExaminar)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelArchivoFirma)
.addComponent(txtRutaArchivo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnExaminar))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnFirmarArchivo)
.addContainerGap())
);
tokenIkey.setText("iKey 2032");
tokenIkey.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tokenIkeyActionPerformed(evt);
}
});
tokenAlladin.setText("eTokenPro");
tokenAlladin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tokenAlladinActionPerformed(evt);
}
});
tokenSD.setText("Security Data");
tokenSD.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tokenSDActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGap(41, 41, 41)
.addComponent(tokenIkey)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tokenAlladin)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tokenSD)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(75, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(tokenAlladin)
.addComponent(tokenSD)
.addComponent(tokenIkey))
.addGap(18, 18, 18)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(25, 25, 25))
);
}// </editor-fold>//GEN-END:initComponents
private void btnExaminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExaminarActionPerformed
// TODO add your handling code here:
try
{
/**llamamos el metodo que permite cargar la ventana*/
JFileChooser fileChooser=new JFileChooser();
String rutaArchivo = txtRutaArchivo.getText();
File directorio = new File(rutaArchivo).getParentFile();
fileChooser.setCurrentDirectory(directorio);
// System.out.println("Directorio del archivo "+fileChooser.getCurrentDirectory() != null ? fileChooser.getCurrentDirectory().getAbsolutePath() : "");
/**abrimos el archivo seleccionado*/
int respuestaDialog = fileChooser.showOpenDialog(this);
if(respuestaDialog == JFileChooser.APPROVE_OPTION){
File fileSelected = fileChooser.getSelectedFile();
rutaArchivoFirmar = fileSelected.getAbsolutePath();
System.out.println("Ruta del archivo escogido "+rutaArchivoFirmar);
txtRutaArchivo.setText(rutaArchivoFirmar);
} else{
JOptionPane.showMessageDialog(null,"" +
"\nAccion cancelada por el usuario",
"ADVERTENCIA!!!",JOptionPane.WARNING_MESSAGE);
}
/**recorremos el archivo, lo leemos para plasmarlo
*en el area de texto*/
}catch(Throwable ex)
{
JOptionPane.showMessageDialog(null,ex+"" +
"\nNo se ha encontrado el archivo",
"ADVERTENCIA!!!",JOptionPane.WARNING_MESSAGE);
}
}//GEN-LAST:event_btnExaminarActionPerformed
private void btnFirmarArchivoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFirmarArchivoActionPerformed
// TODO add your handling code here:
InputStream inputStream = null;
try{
String razon = getParameter("razon") != null ? getParameter("razon") : "";
String lugar = getParameter("lugar") != null ? getParameter("lugar") : "";
String nombreFirma = getParameter("firma") != null ? getParameter("firma") : "";
Float llx = Float.valueOf(getParameter("llx") != null ? Float.parseFloat(getParameter("llx")) : 0.0F);
Float lly = Float.valueOf(getParameter("lly") != null ? Float.parseFloat(getParameter("lly")) : 0.0F);
Float urx = Float.valueOf(getParameter("urx") != null ? Float.parseFloat(getParameter("urx")) : 0.0F);
Float ury = Float.valueOf(getParameter("ury") != null ? Float.parseFloat(getParameter("ury")) : 0.0F);
if(tipoFirma == null){
JOptionPane.showMessageDialog(null, "Debe seleccionar un Token con el cual firmar", "Tipo Firma", JOptionPane.ERROR_MESSAGE);
return;
}
if(txtRutaArchivo.getText() != null){
JPasswordField txtPasswordToken = new JPasswordField();
final JComponent[] components = new JComponent[]{new JLabel("Password:"), txtPasswordToken};
JOptionPane.showMessageDialog(null, components, "TOKEN", JOptionPane.PLAIN_MESSAGE);
if(txtPasswordToken.getPassword() == null){
throw new NullPointerException(FirmMessages.getString("FIR-0007"));
}
inputStream = new FileInputStream(txtRutaArchivo.getText());
byte[] datos = CertificateUtils.sign(inputStream, null, new String(txtPasswordToken.getPassword()), razon, lugar, Boolean.FALSE.booleanValue(), Boolean.FALSE.booleanValue(), new Rectangle(llx.floatValue(), lly.floatValue(), urx.floatValue(), ury.floatValue()), 1, nombreFirma, this.tipoFirma);
if(datos != null){
escribirArchivo(datos);
txtPasswordToken.setText("");
JOptionPane.showMessageDialog(null, "El archivo se modificado correctamente", "Archivo firmado", JOptionPane.INFORMATION_MESSAGE);
}
}else{
JOptionPane.showMessageDialog(null, "Debe seleccionar un archivo", "Archivo no encontrado", JOptionPane.ERROR_MESSAGE);
}
btnFirmarArchivo.setEnabled(false);
btnExaminar.setEnabled(false);
} catch(IOException e){
JOptionPane.showMessageDialog(null, e.getMessage(), "IO Error", JOptionPane.ERROR_MESSAGE);
} catch(Exception e){
JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
} finally{
try {
if(inputStream != null){
inputStream.close();
}
} catch (IOException ex) {
Logger.getLogger(FirmaApplet.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_btnFirmarArchivoActionPerformed
public void escribirArchivo(byte[] data){
System.out.println("Ingreso a escribir el archivo");
FileOutputStream fo = null;
try {
File archivoFirmado = new File(txtRutaArchivo.getText());
fo = new FileOutputStream(archivoFirmado);
fo.write(data);
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Error archivo no encontrado", JOptionPane.ERROR_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Error al escribir el archivo firmado", JOptionPane.ERROR_MESSAGE);
} finally {
try {
fo.close();
} catch (IOException ex) {
Logger.getLogger(FirmaApplet.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private void tokenIkeyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tokenIkeyActionPerformed
// TODO add your handling code here:
tipoFirma = "1";
}//GEN-LAST:event_tokenIkeyActionPerformed
private void tokenAlladinActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tokenAlladinActionPerformed
// TODO add your handling code here:
tipoFirma = "2";
}//GEN-LAST:event_tokenAlladinActionPerformed
private void tokenSDActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tokenSDActionPerformed
// TODO add your handling code here:
tipoFirma = "3";
}//GEN-LAST:event_tokenSDActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnExaminar;
private javax.swing.JButton btnFirmarArchivo;
private javax.swing.ButtonGroup grupoRadios;
private javax.swing.JPanel jPanel1;
private javax.swing.JLabel labelArchivoFirma;
private javax.swing.JRadioButton tokenAlladin;
private javax.swing.JRadioButton tokenIkey;
private javax.swing.JRadioButton tokenSD;
private javax.swing.JTextField txtRutaArchivo;
// End of variables declaration//GEN-END:variables
}

View File

@ -0,0 +1,345 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.fp.firma.applet;
import com.fp.firma.common.CertificateUtils;
import com.fp.firma.common.FirmMessages;
import com.itextpdf.text.Rectangle;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
/**
* Applet de firma electr&oacute;nica a trav&eacute;s de token
* @author dcruz
*/
public class FirmaApplet extends javax.swing.JApplet {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final String PREFIX = "firmado_";
private String rutaArchivoFirmar = "";
private static final Logger logger = Logger.getLogger(FirmaApplet.class .getName());
private String tipoFirma;
/**
* Initializes the applet FirmaApplet
*/
@Override
public void init() {
// FileHandler handler;
// try {
// handler = new FileHandler(System.getProperty("java.io.tmpdir")+"\\applet.txt");
// handler.setFormatter(new SimpleFormatter());
// logger.addHandler(handler);
// } catch (IOException ex) {
// Logger.getLogger(FirmaApplet.class.getName()).log(Level.SEVERE, null, ex);
// } catch (SecurityException ex) {
// Logger.getLogger(FirmaApplet.class.getName()).log(Level.SEVERE, null, ex);
// }
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(FirmaApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(FirmaApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(FirmaApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(FirmaApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the applet */
try {
java.awt.EventQueue.invokeAndWait(new Runnable() {
public void run() {
initComponents();
}
});
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* This method is called from within the init() method to initialize the form. WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
grupoRadios = new javax.swing.ButtonGroup();
jPanel1 = new javax.swing.JPanel();
labelArchivoFirma = new javax.swing.JLabel();
txtRutaArchivo = new javax.swing.JTextField();
btnExaminar = new javax.swing.JButton();
btnFirmarArchivo = new javax.swing.JButton();
tokenIkey = new javax.swing.JRadioButton();
tokenAlladin = new javax.swing.JRadioButton();
tokenSD = new javax.swing.JRadioButton();
grupoRadios.add(tokenIkey);
grupoRadios.add(tokenAlladin);
grupoRadios.add(tokenSD);
labelArchivoFirma.setText("Archivo a firmar");
txtRutaArchivo.setEditable(false);
btnFirmarArchivo.setEnabled(true);
btnExaminar.setEnabled(true);
btnExaminar.setText("Examinar");
btnExaminar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnExaminarActionPerformed(evt);
}
});
btnFirmarArchivo.setText("Firmar");
btnFirmarArchivo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnFirmarArchivoActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(labelArchivoFirma)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(12, 12, 12)
.addComponent(btnFirmarArchivo))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(txtRutaArchivo, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnExaminar)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelArchivoFirma)
.addComponent(txtRutaArchivo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnExaminar))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnFirmarArchivo)
.addContainerGap())
);
tokenIkey.setText("iKey 2032");
tokenIkey.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tokenIkeyActionPerformed(evt);
}
});
tokenAlladin.setText("eTokenPro");
tokenAlladin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tokenAlladinActionPerformed(evt);
}
});
tokenSD.setText("Security Data");
tokenSD.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tokenSDActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGap(41, 41, 41)
.addComponent(tokenIkey)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tokenAlladin)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tokenSD)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(75, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(tokenAlladin)
.addComponent(tokenSD)
.addComponent(tokenIkey))
.addGap(18, 18, 18)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(25, 25, 25))
);
}// </editor-fold>//GEN-END:initComponents
private void btnExaminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExaminarActionPerformed
// TODO add your handling code here:
try
{
/**llamamos el metodo que permite cargar la ventana*/
JFileChooser fileChooser=new JFileChooser();
String rutaArchivo = txtRutaArchivo.getText();
File directorio = new File(rutaArchivo).getParentFile();
fileChooser.setCurrentDirectory(directorio);
// System.out.println("Directorio del archivo "+fileChooser.getCurrentDirectory() != null ? fileChooser.getCurrentDirectory().getAbsolutePath() : "");
/**abrimos el archivo seleccionado*/
int respuestaDialog = fileChooser.showOpenDialog(this);
if(respuestaDialog == JFileChooser.APPROVE_OPTION){
File fileSelected = fileChooser.getSelectedFile();
rutaArchivoFirmar = fileSelected.getAbsolutePath();
System.out.println("Ruta del archivo escogido "+rutaArchivoFirmar);
txtRutaArchivo.setText(rutaArchivoFirmar);
} else{
JOptionPane.showMessageDialog(null,"" +
"\nAccion cancelada por el usuario",
"ADVERTENCIA!!!",JOptionPane.WARNING_MESSAGE);
}
/**recorremos el archivo, lo leemos para plasmarlo
*en el area de texto*/
}catch(Throwable ex)
{
JOptionPane.showMessageDialog(null,ex+"" +
"\nNo se ha encontrado el archivo",
"ADVERTENCIA!!!",JOptionPane.WARNING_MESSAGE);
}
}//GEN-LAST:event_btnExaminarActionPerformed
private void btnFirmarArchivoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFirmarArchivoActionPerformed
// TODO add your handling code here:
InputStream inputStream = null;
try{
String razon = getParameter("razon") != null ? getParameter("razon") : "";
String lugar = getParameter("lugar") != null ? getParameter("lugar") : "";
String nombreFirma = getParameter("firma") != null ? getParameter("firma") : "";
Float llx = Float.valueOf(getParameter("llx") != null ? Float.parseFloat(getParameter("llx")) : 0.0F);
Float lly = Float.valueOf(getParameter("lly") != null ? Float.parseFloat(getParameter("lly")) : 0.0F);
Float urx = Float.valueOf(getParameter("urx") != null ? Float.parseFloat(getParameter("urx")) : 0.0F);
Float ury = Float.valueOf(getParameter("ury") != null ? Float.parseFloat(getParameter("ury")) : 0.0F);
if(tipoFirma == null){
JOptionPane.showMessageDialog(null, "Debe seleccionar un Token con el cual firmar", "Tipo Firma", JOptionPane.ERROR_MESSAGE);
return;
}
if(txtRutaArchivo.getText() != null){
JPasswordField txtPasswordToken = new JPasswordField();
final JComponent[] components = new JComponent[]{new JLabel("Password:"), txtPasswordToken};
JOptionPane.showMessageDialog(null, components, "TOKEN", JOptionPane.PLAIN_MESSAGE);
if(txtPasswordToken.getPassword() == null){
throw new NullPointerException(FirmMessages.getString("FIR-0007"));
}
inputStream = new FileInputStream(txtRutaArchivo.getText());
byte[] datos = CertificateUtils.sign(inputStream, null, new String(txtPasswordToken.getPassword()), razon, lugar, Boolean.FALSE.booleanValue(), Boolean.FALSE.booleanValue(), new Rectangle(llx.floatValue(), lly.floatValue(), urx.floatValue(), ury.floatValue()), 1, nombreFirma, this.tipoFirma);
if(datos != null){
escribirArchivo(datos);
txtPasswordToken.setText("");
JOptionPane.showMessageDialog(null, "El archivo se modificado correctamente", "Archivo firmado", JOptionPane.INFORMATION_MESSAGE);
}
}else{
JOptionPane.showMessageDialog(null, "Debe seleccionar un archivo", "Archivo no encontrado", JOptionPane.ERROR_MESSAGE);
}
btnFirmarArchivo.setEnabled(false);
btnExaminar.setEnabled(false);
} catch(IOException e){
JOptionPane.showMessageDialog(null, e.getMessage(), "IO Error", JOptionPane.ERROR_MESSAGE);
} catch(Exception e){
JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
} finally{
try {
if(inputStream != null){
inputStream.close();
}
} catch (IOException ex) {
Logger.getLogger(FirmaApplet.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_btnFirmarArchivoActionPerformed
public void escribirArchivo(byte[] data){
System.out.println("Ingreso a escribir el archivo");
FileOutputStream fo = null;
try {
File archivoFirmado = new File(txtRutaArchivo.getText());
fo = new FileOutputStream(archivoFirmado);
fo.write(data);
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Error archivo no encontrado", JOptionPane.ERROR_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Error al escribir el archivo firmado", JOptionPane.ERROR_MESSAGE);
} finally {
try {
fo.close();
} catch (IOException ex) {
Logger.getLogger(FirmaApplet.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private void tokenIkeyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tokenIkeyActionPerformed
// TODO add your handling code here:
tipoFirma = "1";
}//GEN-LAST:event_tokenIkeyActionPerformed
private void tokenAlladinActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tokenAlladinActionPerformed
// TODO add your handling code here:
tipoFirma = "2";
}//GEN-LAST:event_tokenAlladinActionPerformed
private void tokenSDActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tokenSDActionPerformed
// TODO add your handling code here:
tipoFirma = "3";
}//GEN-LAST:event_tokenSDActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnExaminar;
private javax.swing.JButton btnFirmarArchivo;
private javax.swing.ButtonGroup grupoRadios;
private javax.swing.JPanel jPanel1;
private javax.swing.JLabel labelArchivoFirma;
private javax.swing.JRadioButton tokenAlladin;
private javax.swing.JRadioButton tokenIkey;
private javax.swing.JRadioButton tokenSD;
private javax.swing.JTextField txtRutaArchivo;
// End of variables declaration//GEN-END:variables
}

View File

@ -0,0 +1,152 @@
<?xml version="1.0" encoding="UTF-8" ?>
<Form version="1.5" maxVersion="1.8" type="org.netbeans.modules.form.forminfo.JAppletFormInfo">
<NonVisualComponents>
<Component class="javax.swing.ButtonGroup" name="grupoRadios">
<AuxValues>
<AuxValue name="JavaCodeGenerator_allCodePost" type="java.lang.String" value="grupoRadios.add(tokenIkey);&#xa;grupoRadios.add(tokenAlladin);&#xa;grupoRadios.add(tokenSD);"/>
</AuxValues>
</Component>
</NonVisualComponents>
<AuxValues>
<AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
<AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
<AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
<AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
<AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
</AuxValues>
<Layout>
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="0" attributes="0">
<EmptySpace max="-2" attributes="0"/>
<Component id="jPanel1" max="32767" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
</Group>
<Group type="102" alignment="0" attributes="0">
<EmptySpace min="-2" pref="41" max="-2" attributes="0"/>
<Component id="tokenIkey" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="tokenAlladin" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="tokenSD" min="-2" max="-2" attributes="0"/>
<EmptySpace max="32767" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
<DimensionLayout dim="1">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="1" attributes="0">
<EmptySpace pref="75" max="32767" attributes="0"/>
<Group type="103" groupAlignment="3" attributes="0">
<Component id="tokenAlladin" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="tokenSD" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="tokenIkey" alignment="3" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace type="separate" max="-2" attributes="0"/>
<Component id="jPanel1" min="-2" max="-2" attributes="0"/>
<EmptySpace min="-2" pref="25" max="-2" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
</Layout>
<SubComponents>
<Container class="javax.swing.JPanel" name="jPanel1">
<Layout>
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" attributes="0">
<Component id="labelArchivoFirma" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" attributes="0">
<EmptySpace min="12" pref="12" max="-2" attributes="0"/>
<Component id="btnFirmarArchivo" min="-2" max="-2" attributes="0"/>
</Group>
<Group type="102" attributes="0">
<Component id="txtRutaArchivo" min="-2" pref="139" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="btnExaminar" min="-2" max="-2" attributes="0"/>
</Group>
</Group>
<EmptySpace max="32767" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
<DimensionLayout dim="1">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="1" attributes="0">
<EmptySpace max="32767" attributes="0"/>
<Group type="103" groupAlignment="3" attributes="0">
<Component id="labelArchivoFirma" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="txtRutaArchivo" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="btnExaminar" alignment="3" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace type="unrelated" max="-2" attributes="0"/>
<Component id="btnFirmarArchivo" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
</Layout>
<SubComponents>
<Component class="javax.swing.JLabel" name="labelArchivoFirma">
<Properties>
<Property name="text" type="java.lang.String" value="Archivo a firmar"/>
</Properties>
</Component>
<Component class="javax.swing.JTextField" name="txtRutaArchivo">
<Properties>
<Property name="editable" type="boolean" value="false"/>
</Properties>
</Component>
<Component class="javax.swing.JButton" name="btnExaminar">
<Properties>
<Property name="text" type="java.lang.String" value="Examinar"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="btnExaminarActionPerformed"/>
</Events>
</Component>
<Component class="javax.swing.JButton" name="btnFirmarArchivo">
<Properties>
<Property name="text" type="java.lang.String" value="Firmar"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="btnFirmarArchivoActionPerformed"/>
</Events>
</Component>
</SubComponents>
</Container>
<Component class="javax.swing.JRadioButton" name="tokenIkey">
<Properties>
<Property name="text" type="java.lang.String" value="iKey 2032"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="tokenIkeyActionPerformed"/>
</Events>
</Component>
<Component class="javax.swing.JRadioButton" name="tokenAlladin">
<Properties>
<Property name="text" type="java.lang.String" value="eTokenPro"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="tokenAlladinActionPerformed"/>
</Events>
</Component>
<Component class="javax.swing.JRadioButton" name="tokenSD">
<Properties>
<Property name="text" type="java.lang.String" value="Security Data"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="tokenSDActionPerformed"/>
</Events>
</Component>
</SubComponents>
</Form>

View File

@ -0,0 +1,345 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.fp.firma.applet;
import com.fp.firma.common.CertificateUtils;
import com.fp.firma.common.FirmMessages;
import com.itextpdf.text.Rectangle;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
/**
* Applet de firma electr&oacute;nica a trav&eacute;s de token
* @author dcruz
*/
public class FirmaApplet extends javax.swing.JApplet {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final String PREFIX = "firmado_";
private String rutaArchivoFirmar = "";
private static final Logger logger = Logger.getLogger(FirmaApplet.class .getName());
private String tipoFirma;
/**
* Initializes the applet FirmaApplet
*/
@Override
public void init() {
// FileHandler handler;
// try {
// handler = new FileHandler(System.getProperty("java.io.tmpdir")+"\\applet.txt");
// handler.setFormatter(new SimpleFormatter());
// logger.addHandler(handler);
// } catch (IOException ex) {
// Logger.getLogger(FirmaApplet.class.getName()).log(Level.SEVERE, null, ex);
// } catch (SecurityException ex) {
// Logger.getLogger(FirmaApplet.class.getName()).log(Level.SEVERE, null, ex);
// }
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(FirmaApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(FirmaApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(FirmaApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(FirmaApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the applet */
try {
java.awt.EventQueue.invokeAndWait(new Runnable() {
public void run() {
initComponents();
}
});
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* This method is called from within the init() method to initialize the form. WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
grupoRadios = new javax.swing.ButtonGroup();
jPanel1 = new javax.swing.JPanel();
labelArchivoFirma = new javax.swing.JLabel();
txtRutaArchivo = new javax.swing.JTextField();
btnExaminar = new javax.swing.JButton();
btnFirmarArchivo = new javax.swing.JButton();
tokenIkey = new javax.swing.JRadioButton();
tokenAlladin = new javax.swing.JRadioButton();
tokenSD = new javax.swing.JRadioButton();
grupoRadios.add(tokenIkey);
grupoRadios.add(tokenAlladin);
grupoRadios.add(tokenSD);
labelArchivoFirma.setText("Archivo a firmar");
txtRutaArchivo.setEditable(false);
btnFirmarArchivo.setEnabled(true);
btnExaminar.setEnabled(true);
btnExaminar.setText("Examinar");
btnExaminar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnExaminarActionPerformed(evt);
}
});
btnFirmarArchivo.setText("Firmar");
btnFirmarArchivo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnFirmarArchivoActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(labelArchivoFirma)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(12, 12, 12)
.addComponent(btnFirmarArchivo))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(txtRutaArchivo, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnExaminar)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelArchivoFirma)
.addComponent(txtRutaArchivo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnExaminar))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnFirmarArchivo)
.addContainerGap())
);
tokenIkey.setText("iKey 2032");
tokenIkey.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tokenIkeyActionPerformed(evt);
}
});
tokenAlladin.setText("eTokenPro");
tokenAlladin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tokenAlladinActionPerformed(evt);
}
});
tokenSD.setText("Security Data");
tokenSD.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tokenSDActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGap(41, 41, 41)
.addComponent(tokenIkey)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tokenAlladin)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tokenSD)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(75, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(tokenAlladin)
.addComponent(tokenSD)
.addComponent(tokenIkey))
.addGap(18, 18, 18)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(25, 25, 25))
);
}// </editor-fold>//GEN-END:initComponents
private void btnExaminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExaminarActionPerformed
// TODO add your handling code here:
try
{
/**llamamos el metodo que permite cargar la ventana*/
JFileChooser fileChooser=new JFileChooser();
String rutaArchivo = txtRutaArchivo.getText();
File directorio = new File(rutaArchivo).getParentFile();
fileChooser.setCurrentDirectory(directorio);
// System.out.println("Directorio del archivo "+fileChooser.getCurrentDirectory() != null ? fileChooser.getCurrentDirectory().getAbsolutePath() : "");
/**abrimos el archivo seleccionado*/
int respuestaDialog = fileChooser.showOpenDialog(this);
if(respuestaDialog == JFileChooser.APPROVE_OPTION){
File fileSelected = fileChooser.getSelectedFile();
rutaArchivoFirmar = fileSelected.getAbsolutePath();
System.out.println("Ruta del archivo escogido "+rutaArchivoFirmar);
txtRutaArchivo.setText(rutaArchivoFirmar);
} else{
JOptionPane.showMessageDialog(null,"" +
"\nAccion cancelada por el usuario",
"ADVERTENCIA!!!",JOptionPane.WARNING_MESSAGE);
}
/**recorremos el archivo, lo leemos para plasmarlo
*en el area de texto*/
}catch(Throwable ex)
{
JOptionPane.showMessageDialog(null,ex+"" +
"\nNo se ha encontrado el archivo",
"ADVERTENCIA!!!",JOptionPane.WARNING_MESSAGE);
}
}//GEN-LAST:event_btnExaminarActionPerformed
private void btnFirmarArchivoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFirmarArchivoActionPerformed
// TODO add your handling code here:
InputStream inputStream = null;
try{
String razon = getParameter("razon") != null ? getParameter("razon") : "";
String lugar = getParameter("lugar") != null ? getParameter("lugar") : "";
String nombreFirma = getParameter("firma") != null ? getParameter("firma") : "";
Float llx = Float.valueOf(getParameter("llx") != null ? Float.parseFloat(getParameter("llx")) : 0.0F);
Float lly = Float.valueOf(getParameter("lly") != null ? Float.parseFloat(getParameter("lly")) : 0.0F);
Float urx = Float.valueOf(getParameter("urx") != null ? Float.parseFloat(getParameter("urx")) : 0.0F);
Float ury = Float.valueOf(getParameter("ury") != null ? Float.parseFloat(getParameter("ury")) : 0.0F);
if(tipoFirma == null){
JOptionPane.showMessageDialog(null, "Debe seleccionar un Token con el cual firmar", "Tipo Firma", JOptionPane.ERROR_MESSAGE);
return;
}
if(txtRutaArchivo.getText() != null){
JPasswordField txtPasswordToken = new JPasswordField();
final JComponent[] components = new JComponent[]{new JLabel("Password:"), txtPasswordToken};
JOptionPane.showMessageDialog(null, components, "TOKEN", JOptionPane.PLAIN_MESSAGE);
if(txtPasswordToken.getPassword() == null){
throw new NullPointerException(FirmMessages.getString("FIR-0007"));
}
inputStream = new FileInputStream(txtRutaArchivo.getText());
byte[] datos = CertificateUtils.sign(inputStream, null, new String(txtPasswordToken.getPassword()), razon, lugar, Boolean.FALSE.booleanValue(), Boolean.FALSE.booleanValue(), new Rectangle(llx.floatValue(), lly.floatValue(), urx.floatValue(), ury.floatValue()), 1, nombreFirma, this.tipoFirma);
if(datos != null){
escribirArchivo(datos);
txtPasswordToken.setText("");
JOptionPane.showMessageDialog(null, "El archivo se modificado correctamente", "Archivo firmado", JOptionPane.INFORMATION_MESSAGE);
}
}else{
JOptionPane.showMessageDialog(null, "Debe seleccionar un archivo", "Archivo no encontrado", JOptionPane.ERROR_MESSAGE);
}
btnFirmarArchivo.setEnabled(false);
btnExaminar.setEnabled(false);
} catch(IOException e){
JOptionPane.showMessageDialog(null, e.getMessage(), "IO Error", JOptionPane.ERROR_MESSAGE);
} catch(Exception e){
JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
} finally{
try {
if(inputStream != null){
inputStream.close();
}
} catch (IOException ex) {
Logger.getLogger(FirmaApplet.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_btnFirmarArchivoActionPerformed
public void escribirArchivo(byte[] data){
System.out.println("Ingreso a escribir el archivo");
FileOutputStream fo = null;
try {
File archivoFirmado = new File(txtRutaArchivo.getText());
fo = new FileOutputStream(archivoFirmado);
fo.write(data);
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Error archivo no encontrado", JOptionPane.ERROR_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Error al escribir el archivo firmado", JOptionPane.ERROR_MESSAGE);
} finally {
try {
fo.close();
} catch (IOException ex) {
Logger.getLogger(FirmaApplet.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private void tokenIkeyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tokenIkeyActionPerformed
// TODO add your handling code here:
tipoFirma = "1";
}//GEN-LAST:event_tokenIkeyActionPerformed
private void tokenAlladinActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tokenAlladinActionPerformed
// TODO add your handling code here:
tipoFirma = "2";
}//GEN-LAST:event_tokenAlladinActionPerformed
private void tokenSDActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tokenSDActionPerformed
// TODO add your handling code here:
tipoFirma = "3";
}//GEN-LAST:event_tokenSDActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnExaminar;
private javax.swing.JButton btnFirmarArchivo;
private javax.swing.ButtonGroup grupoRadios;
private javax.swing.JPanel jPanel1;
private javax.swing.JLabel labelArchivoFirma;
private javax.swing.JRadioButton tokenAlladin;
private javax.swing.JRadioButton tokenIkey;
private javax.swing.JRadioButton tokenSD;
private javax.swing.JTextField txtRutaArchivo;
// End of variables declaration//GEN-END:variables
}

View File

@ -0,0 +1,130 @@
10
dir
4669
svn://172.17.26.185/COMACO/sources/appletFirma/src/main/java/com/fp/firma/common
svn://172.17.26.185/COMACO
2014-12-31T05:22:02.287651Z
3703
dcruz
a11ad980-3ca8-45f0-88f7-f0e618c262b7
FirmasException.java
file
2022-07-28T03:40:23.887721Z
84290c6223a2073cf617d181f8c1bdc5
2014-12-31T05:22:02.287651Z
3703
dcruz
has-props
720
CertificateUtils.java
file
2022-07-28T03:40:23.887721Z
17c37f7ea3aec267390dece54b70a43b
2014-12-31T05:22:02.287651Z
3703
dcruz
has-props
25187
FirmMessages.java
file
2022-07-28T03:40:23.888721Z
214a4e732a4b72d7ee6b901019619bf0
2014-12-31T05:22:02.287651Z
3703
dcruz
has-props
361

View File

@ -0,0 +1,9 @@
K 14
svn:executable
V 1
*
K 13
svn:mime-type
V 10
text/plain
END

View File

@ -0,0 +1,9 @@
K 14
svn:executable
V 1
*
K 13
svn:mime-type
V 10
text/plain
END

View File

@ -0,0 +1,9 @@
K 14
svn:executable
V 1
*
K 13
svn:mime-type
V 10
text/plain
END

View File

@ -0,0 +1,584 @@
package com.fp.firma.common;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import com.fp.firma.dto.TfirmDatosFirmante;
import com.fp.firma.keystore.KeyStoreProvider;
import com.fp.firma.keystore.LinuxKeyStoreProvider;
import com.fp.firma.keystore.WindowsJDK6KeyStoreProvider;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfSignatureAppearance;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.security.BouncyCastleDigest;
import com.itextpdf.text.pdf.security.CertificateInfo;
import com.itextpdf.text.pdf.security.CertificateInfo.X500Name;
import com.itextpdf.text.pdf.security.DigestAlgorithms;
import com.itextpdf.text.pdf.security.ExternalDigest;
import com.itextpdf.text.pdf.security.ExternalSignature;
import com.itextpdf.text.pdf.security.MakeSignature;
import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard;
import com.itextpdf.text.pdf.security.OcspClient;
import com.itextpdf.text.pdf.security.OcspClientBouncyCastle;
import com.itextpdf.text.pdf.security.PrivateKeySignature;
import com.itextpdf.text.pdf.security.TSAClient;
//import javax.persistence.NoResultException;
//import javax.persistence.Query;
/**
* Clase que contiene m&eacute;todos utilitarios para manejar certificados
*
* @author dcruz
*
*/
public class CertificateUtils {
/*
* CONSTANTES DESIGNADAS SEGUN LA NUEVA ESTRUCTURA DEL BCE
*/
// OIDs de Campos del Certificado:
public static final String OID_CEDULA_PASAPORTE = FirmMessages.getString("oid.cedula_pasaporte");
public static final String OID_NOMBRES = FirmMessages.getString("oid.nombres_persona");
public static final String OID_APELLIDO_1 = FirmMessages.getString("oid.apellido_persona1");
public static final String OID_APELLIDO_2 = FirmMessages.getString("oid.apellido_persona2");
public static final String OID_CARGO = FirmMessages.getString("oid.cargo");
public static final String OID_INSTITUCION = FirmMessages.getString("oid.institucion");
public static final String OID_DIRECCION = FirmMessages.getString("oid.direccion");
public static final String OID_TELEFONO = FirmMessages.getString("oid.telefono");
public static final String OID_CIUDAD = FirmMessages.getString("oid.ciudad");
public static final String OID_RAZON_SOCIAL = FirmMessages.getString("oid.razon_social");
public static final String OID_RUC = FirmMessages.getString("oid.ruc");
public static final String X509 = "X.509";
static {
BouncyCastleProvider provider = new BouncyCastleProvider();
Security.addProvider(provider);
}
/**
* Retorna el certificado del usuario contenido en la firma
*
* @param store el store en el que se va a buscar los certificados
* @param aliases los alias que estan dentro del keystore
* @return el {@link java.security.Certificate}
* @throws KeyStoreException
*/
public synchronized static Certificate obtainCertificateInAlias(KeyStore store, Enumeration<String> aliases) throws KeyStoreException {
Certificate certs[] = null;
synchronized (aliases) {
int i = 0;
while (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
System.out.println("Se imprime los alias: " + i + " " + alias);
certs = store.getCertificateChain(alias);
for (int j = 0; j < certs.length; j++) {
X509Certificate certificate = (X509Certificate) certs[j];
boolean[] usages = certificate.getKeyUsage();
System.out.println("Certificado en primera posicion usado: " + j + " " + usages[0]);
if (usages[0]) {
return certificate;
}
}
i++;
}
}
return null;
}
/**
* Se devuelve todos los datos de la firma del usuario en base al certificado enviado
*
* @param certificate el certificado enviado
* @return Los datos del certificado de dicho usuario
*/
public static TfirmDatosFirmante obtainDataForCertificate(Certificate certificate) {
X509Certificate signedCertificate = (X509Certificate) certificate;
TfirmDatosFirmante datosFirmante = new TfirmDatosFirmante();
if (signedCertificate.getExtensionValue(OID_CEDULA_PASAPORTE) != null) {
datosFirmante.setIdentificacion(new String(signedCertificate.getExtensionValue(OID_CEDULA_PASAPORTE)).trim());
}
if (signedCertificate.getExtensionValue(OID_NOMBRES) != null) {
datosFirmante.setNombre(new String(signedCertificate.getExtensionValue(OID_NOMBRES)).trim());
}
if (signedCertificate.getExtensionValue(OID_APELLIDO_1) != null) {
datosFirmante.setApellido1(new String(signedCertificate.getExtensionValue(OID_APELLIDO_1)).trim());
if (signedCertificate.getExtensionValue(OID_APELLIDO_2) != null) {
datosFirmante.setApellido2(new String(signedCertificate.getExtensionValue(OID_APELLIDO_2)).trim());
} else {
datosFirmante.setApellido2("");
}
}
if (signedCertificate.getExtensionValue(OID_TELEFONO) != null) {
datosFirmante.setTelefono(new String(signedCertificate.getExtensionValue(OID_TELEFONO)).trim());
}
if (signedCertificate.getExtensionValue(OID_CARGO) != null) {
datosFirmante.setCargo(new String(signedCertificate.getExtensionValue(OID_CARGO)).trim());
}
if (signedCertificate.getExtensionValue(OID_CIUDAD) != null) {
datosFirmante.setCiudad(new String(signedCertificate.getExtensionValue(OID_CIUDAD)).trim());
}
if (signedCertificate.getExtensionValue(OID_DIRECCION) != null) {
datosFirmante.setDireccion(new String(signedCertificate.getExtensionValue(OID_DIRECCION)).trim());
}
if (signedCertificate.getExtensionValue(OID_INSTITUCION) != null) {
datosFirmante.setInstitucion(new String(signedCertificate.getExtensionValue(OID_INSTITUCION)).trim());
}
if (signedCertificate.getExtensionValue(OID_RAZON_SOCIAL) != null) {
datosFirmante.setInstitucion(new String(signedCertificate.getExtensionValue(OID_RAZON_SOCIAL)).trim());
}
if (signedCertificate.getExtensionValue(OID_RUC) != null) {
datosFirmante.setRuc(new String(signedCertificate.getExtensionValue(OID_RUC)).trim());
}
datosFirmante.setFechaInicioVigencia(signedCertificate.getNotBefore());
datosFirmante.setFechaVigencia(signedCertificate.getNotAfter());
return datosFirmante;
}
/**
* Valida que el certificado del usuario sea un certificado valido contra el servicio OCSP del proveedor
*
* @param certificateUser
* @throws FileNotFoundException
* @throws CertificateException
*/
public static void validateOcsCertificate(Certificate certificateUser) throws FileNotFoundException, CertificateException {
System.out.println(((X509Certificate) certificateUser).getIssuerDN().getName());
CertificateFactory cf = CertificateFactory.getInstance(X509);
InputStream subordStream = new FileInputStream(FirmMessages.getString("dir.ruta.base.repositorio") + "/"
+ FirmMessages.getString("nombre.certificado.subordinado"));
X509Certificate subordCertificate = (X509Certificate) cf.generateCertificate(subordStream);
check((X509Certificate) certificateUser, subordCertificate);
}
/**
* Valida que los certificados enviados sean validos por la entidad certificadora
*
* @param issuerCert certificado del usuario
* @param x509Cert certificado que firmo el certificado expedido
*/
public static void check(X509Certificate issuerCert, X509Certificate x509Cert) {
// try {
//
// BigInteger serialNumber = issuerCert.getSerialNumber();
// X509CertificateHolder holder;
//
// try {
// holder = new X509CertificateHolder(x509Cert.getEncoded());
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
//
// CertificateID id = new CertificateID(new JcaDigestCalculatorProviderBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME).build()
// .get(CertificateID.HASH_SHA1), holder, serialNumber);
//
// OCSPReqBuilder ocspGen = new OCSPReqBuilder();
// ocspGen.addRequest(id);
// OCSPReq ocspReq = ocspGen.build();
//
// // Ir al OCSP
// String ocspUrl = CertificateUtil.getOCSPURL(issuerCert);
//
// if (ocspUrl == null) {
// System.out.println("URL de OCSP is null");
// return;
// }
//
// URL url;
//
// try {
// url = new URL(ocspUrl);
// } catch (MalformedURLException e) {
// throw new RuntimeException(e);
// }
//
// HttpURLConnection con;
// OCSPResp ocspResponse;
// DataOutputStream dataOut = null;
// try {
// con = (HttpURLConnection) url.openConnection();
//
// con.setRequestProperty("Content-Type", "application/ocsp-request");
// con.setRequestProperty("Accept", "application/ocsp-response");
// con.setDoOutput(true);
//
// OutputStream out = con.getOutputStream();
// dataOut = new DataOutputStream(new BufferedOutputStream(out));
// dataOut.write(ocspReq.getEncoded());
//
// System.out.println("Estado de respuesta de la peticion=" + con.getResponseCode());
//
// /*
// * Se parsea la respuesta y se obtiene el estado del certificado retornado por el OCSP
// */
// InputStream in = (InputStream) con.getContent();
// byte[] resp = read(in); // Read the reponse
// ocspResponse = new OCSPResp(resp);
// } catch (IOException e) {
// throw new FirmasException("ERROR AL ESTABLECER CONEXI\u00d3N AL SERVICIO: "+url);
// } finally{
// if(dataOut != null){
// try {
// dataOut.flush();
// dataOut.close();
// } catch (IOException e) {}
// }
// }
//
// int status = ocspResponse.getStatus();
// System.out.println("status=" + status);
//
// BasicOCSPResp basicResponse = (BasicOCSPResp) ocspResponse.getResponseObject();
//
// if (basicResponse != null) {
// SingleResp[] responses = basicResponse.getResponses();
// SingleResp response = responses[0];
// CertificateStatus certStatus = (CertificateStatus) response.getCertStatus();
//
// if (certStatus instanceof RevokedStatus) {
// System.out.println("REVOKED");
// RevokedStatus revokedStatus = (RevokedStatus) certStatus;
// System.out.println("Reason: " + revokedStatus.getRevocationReason());
// System.out.println("Date: " + revokedStatus.getRevocationTime());
//
// throw new FirmasException("ERROR, CERTIFICADO REVOCADO POR "+revokedStatus.getRevocationReason()+" CON FECHA "+ revokedStatus.getRevocationTime());
// }
// }
// } catch (OCSPException e) {
// throw new RuntimeException(e);
// } catch (CertificateEncodingException e) {
// throw new RuntimeException(e);
// }
}
/**
* Devuelve los nombres de firmas de un documento PDF
*
* @param docStream el documento a verificar
* @return un lista de nombres de firmas
*/
public static List<String> obtainNameSigns(InputStream docStream) {
try {
PdfReader docPdf = new PdfReader(docStream);
AcroFields af = docPdf.getAcroFields();
return af.getSignatureNames();
} catch (IOException e) {
System.err.println("Error al obtener los nombres del documentoss");
return null;
} finally{
}
}
/**
* M&eacute;todo para firmar documentos
* @param fileSrc
* @param usuario
* @param password
* @param compania
* @param reason
* @param location
* @param rectangle
* @param numPage
* @param nameSign
* @return
* @throws Exception
*/
public static byte[] sign(InputStream fileSrc, String usuario, String password, Integer compania, String reason, String location,
Rectangle rectangle, int numPage, String nameSign, String pathCertificate) throws Exception {
String path = pathCertificate;
FileInputStream ceritificateInputStream = new FileInputStream(path);
return sign(fileSrc, ceritificateInputStream, password, reason, location, false, true, rectangle, numPage, nameSign, null);
}
/**
* Metodo para firmar documentos
* @param fileSrc
* @param usuario
* @param password
* @param compania
* @param reason
* @param location
* @param rectangle
* @param numPage
* @param nameSign
* @return
* @throws Exception
*/
public static byte[] sign(InputStream fileSrc, String usuario, String password, Integer compania, String reason, String location,
Rectangle rectangle, int numPage, String nameSign) throws Exception {
String path = "";
FileInputStream ceritificateInputStream = new FileInputStream(path);
return sign(fileSrc, ceritificateInputStream, password, reason, location, false, true, rectangle, numPage, nameSign, null);
}
/**
* M&eacute;todo que firma un documento en base los par&aacute;metros indicados
*
* @param fileSrc archivo origen
* @param fileCert archivo firma en formato digital si no es null el firmado es con archivo caso contrario es token
* @param password contrasena
* @param reason raz&oacute;n o motivo de la firma.
* @param location localizaci&oacute;n coemtario adicional de la firma.
* @param withTS tiene TS estamapado de tiempo.
* @param withOCSP tiene OCSP verificacion de la firma por el la entidad certificadora BCE.
* @param rectangle lugar localizaci&acute;n firma
* @param numPage n&uacute;mero pagina
* @param nameSign nombre firma
* @param tipoFirma es el tipo de token que se usar&aacute;(Token que tipo?)
* @return el documento firmado
*/
public static byte[] sign(InputStream fileSrc, InputStream fileCert, String password, String reason, String location, boolean withTS,
boolean withOCSP, Rectangle rectangle, int numPage, String nameSign, String tipoFirma) {
OutputStream outputStream = null;
System.out.println("Ingreso a firmar");
try {
PdfReader pdfReader = new PdfReader(fileSrc);
outputStream = new ByteArrayOutputStream(512);
PdfStamper stamper = PdfStamper.createSignature(pdfReader, outputStream, '\0');
PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
KeyStore store;
String alias;
// PrivateKey privateKey = null;
ExternalSignature signature = null;
if(fileCert != null){
store = KeyStore.getInstance("PKCS12");
store.load(fileCert, password.toCharArray());
alias = store.aliases().nextElement();
signature = new PrivateKeySignature((PrivateKey) store.getKey(alias, password.toCharArray()), DigestAlgorithms.SHA256,
"SunRsaSign");
} else{//firma por token
KeyStoreProvider provider = getKeyStoreProvider(tipoFirma);
store = provider.getKeystore(password.toCharArray());
alias = store.aliases().nextElement();
// privateKey = (PrivateKey) store.getKey(alias, null);
signature = new PrivateKeySignature((PrivateKey) store.getKey(alias, null), DigestAlgorithms.SHA1,
null);
}
// appearance.setCrypto(privateKey, store.getCertificateChain(alias), null, null);
appearance.setLayer2Text(generateSignText(store.getCertificateChain(alias), reason, location));
appearance.setLayer2Font(new Font(Font.FontFamily.UNDEFINED, 8F));
appearance.setVisibleSignature(rectangle, numPage, nameSign);
TSAClient tsc = null;
if (withTS) {
}
OcspClient ocsp = null;
if (withOCSP) {
ocsp = new OcspClientBouncyCastle();
}
// stamper.close();
ExternalDigest externalDigest = new BouncyCastleDigest();
MakeSignature.signDetached(appearance, externalDigest, signature, store.getCertificateChain(alias), null, ocsp, tsc, 15000,
CryptoStandard.CADES);
return ((ByteArrayOutputStream) outputStream).toByteArray();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (DocumentException e) {
throw new RuntimeException(e);
} catch (KeyStoreException e) {
throw new RuntimeException(e);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (CertificateException e) {
throw new RuntimeException(e);
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
} catch (FirmasException e) {
throw new RuntimeException(FirmMessages.getString("FIR-0006"));
} catch (Throwable e) {
throw new RuntimeException(e);
} finally{
try {
if(fileCert != null){
fileCert.close();
}
} catch (IOException e) {}
try {
fileSrc.close();
} catch (IOException e) {}
try {
if(outputStream != null){
outputStream.close();
}
} catch (IOException e) {}
}
}
/**
* Arma documento el texto a mostrar de la plantilla
* @param chains certificados
* @param reason raz&oacute;n
* @param location lugar
* @return una layout de la firma
*/
private static String generateSignText(Certificate[] chains, String reason, String location){
StringBuffer textLayout = new StringBuffer("Firmado digitalmente por: ");
String name = null;
X500Name x500name = CertificateInfo.getSubjectFields((X509Certificate)chains[0]);
if (x500name != null) {
name = x500name.getField("CN");
if (name == null)
name = x500name.getField("E");
}
if(name == null){
name = "";
}
textLayout.append(name).append("\n");
if(reason != null){
textLayout.append("Raz\u00f3n: ").append(reason).append("\n");
}
if(location != null){
textLayout.append("Lugar: ").append(location).append("\n");
}
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
textLayout.append("Fecha: ").append(format.format(new Date(System.currentTimeMillis())));
return textLayout.toString();
}
/**
* Retorna el keystore del token especificado
* @param tipoToken
* @return
* @throws KeyStoreException
*/
private static KeyStoreProvider getKeyStoreProvider(String tipoToken) {
String osName = System.getProperty("os.name");
KeyStoreProvider provider = null;
if(tipoToken == null){
return provider;
}
if (osName.toUpperCase().indexOf("WINDOWS") == 0) {
provider = new WindowsJDK6KeyStoreProvider();
if (tipoToken.equals("2")) {
provider = new WindowsJDK6KeyStoreProvider(); // trabaja con librerias sera para eToken
}else if (tipoToken.equals("1")) {
provider = new WindowsJDK6KeyStoreProvider(); // trabaja con librerias sera para iKey
}else if (tipoToken.equals("3")) {
provider = new WindowsJDK6KeyStoreProvider(); // trabaja con librerias sera para iKey
}
} else {
provider = new LinuxKeyStoreProvider();
}
return provider;
}
private static byte[] read(InputStream in) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int next = in.read();
while (next > -1) {
bos.write(next);
next = in.read();
}
bos.flush();
return bos.toByteArray();
}
/**
* Entrega el path en el que se encuentra el certificado digital.
*
* @param cusuario Codigo de usuario.
* @param ccompania Codigo de compania.
* @return String
* @throws Exception
*/
// private static String getPath(String cusuario, Integer ccompania) throws Exception {
// TfirmCertificado tfirmcertificado = getTfirmCertificado(cusuario);
// TgeneParametersKey tgeneParametersKey = new TgeneParametersKey("PATH_CERTIFICADO_BCE", ccompania);
// TgeneParameters tgeneParameters = TgeneParameters.find(PersistenceHelper.getEntityManager(), tgeneParametersKey);
// String path = tgeneParameters.getTextvalue() + "/" + tfirmcertificado.getPk().getIdcertificado();
// return path;
// }
/**
* Sentencia que entrega la defincion vigente de un certificado digital para un usuario.
*/
// private static final String JPQL = "from TfirmCertificado where t.codigousuario = :cusuario";
/**
* Entrega defincion de certificados digitales vigente.
*
* @param cusuario Codigo de usuario.
* @return TfirmCertificado.
* @throws Exception
*/
// private static TfirmCertificado getTfirmCertificado(String cusuario) throws Exception {
// TfirmCertificado tfirmCertificado = null;
// Query qry = PersistenceHelper.getEntityManager().createQuery(JPQL);
// qry.setParameter("cusuario", cusuario);
// try {
// tfirmCertificado = (TfirmCertificado) qry.getSingleResult();
// } catch (NoResultException e) {
// throw new FirmasException("FIR-0001", "PARAMETROS DEL CERTIFICADO DIGITAL NO DEFINIDO PARA EL USUARIO: {0}", cusuario);
// }
// return tfirmCertificado;
// }
/*
public static boolean validatePassword(InputStream fileSrc, String usuario, String password, Integer compania, String reason, String location,
Rectangle rectangle, int numPage, String nameSign) throws Exception {
String path = getPath(usuario, compania);
FileInputStream ceritificateInputStream = new FileInputStream(path);
return pass(fileSrc, ceritificateInputStream, password, reason, location, false, true, rectangle, numPage, nameSign);
}
private static boolean pass(InputStream fileSrc, InputStream fileCert, String password, String reason, String location, boolean withTS,
boolean withOCSP, Rectangle rectangle, int numPage, String nameSign) {
try {
PdfReader pdfReader = new PdfReader(fileSrc);
OutputStream outputStream = new ByteArrayOutputStream(512);
PdfStamper stamper = PdfStamper.createSignature(pdfReader, outputStream, '\0');
PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
KeyStore store = KeyStore.getInstance("PKCS12");
store.load(fileCert, password.toCharArray());
String alias = store.aliases().nextElement();
ExternalSignature signature = new PrivateKeySignature((PrivateKey) store.getKey(alias, password.toCharArray()), DigestAlgorithms.SHA256,
"SunRsaSign");
return true;
} catch (Exception e) {
return false;
}
}
*/
}

View File

@ -0,0 +1,19 @@
package com.fp.firma.common;
import java.util.ResourceBundle;
public class FirmMessages {
private final static String RESOURCE = "firmessages_es";
private final static ResourceBundle firmessages;
static{
firmessages = ResourceBundle.getBundle(RESOURCE);
}
public static String getString(String key) {
return firmessages.getString(key);
}
}

View File

@ -0,0 +1,30 @@
package com.fp.firma.common;
/**
* Clase que manejar&aacute; todos los errores relacionados con la firma digital
*
* @author dcruz
*
*/
public class FirmasException extends RuntimeException {
private static final long serialVersionUID = -599185902882644036L;
public FirmasException(String message) {
super(message);
}
public FirmasException(String message, Throwable cause) {
super(message, cause);
}
public FirmasException(Throwable cause) {
super(cause);
}
public FirmasException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}

View File

@ -0,0 +1,584 @@
package com.fp.firma.common;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import com.fp.firma.dto.TfirmDatosFirmante;
import com.fp.firma.keystore.KeyStoreProvider;
import com.fp.firma.keystore.LinuxKeyStoreProvider;
import com.fp.firma.keystore.WindowsJDK6KeyStoreProvider;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfSignatureAppearance;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.security.BouncyCastleDigest;
import com.itextpdf.text.pdf.security.CertificateInfo;
import com.itextpdf.text.pdf.security.CertificateInfo.X500Name;
import com.itextpdf.text.pdf.security.DigestAlgorithms;
import com.itextpdf.text.pdf.security.ExternalDigest;
import com.itextpdf.text.pdf.security.ExternalSignature;
import com.itextpdf.text.pdf.security.MakeSignature;
import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard;
import com.itextpdf.text.pdf.security.OcspClient;
import com.itextpdf.text.pdf.security.OcspClientBouncyCastle;
import com.itextpdf.text.pdf.security.PrivateKeySignature;
import com.itextpdf.text.pdf.security.TSAClient;
//import javax.persistence.NoResultException;
//import javax.persistence.Query;
/**
* Clase que contiene m&eacute;todos utilitarios para manejar certificados
*
* @author dcruz
*
*/
public class CertificateUtils {
/*
* CONSTANTES DESIGNADAS SEGUN LA NUEVA ESTRUCTURA DEL BCE
*/
// OIDs de Campos del Certificado:
public static final String OID_CEDULA_PASAPORTE = FirmMessages.getString("oid.cedula_pasaporte");
public static final String OID_NOMBRES = FirmMessages.getString("oid.nombres_persona");
public static final String OID_APELLIDO_1 = FirmMessages.getString("oid.apellido_persona1");
public static final String OID_APELLIDO_2 = FirmMessages.getString("oid.apellido_persona2");
public static final String OID_CARGO = FirmMessages.getString("oid.cargo");
public static final String OID_INSTITUCION = FirmMessages.getString("oid.institucion");
public static final String OID_DIRECCION = FirmMessages.getString("oid.direccion");
public static final String OID_TELEFONO = FirmMessages.getString("oid.telefono");
public static final String OID_CIUDAD = FirmMessages.getString("oid.ciudad");
public static final String OID_RAZON_SOCIAL = FirmMessages.getString("oid.razon_social");
public static final String OID_RUC = FirmMessages.getString("oid.ruc");
public static final String X509 = "X.509";
static {
BouncyCastleProvider provider = new BouncyCastleProvider();
Security.addProvider(provider);
}
/**
* Retorna el certificado del usuario contenido en la firma
*
* @param store el store en el que se va a buscar los certificados
* @param aliases los alias que estan dentro del keystore
* @return el {@link java.security.Certificate}
* @throws KeyStoreException
*/
public synchronized static Certificate obtainCertificateInAlias(KeyStore store, Enumeration<String> aliases) throws KeyStoreException {
Certificate certs[] = null;
synchronized (aliases) {
int i = 0;
while (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
System.out.println("Se imprime los alias: " + i + " " + alias);
certs = store.getCertificateChain(alias);
for (int j = 0; j < certs.length; j++) {
X509Certificate certificate = (X509Certificate) certs[j];
boolean[] usages = certificate.getKeyUsage();
System.out.println("Certificado en primera posicion usado: " + j + " " + usages[0]);
if (usages[0]) {
return certificate;
}
}
i++;
}
}
return null;
}
/**
* Se devuelve todos los datos de la firma del usuario en base al certificado enviado
*
* @param certificate el certificado enviado
* @return Los datos del certificado de dicho usuario
*/
public static TfirmDatosFirmante obtainDataForCertificate(Certificate certificate) {
X509Certificate signedCertificate = (X509Certificate) certificate;
TfirmDatosFirmante datosFirmante = new TfirmDatosFirmante();
if (signedCertificate.getExtensionValue(OID_CEDULA_PASAPORTE) != null) {
datosFirmante.setIdentificacion(new String(signedCertificate.getExtensionValue(OID_CEDULA_PASAPORTE)).trim());
}
if (signedCertificate.getExtensionValue(OID_NOMBRES) != null) {
datosFirmante.setNombre(new String(signedCertificate.getExtensionValue(OID_NOMBRES)).trim());
}
if (signedCertificate.getExtensionValue(OID_APELLIDO_1) != null) {
datosFirmante.setApellido1(new String(signedCertificate.getExtensionValue(OID_APELLIDO_1)).trim());
if (signedCertificate.getExtensionValue(OID_APELLIDO_2) != null) {
datosFirmante.setApellido2(new String(signedCertificate.getExtensionValue(OID_APELLIDO_2)).trim());
} else {
datosFirmante.setApellido2("");
}
}
if (signedCertificate.getExtensionValue(OID_TELEFONO) != null) {
datosFirmante.setTelefono(new String(signedCertificate.getExtensionValue(OID_TELEFONO)).trim());
}
if (signedCertificate.getExtensionValue(OID_CARGO) != null) {
datosFirmante.setCargo(new String(signedCertificate.getExtensionValue(OID_CARGO)).trim());
}
if (signedCertificate.getExtensionValue(OID_CIUDAD) != null) {
datosFirmante.setCiudad(new String(signedCertificate.getExtensionValue(OID_CIUDAD)).trim());
}
if (signedCertificate.getExtensionValue(OID_DIRECCION) != null) {
datosFirmante.setDireccion(new String(signedCertificate.getExtensionValue(OID_DIRECCION)).trim());
}
if (signedCertificate.getExtensionValue(OID_INSTITUCION) != null) {
datosFirmante.setInstitucion(new String(signedCertificate.getExtensionValue(OID_INSTITUCION)).trim());
}
if (signedCertificate.getExtensionValue(OID_RAZON_SOCIAL) != null) {
datosFirmante.setInstitucion(new String(signedCertificate.getExtensionValue(OID_RAZON_SOCIAL)).trim());
}
if (signedCertificate.getExtensionValue(OID_RUC) != null) {
datosFirmante.setRuc(new String(signedCertificate.getExtensionValue(OID_RUC)).trim());
}
datosFirmante.setFechaInicioVigencia(signedCertificate.getNotBefore());
datosFirmante.setFechaVigencia(signedCertificate.getNotAfter());
return datosFirmante;
}
/**
* Valida que el certificado del usuario sea un certificado valido contra el servicio OCSP del proveedor
*
* @param certificateUser
* @throws FileNotFoundException
* @throws CertificateException
*/
public static void validateOcsCertificate(Certificate certificateUser) throws FileNotFoundException, CertificateException {
System.out.println(((X509Certificate) certificateUser).getIssuerDN().getName());
CertificateFactory cf = CertificateFactory.getInstance(X509);
InputStream subordStream = new FileInputStream(FirmMessages.getString("dir.ruta.base.repositorio") + "/"
+ FirmMessages.getString("nombre.certificado.subordinado"));
X509Certificate subordCertificate = (X509Certificate) cf.generateCertificate(subordStream);
check((X509Certificate) certificateUser, subordCertificate);
}
/**
* Valida que los certificados enviados sean validos por la entidad certificadora
*
* @param issuerCert certificado del usuario
* @param x509Cert certificado que firmo el certificado expedido
*/
public static void check(X509Certificate issuerCert, X509Certificate x509Cert) {
// try {
//
// BigInteger serialNumber = issuerCert.getSerialNumber();
// X509CertificateHolder holder;
//
// try {
// holder = new X509CertificateHolder(x509Cert.getEncoded());
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
//
// CertificateID id = new CertificateID(new JcaDigestCalculatorProviderBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME).build()
// .get(CertificateID.HASH_SHA1), holder, serialNumber);
//
// OCSPReqBuilder ocspGen = new OCSPReqBuilder();
// ocspGen.addRequest(id);
// OCSPReq ocspReq = ocspGen.build();
//
// // Ir al OCSP
// String ocspUrl = CertificateUtil.getOCSPURL(issuerCert);
//
// if (ocspUrl == null) {
// System.out.println("URL de OCSP is null");
// return;
// }
//
// URL url;
//
// try {
// url = new URL(ocspUrl);
// } catch (MalformedURLException e) {
// throw new RuntimeException(e);
// }
//
// HttpURLConnection con;
// OCSPResp ocspResponse;
// DataOutputStream dataOut = null;
// try {
// con = (HttpURLConnection) url.openConnection();
//
// con.setRequestProperty("Content-Type", "application/ocsp-request");
// con.setRequestProperty("Accept", "application/ocsp-response");
// con.setDoOutput(true);
//
// OutputStream out = con.getOutputStream();
// dataOut = new DataOutputStream(new BufferedOutputStream(out));
// dataOut.write(ocspReq.getEncoded());
//
// System.out.println("Estado de respuesta de la peticion=" + con.getResponseCode());
//
// /*
// * Se parsea la respuesta y se obtiene el estado del certificado retornado por el OCSP
// */
// InputStream in = (InputStream) con.getContent();
// byte[] resp = read(in); // Read the reponse
// ocspResponse = new OCSPResp(resp);
// } catch (IOException e) {
// throw new FirmasException("ERROR AL ESTABLECER CONEXI\u00d3N AL SERVICIO: "+url);
// } finally{
// if(dataOut != null){
// try {
// dataOut.flush();
// dataOut.close();
// } catch (IOException e) {}
// }
// }
//
// int status = ocspResponse.getStatus();
// System.out.println("status=" + status);
//
// BasicOCSPResp basicResponse = (BasicOCSPResp) ocspResponse.getResponseObject();
//
// if (basicResponse != null) {
// SingleResp[] responses = basicResponse.getResponses();
// SingleResp response = responses[0];
// CertificateStatus certStatus = (CertificateStatus) response.getCertStatus();
//
// if (certStatus instanceof RevokedStatus) {
// System.out.println("REVOKED");
// RevokedStatus revokedStatus = (RevokedStatus) certStatus;
// System.out.println("Reason: " + revokedStatus.getRevocationReason());
// System.out.println("Date: " + revokedStatus.getRevocationTime());
//
// throw new FirmasException("ERROR, CERTIFICADO REVOCADO POR "+revokedStatus.getRevocationReason()+" CON FECHA "+ revokedStatus.getRevocationTime());
// }
// }
// } catch (OCSPException e) {
// throw new RuntimeException(e);
// } catch (CertificateEncodingException e) {
// throw new RuntimeException(e);
// }
}
/**
* Devuelve los nombres de firmas de un documento PDF
*
* @param docStream el documento a verificar
* @return un lista de nombres de firmas
*/
public static List<String> obtainNameSigns(InputStream docStream) {
try {
PdfReader docPdf = new PdfReader(docStream);
AcroFields af = docPdf.getAcroFields();
return af.getSignatureNames();
} catch (IOException e) {
System.err.println("Error al obtener los nombres del documentoss");
return null;
} finally{
}
}
/**
* M&eacute;todo para firmar documentos
* @param fileSrc
* @param usuario
* @param password
* @param compania
* @param reason
* @param location
* @param rectangle
* @param numPage
* @param nameSign
* @return
* @throws Exception
*/
public static byte[] sign(InputStream fileSrc, String usuario, String password, Integer compania, String reason, String location,
Rectangle rectangle, int numPage, String nameSign, String pathCertificate) throws Exception {
String path = pathCertificate;
FileInputStream ceritificateInputStream = new FileInputStream(path);
return sign(fileSrc, ceritificateInputStream, password, reason, location, false, true, rectangle, numPage, nameSign, null);
}
/**
* Metodo para firmar documentos
* @param fileSrc
* @param usuario
* @param password
* @param compania
* @param reason
* @param location
* @param rectangle
* @param numPage
* @param nameSign
* @return
* @throws Exception
*/
public static byte[] sign(InputStream fileSrc, String usuario, String password, Integer compania, String reason, String location,
Rectangle rectangle, int numPage, String nameSign) throws Exception {
String path = "";
FileInputStream ceritificateInputStream = new FileInputStream(path);
return sign(fileSrc, ceritificateInputStream, password, reason, location, false, true, rectangle, numPage, nameSign, null);
}
/**
* M&eacute;todo que firma un documento en base los par&aacute;metros indicados
*
* @param fileSrc archivo origen
* @param fileCert archivo firma en formato digital si no es null el firmado es con archivo caso contrario es token
* @param password contrasena
* @param reason raz&oacute;n o motivo de la firma.
* @param location localizaci&oacute;n coemtario adicional de la firma.
* @param withTS tiene TS estamapado de tiempo.
* @param withOCSP tiene OCSP verificacion de la firma por el la entidad certificadora BCE.
* @param rectangle lugar localizaci&acute;n firma
* @param numPage n&uacute;mero pagina
* @param nameSign nombre firma
* @param tipoFirma es el tipo de token que se usar&aacute;(Token que tipo?)
* @return el documento firmado
*/
public static byte[] sign(InputStream fileSrc, InputStream fileCert, String password, String reason, String location, boolean withTS,
boolean withOCSP, Rectangle rectangle, int numPage, String nameSign, String tipoFirma) {
OutputStream outputStream = null;
System.out.println("Ingreso a firmar");
try {
PdfReader pdfReader = new PdfReader(fileSrc);
outputStream = new ByteArrayOutputStream(512);
PdfStamper stamper = PdfStamper.createSignature(pdfReader, outputStream, '\0');
PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
KeyStore store;
String alias;
// PrivateKey privateKey = null;
ExternalSignature signature = null;
if(fileCert != null){
store = KeyStore.getInstance("PKCS12");
store.load(fileCert, password.toCharArray());
alias = store.aliases().nextElement();
signature = new PrivateKeySignature((PrivateKey) store.getKey(alias, password.toCharArray()), DigestAlgorithms.SHA256,
"SunRsaSign");
} else{//firma por token
KeyStoreProvider provider = getKeyStoreProvider(tipoFirma);
store = provider.getKeystore(password.toCharArray());
alias = store.aliases().nextElement();
// privateKey = (PrivateKey) store.getKey(alias, null);
signature = new PrivateKeySignature((PrivateKey) store.getKey(alias, null), DigestAlgorithms.SHA1,
null);
}
// appearance.setCrypto(privateKey, store.getCertificateChain(alias), null, null);
appearance.setLayer2Text(generateSignText(store.getCertificateChain(alias), reason, location));
appearance.setLayer2Font(new Font(Font.FontFamily.UNDEFINED, 8F));
appearance.setVisibleSignature(rectangle, numPage, nameSign);
TSAClient tsc = null;
if (withTS) {
}
OcspClient ocsp = null;
if (withOCSP) {
ocsp = new OcspClientBouncyCastle();
}
// stamper.close();
ExternalDigest externalDigest = new BouncyCastleDigest();
MakeSignature.signDetached(appearance, externalDigest, signature, store.getCertificateChain(alias), null, ocsp, tsc, 15000,
CryptoStandard.CADES);
return ((ByteArrayOutputStream) outputStream).toByteArray();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (DocumentException e) {
throw new RuntimeException(e);
} catch (KeyStoreException e) {
throw new RuntimeException(e);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (CertificateException e) {
throw new RuntimeException(e);
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
} catch (FirmasException e) {
throw new RuntimeException(FirmMessages.getString("FIR-0006"));
} catch (Throwable e) {
throw new RuntimeException(e);
} finally{
try {
if(fileCert != null){
fileCert.close();
}
} catch (IOException e) {}
try {
fileSrc.close();
} catch (IOException e) {}
try {
if(outputStream != null){
outputStream.close();
}
} catch (IOException e) {}
}
}
/**
* Arma documento el texto a mostrar de la plantilla
* @param chains certificados
* @param reason raz&oacute;n
* @param location lugar
* @return una layout de la firma
*/
private static String generateSignText(Certificate[] chains, String reason, String location){
StringBuffer textLayout = new StringBuffer("Firmado digitalmente por: ");
String name = null;
X500Name x500name = CertificateInfo.getSubjectFields((X509Certificate)chains[0]);
if (x500name != null) {
name = x500name.getField("CN");
if (name == null)
name = x500name.getField("E");
}
if(name == null){
name = "";
}
textLayout.append(name).append("\n");
if(reason != null){
textLayout.append("Raz\u00f3n: ").append(reason).append("\n");
}
if(location != null){
textLayout.append("Lugar: ").append(location).append("\n");
}
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
textLayout.append("Fecha: ").append(format.format(new Date(System.currentTimeMillis())));
return textLayout.toString();
}
/**
* Retorna el keystore del token especificado
* @param tipoToken
* @return
* @throws KeyStoreException
*/
private static KeyStoreProvider getKeyStoreProvider(String tipoToken) {
String osName = System.getProperty("os.name");
KeyStoreProvider provider = null;
if(tipoToken == null){
return provider;
}
if (osName.toUpperCase().indexOf("WINDOWS") == 0) {
provider = new WindowsJDK6KeyStoreProvider();
if (tipoToken.equals("2")) {
provider = new WindowsJDK6KeyStoreProvider(); // trabaja con librerias sera para eToken
}else if (tipoToken.equals("1")) {
provider = new WindowsJDK6KeyStoreProvider(); // trabaja con librerias sera para iKey
}else if (tipoToken.equals("3")) {
provider = new WindowsJDK6KeyStoreProvider(); // trabaja con librerias sera para iKey
}
} else {
provider = new LinuxKeyStoreProvider();
}
return provider;
}
private static byte[] read(InputStream in) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int next = in.read();
while (next > -1) {
bos.write(next);
next = in.read();
}
bos.flush();
return bos.toByteArray();
}
/**
* Entrega el path en el que se encuentra el certificado digital.
*
* @param cusuario Codigo de usuario.
* @param ccompania Codigo de compania.
* @return String
* @throws Exception
*/
// private static String getPath(String cusuario, Integer ccompania) throws Exception {
// TfirmCertificado tfirmcertificado = getTfirmCertificado(cusuario);
// TgeneParametersKey tgeneParametersKey = new TgeneParametersKey("PATH_CERTIFICADO_BCE", ccompania);
// TgeneParameters tgeneParameters = TgeneParameters.find(PersistenceHelper.getEntityManager(), tgeneParametersKey);
// String path = tgeneParameters.getTextvalue() + "/" + tfirmcertificado.getPk().getIdcertificado();
// return path;
// }
/**
* Sentencia que entrega la defincion vigente de un certificado digital para un usuario.
*/
// private static final String JPQL = "from TfirmCertificado where t.codigousuario = :cusuario";
/**
* Entrega defincion de certificados digitales vigente.
*
* @param cusuario Codigo de usuario.
* @return TfirmCertificado.
* @throws Exception
*/
// private static TfirmCertificado getTfirmCertificado(String cusuario) throws Exception {
// TfirmCertificado tfirmCertificado = null;
// Query qry = PersistenceHelper.getEntityManager().createQuery(JPQL);
// qry.setParameter("cusuario", cusuario);
// try {
// tfirmCertificado = (TfirmCertificado) qry.getSingleResult();
// } catch (NoResultException e) {
// throw new FirmasException("FIR-0001", "PARAMETROS DEL CERTIFICADO DIGITAL NO DEFINIDO PARA EL USUARIO: {0}", cusuario);
// }
// return tfirmCertificado;
// }
/*
public static boolean validatePassword(InputStream fileSrc, String usuario, String password, Integer compania, String reason, String location,
Rectangle rectangle, int numPage, String nameSign) throws Exception {
String path = getPath(usuario, compania);
FileInputStream ceritificateInputStream = new FileInputStream(path);
return pass(fileSrc, ceritificateInputStream, password, reason, location, false, true, rectangle, numPage, nameSign);
}
private static boolean pass(InputStream fileSrc, InputStream fileCert, String password, String reason, String location, boolean withTS,
boolean withOCSP, Rectangle rectangle, int numPage, String nameSign) {
try {
PdfReader pdfReader = new PdfReader(fileSrc);
OutputStream outputStream = new ByteArrayOutputStream(512);
PdfStamper stamper = PdfStamper.createSignature(pdfReader, outputStream, '\0');
PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
KeyStore store = KeyStore.getInstance("PKCS12");
store.load(fileCert, password.toCharArray());
String alias = store.aliases().nextElement();
ExternalSignature signature = new PrivateKeySignature((PrivateKey) store.getKey(alias, password.toCharArray()), DigestAlgorithms.SHA256,
"SunRsaSign");
return true;
} catch (Exception e) {
return false;
}
}
*/
}

View File

@ -0,0 +1,19 @@
package com.fp.firma.common;
import java.util.ResourceBundle;
public class FirmMessages {
private final static String RESOURCE = "firmessages_es";
private final static ResourceBundle firmessages;
static{
firmessages = ResourceBundle.getBundle(RESOURCE);
}
public static String getString(String key) {
return firmessages.getString(key);
}
}

View File

@ -0,0 +1,30 @@
package com.fp.firma.common;
/**
* Clase que manejar&aacute; todos los errores relacionados con la firma digital
*
* @author dcruz
*
*/
public class FirmasException extends RuntimeException {
private static final long serialVersionUID = -599185902882644036L;
public FirmasException(String message) {
super(message);
}
public FirmasException(String message, Throwable cause) {
super(message, cause);
}
public FirmasException(Throwable cause) {
super(cause);
}
public FirmasException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}

View File

@ -0,0 +1,62 @@
10
dir
4669
svn://172.17.26.185/COMACO/sources/appletFirma/src/main/java/com/fp/firma/component
svn://172.17.26.185/COMACO
2014-12-31T05:22:02.287651Z
3703
dcruz
a11ad980-3ca8-45f0-88f7-f0e618c262b7
PasswordDialog.java
file
2022-07-28T03:40:23.697721Z
2b492580e233dc08baf86d4b915c4e2a
2014-12-31T05:22:02.287651Z
3703
dcruz
has-props
1794

View File

@ -0,0 +1,9 @@
K 14
svn:executable
V 1
*
K 13
svn:mime-type
V 10
text/plain
END

View File

@ -0,0 +1,53 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.fp.firma.component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
/**
* Dialog que permite el ingreso del password del token para la firma
* @author dcruz
*/
public class PasswordDialog extends JDialog implements ActionListener, PropertyChangeListener{
private JPasswordField txtPasswordCertificado;
public PasswordDialog(){
super();
txtPasswordCertificado = new JPasswordField();
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addComponentListener(new ComponentAdapter() {
@Override
public void componentShown(ComponentEvent ce) {
txtPasswordCertificado.requestFocusInWindow();
}
});
txtPasswordCertificado.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public void propertyChange(PropertyChangeEvent evt) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/** This method clears the dialog and hides it. */
public void clearAndHide() {
txtPasswordCertificado.setText(null);
setVisible(false);
}
}

View File

@ -0,0 +1,53 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.fp.firma.component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
/**
* Dialog que permite el ingreso del password del token para la firma
* @author dcruz
*/
public class PasswordDialog extends JDialog implements ActionListener, PropertyChangeListener{
private JPasswordField txtPasswordCertificado;
public PasswordDialog(){
super();
txtPasswordCertificado = new JPasswordField();
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addComponentListener(new ComponentAdapter() {
@Override
public void componentShown(ComponentEvent ce) {
txtPasswordCertificado.requestFocusInWindow();
}
});
txtPasswordCertificado.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public void propertyChange(PropertyChangeEvent evt) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/** This method clears the dialog and hides it. */
public void clearAndHide() {
txtPasswordCertificado.setText(null);
setVisible(false);
}
}

View File

@ -0,0 +1,62 @@
10
dir
4669
svn://172.17.26.185/COMACO/sources/appletFirma/src/main/java/com/fp/firma/dto
svn://172.17.26.185/COMACO
2014-12-31T05:22:02.287651Z
3703
dcruz
a11ad980-3ca8-45f0-88f7-f0e618c262b7
TfirmDatosFirmante.java
file
2022-07-28T03:40:23.854721Z
dab60ed3fdfb2662d1e1b54882a17c12
2014-12-31T05:22:02.287651Z
3703
dcruz
has-props
3379

View File

@ -0,0 +1,9 @@
K 14
svn:executable
V 1
*
K 13
svn:mime-type
V 10
text/plain
END

View File

@ -0,0 +1,169 @@
package com.fp.firma.dto;
import java.io.Serializable;
import java.util.Date;
/**
* Clase que contiene los datos del usuario que es dueno de la firma y en la cual
*
* @author dcruz
*
*/
public class TfirmDatosFirmante implements
Serializable, Cloneable {
private static final long serialVersionUID = 4232773513442100177L;
private String aliasCertificado;
private String identificacion;
private String nombre;
private String apellido1;
private String apellido2;
private String cargo;
private String institucion;
private String direccion;
private String telefono;
private String ciudad;
private String razonSocial;
private String ruc;
private Date fechaInicioVigencia;
private Date fechaVigencia;
public TfirmDatosFirmante(){}
public TfirmDatosFirmante(String identificacion, String nombre,
String apellido1, String apellido2, String cargo,
String institucion, String direccion, String telefono,
String ciudad, String razonSocial, String ruc) {
super();
this.identificacion = identificacion;
this.nombre = nombre;
this.apellido1 = apellido1;
this.apellido2 = apellido2;
this.cargo = cargo;
this.institucion = institucion;
this.direccion = direccion;
this.telefono = telefono;
this.ciudad = ciudad;
this.razonSocial = razonSocial;
this.ruc = ruc;
}
public String getIdentificacion() {
return identificacion;
}
public void setIdentificacion(String identificacion) {
this.identificacion = identificacion;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getApellido1() {
return apellido1;
}
public void setApellido1(String apellido1) {
this.apellido1 = apellido1;
}
public String getApellido2() {
return apellido2;
}
public void setApellido2(String apellido2) {
this.apellido2 = apellido2;
}
public String getCargo() {
return cargo;
}
public void setCargo(String cargo) {
this.cargo = cargo;
}
public String getInstitucion() {
return institucion;
}
public void setInstitucion(String institucion) {
this.institucion = institucion;
}
public String getDireccion() {
return direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public String getCiudad() {
return ciudad;
}
public void setCiudad(String ciudad) {
this.ciudad = ciudad;
}
public String getRazonSocial() {
return razonSocial;
}
public void setRazonSocial(String razonSocial) {
this.razonSocial = razonSocial;
}
public String getRuc() {
return ruc;
}
public void setRuc(String ruc) {
this.ruc = ruc;
}
public Object cloneMe() throws CloneNotSupportedException {
return this.clone();
}
public Date getFechaVigencia() {
return fechaVigencia;
}
public void setFechaVigencia(Date fechaVigencia) {
this.fechaVigencia = fechaVigencia;
}
public Date getFechaInicioVigencia() {
return fechaInicioVigencia;
}
public void setFechaInicioVigencia(Date fechaInicioVigencia) {
this.fechaInicioVigencia = fechaInicioVigencia;
}
public String getAliasCertificado() {
return aliasCertificado;
}
public void setAliasCertificado(String aliasCertificado) {
this.aliasCertificado = aliasCertificado;
}
}

View File

@ -0,0 +1,169 @@
package com.fp.firma.dto;
import java.io.Serializable;
import java.util.Date;
/**
* Clase que contiene los datos del usuario que es dueno de la firma y en la cual
*
* @author dcruz
*
*/
public class TfirmDatosFirmante implements
Serializable, Cloneable {
private static final long serialVersionUID = 4232773513442100177L;
private String aliasCertificado;
private String identificacion;
private String nombre;
private String apellido1;
private String apellido2;
private String cargo;
private String institucion;
private String direccion;
private String telefono;
private String ciudad;
private String razonSocial;
private String ruc;
private Date fechaInicioVigencia;
private Date fechaVigencia;
public TfirmDatosFirmante(){}
public TfirmDatosFirmante(String identificacion, String nombre,
String apellido1, String apellido2, String cargo,
String institucion, String direccion, String telefono,
String ciudad, String razonSocial, String ruc) {
super();
this.identificacion = identificacion;
this.nombre = nombre;
this.apellido1 = apellido1;
this.apellido2 = apellido2;
this.cargo = cargo;
this.institucion = institucion;
this.direccion = direccion;
this.telefono = telefono;
this.ciudad = ciudad;
this.razonSocial = razonSocial;
this.ruc = ruc;
}
public String getIdentificacion() {
return identificacion;
}
public void setIdentificacion(String identificacion) {
this.identificacion = identificacion;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getApellido1() {
return apellido1;
}
public void setApellido1(String apellido1) {
this.apellido1 = apellido1;
}
public String getApellido2() {
return apellido2;
}
public void setApellido2(String apellido2) {
this.apellido2 = apellido2;
}
public String getCargo() {
return cargo;
}
public void setCargo(String cargo) {
this.cargo = cargo;
}
public String getInstitucion() {
return institucion;
}
public void setInstitucion(String institucion) {
this.institucion = institucion;
}
public String getDireccion() {
return direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public String getCiudad() {
return ciudad;
}
public void setCiudad(String ciudad) {
this.ciudad = ciudad;
}
public String getRazonSocial() {
return razonSocial;
}
public void setRazonSocial(String razonSocial) {
this.razonSocial = razonSocial;
}
public String getRuc() {
return ruc;
}
public void setRuc(String ruc) {
this.ruc = ruc;
}
public Object cloneMe() throws CloneNotSupportedException {
return this.clone();
}
public Date getFechaVigencia() {
return fechaVigencia;
}
public void setFechaVigencia(Date fechaVigencia) {
this.fechaVigencia = fechaVigencia;
}
public Date getFechaInicioVigencia() {
return fechaInicioVigencia;
}
public void setFechaInicioVigencia(Date fechaInicioVigencia) {
this.fechaInicioVigencia = fechaInicioVigencia;
}
public String getAliasCertificado() {
return aliasCertificado;
}
public void setAliasCertificado(String aliasCertificado) {
this.aliasCertificado = aliasCertificado;
}
}

View File

@ -0,0 +1,470 @@
10
dir
4669
svn://172.17.26.185/COMACO/sources/appletFirma/src/main/java/com/fp/firma/keystore
svn://172.17.26.185/COMACO
2014-12-31T05:22:02.287651Z
3703
dcruz
a11ad980-3ca8-45f0-88f7-f0e618c262b7
WindowsJDK5KeyStoreProvider_SD.java
file
2022-07-28T03:40:23.800721Z
4355360f5ecffb2d4776d5895e69d2ef
2014-12-31T05:22:02.287651Z
3703
dcruz
has-props
5923
FileKeyStoreProvider.java
file
2022-07-28T03:40:23.801721Z
352ad7236593816e5385e65d46a8b0f2
2014-12-31T05:22:02.287651Z
3703
dcruz
has-props
1478
KeyStoreProvider.java
file
2022-07-28T03:40:23.801721Z
a0f54011dfb2d1e7f45d631fc88fd1b5
2014-12-31T05:22:02.287651Z
3703
dcruz
has-props
712
LinuxKeyStoreProvider.java
file
2022-07-28T03:40:23.801721Z
cd842f1fbfeb4276644783b68fc000f2
2014-12-31T05:22:02.287651Z
3703
dcruz
has-props
4707
AppleKeyStoreProvider.java
file
2022-07-28T03:40:23.802721Z
9cb997093c0456d0e27e53487b3089ed
2014-12-31T05:22:02.287651Z
3703
dcruz
has-props
1435
PKCS11KeyStoreProvider.java
file
2022-07-28T03:40:23.802721Z
9d48dfb6533b29e3de2b09e3558a4102
2014-12-31T05:22:02.287651Z
3703
dcruz
has-props
2747
SimpleCallbackHandler.java
file
2022-07-28T03:40:23.802721Z
f61edcced631f06f1e348a9e69df41a2
2014-12-31T05:22:02.287651Z
3703
dcruz
has-props
1136
KeyStoreProviderFactory.java
file
2022-07-28T03:40:23.803721Z
6592e7f0cf2ac2b4c84453799ff34a3a
2014-12-31T05:22:02.287651Z
3703
dcruz
has-props
1209
WindowsJDK5KeyStoreProvider.java
file
2022-07-28T03:40:23.803721Z
7bf432721d15fd670c94fb663f37d404
2014-12-31T05:22:02.287651Z
3703
dcruz
has-props
5464
MockKeyStoreProvider.java
file
2022-07-28T03:40:23.804721Z
b634940536517cc8b206d61696baaeeb
2014-12-31T05:22:02.287651Z
3703
dcruz
has-props
1696
WindowsJDK5KeyStoreProvider_iKey.java
file
2022-07-28T03:40:23.804721Z
08c26de2f28d4b0ec66430d288a760cc
2014-12-31T05:22:02.287651Z
3703
dcruz
has-props
5977
WindowsJDK6KeyStoreProvider.java
file
2022-07-28T03:40:23.804721Z
17872a0f5c62ffaa84c62af09d9a9da2
2014-12-31T05:22:02.287651Z
3703
dcruz
has-props
1650
WindowsKeyStoreProvider.java
file
2022-07-28T03:40:23.805721Z
32b9f0efba427dd9cb235cbb97baa6e2
2014-12-31T05:22:02.287651Z
3703
dcruz
has-props
1367

View File

@ -0,0 +1,9 @@
K 14
svn:executable
V 1
*
K 13
svn:mime-type
V 10
text/plain
END

View File

@ -0,0 +1,9 @@
K 14
svn:executable
V 1
*
K 13
svn:mime-type
V 10
text/plain
END

View File

@ -0,0 +1,9 @@
K 14
svn:executable
V 1
*
K 13
svn:mime-type
V 10
text/plain
END

View File

@ -0,0 +1,9 @@
K 14
svn:executable
V 1
*
K 13
svn:mime-type
V 10
text/plain
END

View File

@ -0,0 +1,9 @@
K 14
svn:executable
V 1
*
K 13
svn:mime-type
V 10
text/plain
END

View File

@ -0,0 +1,9 @@
K 14
svn:executable
V 1
*
K 13
svn:mime-type
V 10
text/plain
END

View File

@ -0,0 +1,9 @@
K 14
svn:executable
V 1
*
K 13
svn:mime-type
V 10
text/plain
END

View File

@ -0,0 +1,9 @@
K 14
svn:executable
V 1
*
K 13
svn:mime-type
V 10
text/plain
END

View File

@ -0,0 +1,9 @@
K 14
svn:executable
V 1
*
K 13
svn:mime-type
V 10
text/plain
END

View File

@ -0,0 +1,9 @@
K 14
svn:executable
V 1
*
K 13
svn:mime-type
V 10
text/plain
END

View File

@ -0,0 +1,9 @@
K 14
svn:executable
V 1
*
K 13
svn:mime-type
V 10
text/plain
END

View File

@ -0,0 +1,9 @@
K 14
svn:executable
V 1
*
K 13
svn:mime-type
V 10
text/plain
END

View File

@ -0,0 +1,9 @@
K 14
svn:executable
V 1
*
K 13
svn:mime-type
V 10
text/plain
END

View File

@ -0,0 +1,45 @@
/*
* Copyright (C) 2009 Libreria para Firma Digital development team.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*/
package com.fp.firma.keystore;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.cert.CertificateException;
/**
* Implementacion de <code>KeyStoreProvider</code> para el
* sistema operativo Mac OS X.
*
*/
public class AppleKeyStoreProvider implements KeyStoreProvider {
private static final String APPLE_PROVIDER_TYPE = "KeychainStore";
private static final String APPLE_PROVIDER_NAME = "Apple";
@Override
public KeyStore getKeystore(char[] password) throws KeyStoreException {
try {
KeyStore keyStore = KeyStore.getInstance(APPLE_PROVIDER_TYPE, APPLE_PROVIDER_NAME);
keyStore.load(null, null);
return keyStore;
} catch (NoSuchProviderException e) {
throw new KeyStoreException(e);
} catch (NoSuchAlgorithmException e) {
throw new KeyStoreException(e);
} catch (CertificateException e) {
throw new KeyStoreException(e);
} catch (IOException e) {
throw new KeyStoreException(e);
}
}
}

View File

@ -0,0 +1,48 @@
/*
* Copyright (C) 2009 Libreria para Firma Digital development team.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*/
package com.fp.firma.keystore;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
/**
* Implementaci&oacute;n de KeyStoreProvider para leer de un archivo.
*
*/
public class FileKeyStoreProvider implements KeyStoreProvider {
@Override
public KeyStore getKeystore(char[] password) throws KeyStoreException {
try {
InputStream input = new FileInputStream(System.getProperty("user.home") + File.separator + ".keystore");
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(input, password);
return keyStore;
} catch (FileNotFoundException e) {
throw new KeyStoreException(e);
} catch (NoSuchAlgorithmException e) {
throw new KeyStoreException(e);
} catch (CertificateException e) {
throw new KeyStoreException(e);
} catch (IOException e) {
throw new KeyStoreException(e);
} finally {
// TODO: Close InputStream
}
}
}

View File

@ -0,0 +1,29 @@
/*
* Copyright (C) 2009 Libreria para Firma Digital development team.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*/
package com.fp.firma.keystore;
import java.security.KeyStore;
import java.security.KeyStoreException;
/**
* Obtiene un KeyStore.
*
*/
public interface KeyStoreProvider {
/**
* Obtiene un KeyStore protegido por un password.
*
* @param password
* @return
* @throws KeyStoreException
*/
KeyStore getKeystore(char[] password) throws KeyStoreException;
}

View File

@ -0,0 +1,40 @@
package com.fp.firma.keystore;
import java.util.logging.Logger;
/**
* Obtiene la implementacion correcta de KeyStoreProvider de acuerdo al sistema
* operativo.
*/
public class KeyStoreProviderFactory {
private static final Logger log = Logger.getLogger(KeyStoreProviderFactory.class.getName());
/**
* Obtiene la implementacion correcta de KeyStoreProvider de acuerdo al
* sistema operativo.
*
* @return implementacion de KeyStoreProvider
*/
public static KeyStoreProvider createKeyStoreProvider() {
String osName = System.getProperty("os.name");
String javaVersion = System.getProperty("java.version");
log.finer("Operating System:" + osName);
log.finer("Java Version:" + javaVersion);
if (osName.toUpperCase().indexOf("WINDOWS") == 0) {
if (javaVersion.indexOf("1.6") == 0) {
return new WindowsJDK6KeyStoreProvider();
} else {
return new WindowsJDK5KeyStoreProvider();
}
} else if (osName.toUpperCase().indexOf("LINUX") == 0) {
return new LinuxKeyStoreProvider();
} else if (osName.toUpperCase().indexOf("MAC") == 0) {
return new AppleKeyStoreProvider();
} else {
throw new IllegalArgumentException("Sistema operativo no soportado!");
}
}
}

View File

@ -0,0 +1,123 @@
/*
* Copyright (C) 2009 Libreria para Firma Digital development team.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*/
package com.fp.firma.keystore;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.security.AuthProvider;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.Provider;
import java.security.Security;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.security.auth.login.LoginException;
/**
* Implementacion de <code>KeyStoreProvider</code> para utilizar con librerias
* PKCS#11 del sistema operativo Linux.
*
* Utiza OpenCT para acceder a un Token USB.
*
*
*/
public class LinuxKeyStoreProvider implements KeyStoreProvider {
//MAC: /usr/local/lib/libsfntpkcs11.dylib\nslot = 1
private static final byte[] PKCS11_CONFIG = "name = SmartCard\nlibrary = /usr/local/SafeNet/lib/libsfntpkcs11.so\nslot = 1 \n showInfo = true".getBytes(); // /usr/local/SafeNet/lib/libsfntpkcs11.so\nslot = 1
///usr/local/lib/libsfntpkcs11.dylib
private static final String SUN_PKCS11_PROVIDER_CLASS = "sun.security.pkcs11.SunPKCS11";
private AuthProvider aprov;
@Override
public KeyStore getKeystore(char[] password) throws KeyStoreException {
try {
InputStream configStream = new ByteArrayInputStream(PKCS11_CONFIG);
Provider sunPKCS11Provider = this.createSunPKCS11Provider(configStream);
Security.addProvider(sunPKCS11Provider);
// Eestas lineas se añadieron para poder hacer un logout del keystore
//
KeyStore.Builder ksBuilder = KeyStore.Builder.newInstance(
"PKCS11",
null,
new KeyStore.CallbackHandlerProtection( new SimpleCallbackHandler(null,password ) )); //cmdLineHdlr
KeyStore ks = ksBuilder.getKeyStore();
//
aprov = (AuthProvider) Security.getProvider( sunPKCS11Provider.getName() );
aprov.setCallbackHandler( new SimpleCallbackHandler(null,password ) ); //cmdLineHdlr
try {
aprov.login(null, null);
} catch (LoginException ex) {
Logger.getLogger(LinuxKeyStoreProvider.class.getName()).log(Level.SEVERE, null, ex);
throw new LoginException( /*ex*/ );
}
// KeyStore keyStore = KeyStore.getInstance("PKCS11");
//
// keyStore.load(null, password); //null
System.out.println("Dentro LinuxKeystore anntes de ks:" + ks);
// aprov.logout();
return ks; //keyStore
// } catch (CertificateException e) {
// throw new KeyStoreException(e);
// } catch (NoSuchAlgorithmException e) {
// throw new KeyStoreException(e);
// } catch (IOException e) {
// throw new KeyStoreException(e);
// }
} catch (Exception e){
System.out.println("Error en el keystore:" + e);
e.printStackTrace();
throw new KeyStoreException(e);
}
}
/**
* <code> logout </code>
* Esta función permite limpiar de memoria el keystore.
* @throws javax.security.auth.login.LoginException
*/
public void logout() throws LoginException{
this.aprov.logout();
}
/**
* Instancia la clase <code>sun.security.pkcs11.SunPKCS11</code>
* dinamicamente, usando Java Reflection.
*
* @return una instancia de <code>sun.security.pkcs11.SunPKCS11</code>
*/
@SuppressWarnings("unchecked")
private Provider createSunPKCS11Provider(InputStream configStream) throws KeyStoreException {
try {
Class sunPkcs11Class = Class.forName(SUN_PKCS11_PROVIDER_CLASS);
Constructor pkcs11Constr = sunPkcs11Class.getConstructor(InputStream.class);
Provider pkcs11Provider = (Provider) pkcs11Constr.newInstance(configStream);
return pkcs11Provider;
} catch (ClassNotFoundException e) {
throw new KeyStoreException(e);
} catch (NoSuchMethodException e) {
throw new KeyStoreException(e);
} catch (InvocationTargetException e) {
throw new KeyStoreException(e);
} catch (IllegalAccessException e) {
throw new KeyStoreException(e);
} catch (InstantiationException e) {
throw new KeyStoreException(e);
}
}
}

View File

@ -0,0 +1,53 @@
/*
* Copyright (C) 2009 Libreria para Firma Digital development team.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*/
package com.fp.firma.keystore;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.KeyStoreException;
/**
* Implementacion de KeyStoreProvider para pruebas.
*
*/
public class MockKeyStoreProvider implements KeyStoreProvider {
private static final String KEYSTORE_FILE = "/home/ricardo/ricardostore";
// private static final String KEYSTORE_ALIAS = "firmadigital";
// private static final char[] KEYSTORE_PASSWORD = "abc123".toCharArray();
// private static final char[] KEY_PASSWORD = "ricardo".toCharArray();
@Override
public KeyStore getKeystore(char[] password) throws KeyStoreException {
try {
KeyStore keyStore = KeyStore.getInstance("JKS");
FileInputStream ksfis;
ksfis = new FileInputStream(KEYSTORE_FILE);
BufferedInputStream ksbufin = new BufferedInputStream(ksfis);
keyStore.load(ksbufin, password);
// PrivateKey priv = (PrivateKey) keyStore.getKey(KEYSTORE_ALIAS,
// KEY_PASSWORD);
return keyStore;
} catch (FileNotFoundException e) {
throw new KeyStoreException(e);
} catch (GeneralSecurityException e) {
throw new KeyStoreException(e);
} catch (IOException e) {
throw new KeyStoreException(e);
}
}
}

View File

@ -0,0 +1,86 @@
/*
* Copyright (C) 2009 Libreria para Firma Digital development team.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*/
package com.fp.firma.keystore;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.Security;
import java.security.cert.CertificateException;
/**
* Implementacion de <code>KeyStoreProvider</code> para utilizar con librerias
* PKCS#11 del sistema operativo.
*
* Utiza OpenCT para acceder a un Token USB.
*
*
*/
public abstract class PKCS11KeyStoreProvider implements KeyStoreProvider {
/**
* Obtiene la configuraci&oacute;n para el Provider, seg&uacute;n el sistema operativo que se utilice.
*
* @return
*/
public abstract String getConfig();
public KeyStore getKeystore(char[] password) throws KeyStoreException {
try {
InputStream configStream = new ByteArrayInputStream(getConfig().getBytes());
Provider sunPKCS11Provider = this.createSunPKCS11Provider(configStream);
Security.addProvider(sunPKCS11Provider);
KeyStore keyStore = KeyStore.getInstance("PKCS11");
keyStore.load(null, password);
return keyStore;
} catch (CertificateException e) {
throw new KeyStoreException(e);
} catch (NoSuchAlgorithmException e) {
throw new KeyStoreException(e);
} catch (IOException e) {
throw new KeyStoreException(e);
}
}
/**
* Instancia la clase <code>sun.security.pkcs11.SunPKCS11</code>
* dinamicamente, usando Java Reflection.
*
* @return una instancia de <code>sun.security.pkcs11.SunPKCS11</code>
*/
@SuppressWarnings("unchecked")
private Provider createSunPKCS11Provider(InputStream configStream) throws KeyStoreException {
try {
Class sunPkcs11Class = Class.forName("sun.security.pkcs11.SunPKCS11");
Constructor pkcs11Constr = sunPkcs11Class.getConstructor(InputStream.class);
return (Provider) pkcs11Constr.newInstance(configStream);
} catch (ClassNotFoundException e) {
throw new KeyStoreException(e);
} catch (NoSuchMethodException e) {
throw new KeyStoreException(e);
} catch (InvocationTargetException e) {
throw new KeyStoreException(e);
} catch (IllegalAccessException e) {
throw new KeyStoreException(e);
} catch (InstantiationException e) {
throw new KeyStoreException(e);
}
}
}

View File

@ -0,0 +1,49 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.fp.firma.keystore;
/**
*
* @author subinfo
*/
import javax.security.auth.callback.*;
/**
* This simple callback handler presents the given user name and password.
* @version 1.0 2004-09-14
* @author Cay Horstmann
*/
public class SimpleCallbackHandler implements CallbackHandler
{
/**
* Constructs the callback handler.
* @param username the user name
* @param password a character array containing the password
*/
public SimpleCallbackHandler(String username, char[] password)
{
this.username = username;
this.password = password;
}
public void handle(Callback[] callbacks)
{
for (Callback callback : callbacks)
{
if (callback instanceof NameCallback)
{
((NameCallback) callback).setName(username);
}
else if (callback instanceof PasswordCallback)
{
((PasswordCallback) callback).setPassword(password);
}
}
}
private String username;
private char[] password;
}

View File

@ -0,0 +1,129 @@
/** Programa para La firma electrónica de archivos
* Desarrollado y Modificado por la Subsecretaría de Tecnologías de la Información
* de la Secretaría Nacional de la Administración Pública del Ecuador
* Firma Digital firmadigital.informatica.gob.ec
*------------------------------------------------------------------------------
* This program is free software: you can redistribute it and/or
modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
License
* along with this program. If not, see http://www.gnu.org/licenses. [^]
*------------------------------------------------------------------------------
**/
package com.fp.firma.keystore;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.AuthProvider;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.Provider;
import java.security.ProviderException;
import java.security.Security;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.management.ReflectionException;
import javax.security.auth.login.LoginException;
/**
* maneja el keystore de windows, no el CAPI, accede a travez de librerias, en esta se usa librerias para eTokenPro
**/
public class WindowsJDK5KeyStoreProvider implements KeyStoreProvider {
//private static final byte[] PKCS11_CONFIG = "name = SmartCard\nlibrary = C:\\WINDOWS\\SYSTEM32\\DKCK201.DLL \ndisabledMechanisms = { CKM_SHA1_RSA_PKCS }".getBytes();
private static String windowsDir = "name = SmartCard\nlibrary = " + System.getenv("WINDIR") + "\\SYSTEM32\\eTPKCS11.DLL \ndisabledMechanisms = { CKM_SHA1_RSA_PKCS } \n showInfo = true"; //showInfo = true
private static final byte[] PKCS11_CONFIG = windowsDir.getBytes();
private static final String SUN_PKCS11_PROVIDER_CLASS = "sun.security.pkcs11.SunPKCS11";
private AuthProvider aprov;
@Override
public KeyStore getKeystore(char[] password) throws KeyStoreException {
try {
System.out.println("Tiene PKCS11: " + PKCS11_CONFIG);
InputStream configStream = new ByteArrayInputStream(PKCS11_CONFIG);
Provider sunPKCS11Provider = this.createSunPKCS11Provider(configStream);
Security.addProvider(sunPKCS11Provider);
KeyStore.Builder ksBuilder = KeyStore.Builder.newInstance(
"PKCS11",
null,
new KeyStore.CallbackHandlerProtection(new SimpleCallbackHandler(null, password))); //cmdLineHdlr
KeyStore ks = ksBuilder.getKeyStore();
aprov = (AuthProvider) Security.getProvider(sunPKCS11Provider.getName());
aprov.setCallbackHandler(new SimpleCallbackHandler(null, password)); //cmdLineHdlr
aprov.login(null, null);
//
return ks; //keyStore
//
} catch (LoginException ex) {
Logger.getLogger(WindowsJDK5KeyStoreProvider.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("error en el loginExcep" + ex);
} catch (KeyStoreException e) {
System.out.println("e:" + e.getCause().toString().length());
throw new KeyStoreException(e);
}
// catch (Exception e){
// System.out.println("Error en el keystore:" + e.getCause().toString().length() );
// throw new KeyStoreException( e.getMessage() ,e.getCause());
// }
return null;
}
/**
* <code> logout </code>
* Esta función permite limpiar de memoria el keystore.
* @throws javax.security.auth.login.LoginException
*/
public void logout() throws LoginException {
this.aprov.logout();
}
/**
* Instancia la clase <code>sun.security.pkcs11.SunPKCS11</code>
* dinamicamente, usando Java Reflection.
*
* @return una instancia de <code>sun.security.pkcs11.SunPKCS11</code>
*/
@SuppressWarnings("unchecked")
private Provider createSunPKCS11Provider(InputStream configStream) throws ProviderException, KeyStoreException {
try {
Class sunPkcs11Class = Class.forName(SUN_PKCS11_PROVIDER_CLASS);
Constructor pkcs11Constr = sunPkcs11Class.getConstructor(InputStream.class);
Provider pkcs11Provider = (Provider) pkcs11Constr.newInstance(configStream);
return pkcs11Provider;
} catch (ClassNotFoundException e) {
throw new KeyStoreException(e);
} catch (NoSuchMethodException e) {
throw new KeyStoreException(e);
} catch (InvocationTargetException e) {
throw new KeyStoreException(e.getMessage(), e.getCause());
} catch (IllegalAccessException e) {
throw new KeyStoreException(e);
} catch (InstantiationException e) {
throw new KeyStoreException(e);
}
}
}

View File

@ -0,0 +1,139 @@
/** Programa para La firma electrónica de archivos
* Desarrollado y Modificado por la Subsecretaría de Tecnologías de la Información
* de la Secretaría Nacional de la Administración Pública del Ecuador
* Firma Digital firmadigital.informatica.gob.ec
*------------------------------------------------------------------------------
* This program is free software: you can redistribute it and/or
modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
License
* along with this program. If not, see http://www.gnu.org/licenses. [^]
*------------------------------------------------------------------------------
**/
package com.fp.firma.keystore;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.security.AuthProvider;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.Provider;
import java.security.Security;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.security.auth.login.LoginException;
/**
* Esta clase se usa para obtener el keystore (Con el se pueden obtener luego los certificados dentro del token) en Windows
*/
public class WindowsJDK5KeyStoreProvider_SD implements KeyStoreProvider {
//private static final byte[] PKCS11_CONFIG = "name = SmartCard\nlibrary = C:\\WINDOWS\\SYSTEM32\\DKCK201.DLL \ndisabledMechanisms = { CKM_SHA1_RSA_PKCS }".getBytes();
// esta linea corrige el error de la ubicación de Windows
// para trabajar con iKey
private static final String windowsDir_SD = "name = ePass3003\nlibrary = C:\\WINDOWS\\SYSTEM32\\SecurityDataCsp11_3003.dll \ndisabledMechanisms = { CKM_SHA1_RSA_PKCS } \n\r showInfo = true";
private static final byte[] PKCS11_CONFIG_SD = windowsDir_SD.getBytes();
private static final String SUN_PKCS11_PROVIDER_CLASS = "sun.security.pkcs11.SunPKCS11";
private AuthProvider aprov;
/**
* <code> getKeystore </code>
* Esta funcion se utiliza para obtener el keystore de java para manejar luego la clave privada y los certificados dentro del token
* @param password Se pasa la clave del token
* @return
* @throws java.security.KeyStoreException
*/
@Override
public KeyStore getKeystore(char[] password) throws KeyStoreException {
try {
// empieza intentando con eToken
InputStream configStream = new ByteArrayInputStream(PKCS11_CONFIG_SD);
Provider sunPKCS11Provider = this.createSunPKCS11Provider(configStream);
Security.addProvider(sunPKCS11Provider);
KeyStore.Builder ksBuilder = KeyStore.Builder.newInstance(
"PKCS11",
null,
new KeyStore.CallbackHandlerProtection(new SimpleCallbackHandler(null, password))); //cmdLineHdlr
KeyStore ks = ksBuilder.getKeyStore();
// Estas lineas se añadieron para controlar mejor el logout del token
aprov = (AuthProvider) Security.getProvider(sunPKCS11Provider.getName());
aprov.setCallbackHandler(new SimpleCallbackHandler(null, password)); //cmdLineHdlr
try {
aprov.login(null, null);
} catch (LoginException ex) {
Logger.getLogger(WindowsJDK5KeyStoreProvider_SD.class.getName()).log(Level.SEVERE, null, ex);
throw new LoginException( /*ex*/);
}
return ks; //keyStore
} catch (LoginException ex) {
Logger.getLogger(WindowsJDK5KeyStoreProvider_SD.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("error en el loginExcep" + ex);
} catch (KeyStoreException e) {
System.out.println("e:" + e.getCause().toString().length());
throw new KeyStoreException(e);
}
// } catch (Exception e){
// System.out.println("Error en el keystore:" + e);
// throw new KeyStoreException(e);
// }
return null;
}
/**
* <code> logout </code>
* Esta función permite limpiar de memoria el keystore.
* @throws javax.security.auth.login.LoginException
*/
public void logout() throws LoginException {
this.aprov.logout();
}
/**
* Instancia la clase <code>sun.security.pkcs11.SunPKCS11</code>
* dinamicamente, usando Java Reflection.
*
* @return una instancia de <code>sun.security.pkcs11.SunPKCS11</code>
*/
@SuppressWarnings("unchecked")
private Provider createSunPKCS11Provider(InputStream configStream) throws KeyStoreException {
try {
Class sunPkcs11Class = Class.forName(SUN_PKCS11_PROVIDER_CLASS);
Constructor pkcs11Constr = sunPkcs11Class.getConstructor(InputStream.class);
Provider pkcs11Provider = (Provider) pkcs11Constr.newInstance(configStream);
return pkcs11Provider;
} catch (ClassNotFoundException e) {
throw new KeyStoreException(e);
} catch (NoSuchMethodException e) {
throw new KeyStoreException(e);
} catch (InvocationTargetException e) {
throw new KeyStoreException(e);
} catch (IllegalAccessException e) {
throw new KeyStoreException(e);
} catch (InstantiationException e) {
throw new KeyStoreException(e);
}
}
}

View File

@ -0,0 +1,144 @@
/** Programa para La firma electrónica de archivos
* Desarrollado y Modificado por la Subsecretaría de Tecnologías de la Información
* de la Secretaría Nacional de la Administración Pública del Ecuador
* Firma Digital firmadigital.informatica.gob.ec
*------------------------------------------------------------------------------
* This program is free software: you can redistribute it and/or
modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
License
* along with this program. If not, see http://www.gnu.org/licenses. [^]
*------------------------------------------------------------------------------
**/
package com.fp.firma.keystore;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.security.AuthProvider;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.Provider;
import java.security.Security;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.security.auth.login.LoginException;
/**
* Esta clase se usa para obtener el keystore (Con el se pueden obtener luego los certificados dentro del token iKEY) en Windows
*/
public class WindowsJDK5KeyStoreProvider_iKey implements KeyStoreProvider {
//private static final byte[] PKCS11_CONFIG = "name = SmartCard\nlibrary = C:\\WINDOWS\\SYSTEM32\\DKCK201.DLL \ndisabledMechanisms = { CKM_SHA1_RSA_PKCS }".getBytes();
// esta linea corrige el error de la ubicación de Windows
// para trabajar con iKey
private static String windowsDir_iKey ="name = SmartCard\nlibrary = "+ System.getenv("WINDIR") + "\\SYSTEM32\\DKCK201.DLL \ndisabledMechanisms = { CKM_SHA1_RSA_PKCS } \n showInfo = true";
private static final byte[] PKCS11_CONFIG_IKEY = windowsDir_iKey.getBytes();
private static final String SUN_PKCS11_PROVIDER_CLASS = "sun.security.pkcs11.SunPKCS11";
private AuthProvider aprov;
/**
* <code> getKeystore </code>
* Esta funcion se utiliza para obtener el keystore de java para manejar luego la clave privada y los certificados dentro del token
* @param password Se pasa la clave del token
* @return
* @throws java.security.KeyStoreException
*/
@Override
public KeyStore getKeystore(char[] password) throws KeyStoreException {
try {
// empieza intentando con eToken
InputStream configStream = new ByteArrayInputStream(PKCS11_CONFIG_IKEY);
Provider sunPKCS11Provider = this.createSunPKCS11Provider(configStream);
Security.addProvider(sunPKCS11Provider);
KeyStore.Builder ksBuilder = KeyStore.Builder.newInstance(
"PKCS11",
null,
new KeyStore.CallbackHandlerProtection( new SimpleCallbackHandler(null,password ) )); //cmdLineHdlr
KeyStore ks = ksBuilder.getKeyStore();
// Estas lineas se añadieron para controlar mejor el logout del token
aprov = (AuthProvider) Security.getProvider( sunPKCS11Provider.getName() );
aprov.setCallbackHandler( new SimpleCallbackHandler(null,password ) ); //cmdLineHdlr
try {
aprov.login(null, null);
} catch (LoginException ex) {
Logger.getLogger(WindowsJDK5KeyStoreProvider_iKey.class.getName()).log(Level.SEVERE, null, ex);
throw new LoginException( /*ex*/ );
}
return ks; //keyStore
}
catch (LoginException ex) {
Logger.getLogger(WindowsJDK5KeyStoreProvider_iKey.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("error en el loginExcep" + ex);
} catch (KeyStoreException e) {
System.out.println("e:"+ e.getCause().toString().length() );
throw new KeyStoreException(e);
}
// } catch (Exception e){
// System.out.println("Error en el keystore:" + e);
// throw new KeyStoreException(e);
// }
return null;
}
/**
* <code> logout </code>
* Esta función permite limpiar de memoria el keystore.
* @throws javax.security.auth.login.LoginException
*/
public void logout() throws LoginException{
this.aprov.logout();
}
/**
* Instancia la clase <code>sun.security.pkcs11.SunPKCS11</code>
* dinamicamente, usando Java Reflection.
*
* @return una instancia de <code>sun.security.pkcs11.SunPKCS11</code>
*/
@SuppressWarnings("unchecked")
private Provider createSunPKCS11Provider(InputStream configStream) throws KeyStoreException {
try {
Class sunPkcs11Class = Class.forName(SUN_PKCS11_PROVIDER_CLASS);
Constructor pkcs11Constr = sunPkcs11Class.getConstructor(InputStream.class);
Provider pkcs11Provider = (Provider) pkcs11Constr.newInstance(configStream);
return pkcs11Provider;
} catch (ClassNotFoundException e) {
throw new KeyStoreException(e);
} catch (NoSuchMethodException e) {
throw new KeyStoreException(e);
} catch (InvocationTargetException e) {
throw new KeyStoreException(e);
} catch (IllegalAccessException e) {
throw new KeyStoreException(e);
} catch (InstantiationException e) {
throw new KeyStoreException(e);
}
}
}

View File

@ -0,0 +1,53 @@
/*
* Copyright (C) 2009 Libreria para Firma Digital development team.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*/
package com.fp.firma.keystore;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import com.fp.firma.common.FirmasException;
/**
* Implementaci&oacute;n de KeyStoreProvider para acceder al keystore del sistema operativo
* Microsoft Windows.
*
* Utiliza funcionalidad disponible desde el JDK6 en adelante para acceder al MS CAPI.
*
*/
public class WindowsJDK6KeyStoreProvider implements KeyStoreProvider {
public KeyStore getKeystore(char[] password) throws KeyStoreException {
try {
KeyStore keyStore = KeyStore.getInstance("Windows-MY");
keyStore.load(null, password);
return keyStore;
} catch (NoSuchAlgorithmException e) {
throw new KeyStoreException(e);
} catch (CertificateException e) {
throw new KeyStoreException(e);
} catch (IOException e) {
if(e.getCause() instanceof UnrecoverableKeyException){
throw new FirmasException(e);
} else{
throw new KeyStoreException(e);
}
} catch (Throwable e) {
if ((e instanceof UnrecoverableKeyException)) {
throw new FirmasException(e);
} else{
throw new KeyStoreException(e);
}
}
}
}

View File

@ -0,0 +1,43 @@
/*
* Copyright (C) 2009 Libreria para Firma Digital development team.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*/
package com.fp.firma.keystore;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
/**
* Implementacion de KeyStoreProvider para acceder al keystore del sistema operativo
* Microsoft Windows.
*
* Utiliza funcionalidad disponible desde el JDK6 en adelante para acceder al MS CAPI.
*
*/
public class WindowsKeyStoreProvider implements KeyStoreProvider {
private static final String MICROSOFT_WINDOWS_PROVIDER_TYPE = "Windows-MY";
@Override
public KeyStore getKeystore(char[] password) throws KeyStoreException {
try {
KeyStore keyStore = KeyStore.getInstance(MICROSOFT_WINDOWS_PROVIDER_TYPE);
keyStore.load(null, password);
return keyStore;
} catch (NoSuchAlgorithmException e) {
throw new KeyStoreException(e);
} catch (CertificateException e) {
throw new KeyStoreException(e);
} catch (IOException e) {
throw new KeyStoreException(e);
}
}
}

View File

@ -0,0 +1,45 @@
/*
* Copyright (C) 2009 Libreria para Firma Digital development team.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*/
package com.fp.firma.keystore;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.cert.CertificateException;
/**
* Implementacion de <code>KeyStoreProvider</code> para el
* sistema operativo Mac OS X.
*
*/
public class AppleKeyStoreProvider implements KeyStoreProvider {
private static final String APPLE_PROVIDER_TYPE = "KeychainStore";
private static final String APPLE_PROVIDER_NAME = "Apple";
@Override
public KeyStore getKeystore(char[] password) throws KeyStoreException {
try {
KeyStore keyStore = KeyStore.getInstance(APPLE_PROVIDER_TYPE, APPLE_PROVIDER_NAME);
keyStore.load(null, null);
return keyStore;
} catch (NoSuchProviderException e) {
throw new KeyStoreException(e);
} catch (NoSuchAlgorithmException e) {
throw new KeyStoreException(e);
} catch (CertificateException e) {
throw new KeyStoreException(e);
} catch (IOException e) {
throw new KeyStoreException(e);
}
}
}

View File

@ -0,0 +1,48 @@
/*
* Copyright (C) 2009 Libreria para Firma Digital development team.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*/
package com.fp.firma.keystore;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
/**
* Implementaci&oacute;n de KeyStoreProvider para leer de un archivo.
*
*/
public class FileKeyStoreProvider implements KeyStoreProvider {
@Override
public KeyStore getKeystore(char[] password) throws KeyStoreException {
try {
InputStream input = new FileInputStream(System.getProperty("user.home") + File.separator + ".keystore");
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(input, password);
return keyStore;
} catch (FileNotFoundException e) {
throw new KeyStoreException(e);
} catch (NoSuchAlgorithmException e) {
throw new KeyStoreException(e);
} catch (CertificateException e) {
throw new KeyStoreException(e);
} catch (IOException e) {
throw new KeyStoreException(e);
} finally {
// TODO: Close InputStream
}
}
}

View File

@ -0,0 +1,29 @@
/*
* Copyright (C) 2009 Libreria para Firma Digital development team.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*/
package com.fp.firma.keystore;
import java.security.KeyStore;
import java.security.KeyStoreException;
/**
* Obtiene un KeyStore.
*
*/
public interface KeyStoreProvider {
/**
* Obtiene un KeyStore protegido por un password.
*
* @param password
* @return
* @throws KeyStoreException
*/
KeyStore getKeystore(char[] password) throws KeyStoreException;
}

View File

@ -0,0 +1,40 @@
package com.fp.firma.keystore;
import java.util.logging.Logger;
/**
* Obtiene la implementacion correcta de KeyStoreProvider de acuerdo al sistema
* operativo.
*/
public class KeyStoreProviderFactory {
private static final Logger log = Logger.getLogger(KeyStoreProviderFactory.class.getName());
/**
* Obtiene la implementacion correcta de KeyStoreProvider de acuerdo al
* sistema operativo.
*
* @return implementacion de KeyStoreProvider
*/
public static KeyStoreProvider createKeyStoreProvider() {
String osName = System.getProperty("os.name");
String javaVersion = System.getProperty("java.version");
log.finer("Operating System:" + osName);
log.finer("Java Version:" + javaVersion);
if (osName.toUpperCase().indexOf("WINDOWS") == 0) {
if (javaVersion.indexOf("1.6") == 0) {
return new WindowsJDK6KeyStoreProvider();
} else {
return new WindowsJDK5KeyStoreProvider();
}
} else if (osName.toUpperCase().indexOf("LINUX") == 0) {
return new LinuxKeyStoreProvider();
} else if (osName.toUpperCase().indexOf("MAC") == 0) {
return new AppleKeyStoreProvider();
} else {
throw new IllegalArgumentException("Sistema operativo no soportado!");
}
}
}

View File

@ -0,0 +1,123 @@
/*
* Copyright (C) 2009 Libreria para Firma Digital development team.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*/
package com.fp.firma.keystore;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.security.AuthProvider;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.Provider;
import java.security.Security;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.security.auth.login.LoginException;
/**
* Implementacion de <code>KeyStoreProvider</code> para utilizar con librerias
* PKCS#11 del sistema operativo Linux.
*
* Utiza OpenCT para acceder a un Token USB.
*
*
*/
public class LinuxKeyStoreProvider implements KeyStoreProvider {
//MAC: /usr/local/lib/libsfntpkcs11.dylib\nslot = 1
private static final byte[] PKCS11_CONFIG = "name = SmartCard\nlibrary = /usr/local/SafeNet/lib/libsfntpkcs11.so\nslot = 1 \n showInfo = true".getBytes(); // /usr/local/SafeNet/lib/libsfntpkcs11.so\nslot = 1
///usr/local/lib/libsfntpkcs11.dylib
private static final String SUN_PKCS11_PROVIDER_CLASS = "sun.security.pkcs11.SunPKCS11";
private AuthProvider aprov;
@Override
public KeyStore getKeystore(char[] password) throws KeyStoreException {
try {
InputStream configStream = new ByteArrayInputStream(PKCS11_CONFIG);
Provider sunPKCS11Provider = this.createSunPKCS11Provider(configStream);
Security.addProvider(sunPKCS11Provider);
// Eestas lineas se ±adieron para poder hacer un logout del keystore
//
KeyStore.Builder ksBuilder = KeyStore.Builder.newInstance(
"PKCS11",
null,
new KeyStore.CallbackHandlerProtection( new SimpleCallbackHandler(null,password ) )); //cmdLineHdlr
KeyStore ks = ksBuilder.getKeyStore();
//
aprov = (AuthProvider) Security.getProvider( sunPKCS11Provider.getName() );
aprov.setCallbackHandler( new SimpleCallbackHandler(null,password ) ); //cmdLineHdlr
try {
aprov.login(null, null);
} catch (LoginException ex) {
Logger.getLogger(LinuxKeyStoreProvider.class.getName()).log(Level.SEVERE, null, ex);
throw new LoginException( /*ex*/ );
}
// KeyStore keyStore = KeyStore.getInstance("PKCS11");
//
// keyStore.load(null, password); //null
System.out.println("Dentro LinuxKeystore anntes de ks:" + ks);
// aprov.logout();
return ks; //keyStore
// } catch (CertificateException e) {
// throw new KeyStoreException(e);
// } catch (NoSuchAlgorithmException e) {
// throw new KeyStoreException(e);
// } catch (IOException e) {
// throw new KeyStoreException(e);
// }
} catch (Exception e){
System.out.println("Error en el keystore:" + e);
e.printStackTrace();
throw new KeyStoreException(e);
}
}
/**
* <code> logout </code>
* Esta función permite limpiar de memoria el keystore.
* @throws javax.security.auth.login.LoginException
*/
public void logout() throws LoginException{
this.aprov.logout();
}
/**
* Instancia la clase <code>sun.security.pkcs11.SunPKCS11</code>
* dinamicamente, usando Java Reflection.
*
* @return una instancia de <code>sun.security.pkcs11.SunPKCS11</code>
*/
@SuppressWarnings("unchecked")
private Provider createSunPKCS11Provider(InputStream configStream) throws KeyStoreException {
try {
Class sunPkcs11Class = Class.forName(SUN_PKCS11_PROVIDER_CLASS);
Constructor pkcs11Constr = sunPkcs11Class.getConstructor(InputStream.class);
Provider pkcs11Provider = (Provider) pkcs11Constr.newInstance(configStream);
return pkcs11Provider;
} catch (ClassNotFoundException e) {
throw new KeyStoreException(e);
} catch (NoSuchMethodException e) {
throw new KeyStoreException(e);
} catch (InvocationTargetException e) {
throw new KeyStoreException(e);
} catch (IllegalAccessException e) {
throw new KeyStoreException(e);
} catch (InstantiationException e) {
throw new KeyStoreException(e);
}
}
}

View File

@ -0,0 +1,53 @@
/*
* Copyright (C) 2009 Libreria para Firma Digital development team.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*/
package com.fp.firma.keystore;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.KeyStoreException;
/**
* Implementacion de KeyStoreProvider para pruebas.
*
*/
public class MockKeyStoreProvider implements KeyStoreProvider {
private static final String KEYSTORE_FILE = "/home/ricardo/ricardostore";
// private static final String KEYSTORE_ALIAS = "firmadigital";
// private static final char[] KEYSTORE_PASSWORD = "abc123".toCharArray();
// private static final char[] KEY_PASSWORD = "ricardo".toCharArray();
@Override
public KeyStore getKeystore(char[] password) throws KeyStoreException {
try {
KeyStore keyStore = KeyStore.getInstance("JKS");
FileInputStream ksfis;
ksfis = new FileInputStream(KEYSTORE_FILE);
BufferedInputStream ksbufin = new BufferedInputStream(ksfis);
keyStore.load(ksbufin, password);
// PrivateKey priv = (PrivateKey) keyStore.getKey(KEYSTORE_ALIAS,
// KEY_PASSWORD);
return keyStore;
} catch (FileNotFoundException e) {
throw new KeyStoreException(e);
} catch (GeneralSecurityException e) {
throw new KeyStoreException(e);
} catch (IOException e) {
throw new KeyStoreException(e);
}
}
}

View File

@ -0,0 +1,86 @@
/*
* Copyright (C) 2009 Libreria para Firma Digital development team.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*/
package com.fp.firma.keystore;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.Security;
import java.security.cert.CertificateException;
/**
* Implementacion de <code>KeyStoreProvider</code> para utilizar con librerias
* PKCS#11 del sistema operativo.
*
* Utiza OpenCT para acceder a un Token USB.
*
*
*/
public abstract class PKCS11KeyStoreProvider implements KeyStoreProvider {
/**
* Obtiene la configuraci&oacute;n para el Provider, seg&uacute;n el sistema operativo que se utilice.
*
* @return
*/
public abstract String getConfig();
public KeyStore getKeystore(char[] password) throws KeyStoreException {
try {
InputStream configStream = new ByteArrayInputStream(getConfig().getBytes());
Provider sunPKCS11Provider = this.createSunPKCS11Provider(configStream);
Security.addProvider(sunPKCS11Provider);
KeyStore keyStore = KeyStore.getInstance("PKCS11");
keyStore.load(null, password);
return keyStore;
} catch (CertificateException e) {
throw new KeyStoreException(e);
} catch (NoSuchAlgorithmException e) {
throw new KeyStoreException(e);
} catch (IOException e) {
throw new KeyStoreException(e);
}
}
/**
* Instancia la clase <code>sun.security.pkcs11.SunPKCS11</code>
* dinamicamente, usando Java Reflection.
*
* @return una instancia de <code>sun.security.pkcs11.SunPKCS11</code>
*/
@SuppressWarnings("unchecked")
private Provider createSunPKCS11Provider(InputStream configStream) throws KeyStoreException {
try {
Class sunPkcs11Class = Class.forName("sun.security.pkcs11.SunPKCS11");
Constructor pkcs11Constr = sunPkcs11Class.getConstructor(InputStream.class);
return (Provider) pkcs11Constr.newInstance(configStream);
} catch (ClassNotFoundException e) {
throw new KeyStoreException(e);
} catch (NoSuchMethodException e) {
throw new KeyStoreException(e);
} catch (InvocationTargetException e) {
throw new KeyStoreException(e);
} catch (IllegalAccessException e) {
throw new KeyStoreException(e);
} catch (InstantiationException e) {
throw new KeyStoreException(e);
}
}
}

View File

@ -0,0 +1,49 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.fp.firma.keystore;
/**
*
* @author subinfo
*/
import javax.security.auth.callback.*;
/**
* This simple callback handler presents the given user name and password.
* @version 1.0 2004-09-14
* @author Cay Horstmann
*/
public class SimpleCallbackHandler implements CallbackHandler
{
/**
* Constructs the callback handler.
* @param username the user name
* @param password a character array containing the password
*/
public SimpleCallbackHandler(String username, char[] password)
{
this.username = username;
this.password = password;
}
public void handle(Callback[] callbacks)
{
for (Callback callback : callbacks)
{
if (callback instanceof NameCallback)
{
((NameCallback) callback).setName(username);
}
else if (callback instanceof PasswordCallback)
{
((PasswordCallback) callback).setPassword(password);
}
}
}
private String username;
private char[] password;
}

View File

@ -0,0 +1,129 @@
/** Programa para La firma electrónica de archivos
* Desarrollado y Modificado por la Subsecretaría de Tecnologías de la Información
* de la Secretaría Nacional de la Administración Pública del Ecuador
* Firma Digital firmadigital.informatica.gob.ec
*------------------------------------------------------------------------------
* This program is free software: you can redistribute it and/or
modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
License
* along with this program. If not, see http://www.gnu.org/licenses. [^]
*------------------------------------------------------------------------------
**/
package com.fp.firma.keystore;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.AuthProvider;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.Provider;
import java.security.ProviderException;
import java.security.Security;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.management.ReflectionException;
import javax.security.auth.login.LoginException;
/**
* maneja el keystore de windows, no el CAPI, accede a travez de librerias, en esta se usa librerias para eTokenPro
**/
public class WindowsJDK5KeyStoreProvider implements KeyStoreProvider {
//private static final byte[] PKCS11_CONFIG = "name = SmartCard\nlibrary = C:\\WINDOWS\\SYSTEM32\\DKCK201.DLL \ndisabledMechanisms = { CKM_SHA1_RSA_PKCS }".getBytes();
private static String windowsDir = "name = SmartCard\nlibrary = " + System.getenv("WINDIR") + "\\SYSTEM32\\eTPKCS11.DLL \ndisabledMechanisms = { CKM_SHA1_RSA_PKCS } \n showInfo = true"; //showInfo = true
private static final byte[] PKCS11_CONFIG = windowsDir.getBytes();
private static final String SUN_PKCS11_PROVIDER_CLASS = "sun.security.pkcs11.SunPKCS11";
private AuthProvider aprov;
@Override
public KeyStore getKeystore(char[] password) throws KeyStoreException {
try {
System.out.println("Tiene PKCS11: " + PKCS11_CONFIG);
InputStream configStream = new ByteArrayInputStream(PKCS11_CONFIG);
Provider sunPKCS11Provider = this.createSunPKCS11Provider(configStream);
Security.addProvider(sunPKCS11Provider);
KeyStore.Builder ksBuilder = KeyStore.Builder.newInstance(
"PKCS11",
null,
new KeyStore.CallbackHandlerProtection(new SimpleCallbackHandler(null, password))); //cmdLineHdlr
KeyStore ks = ksBuilder.getKeyStore();
aprov = (AuthProvider) Security.getProvider(sunPKCS11Provider.getName());
aprov.setCallbackHandler(new SimpleCallbackHandler(null, password)); //cmdLineHdlr
aprov.login(null, null);
//
return ks; //keyStore
//
} catch (LoginException ex) {
Logger.getLogger(WindowsJDK5KeyStoreProvider.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("error en el loginExcep" + ex);
} catch (KeyStoreException e) {
System.out.println("e:" + e.getCause().toString().length());
throw new KeyStoreException(e);
}
// catch (Exception e){
// System.out.println("Error en el keystore:" + e.getCause().toString().length() );
// throw new KeyStoreException( e.getMessage() ,e.getCause());
// }
return null;
}
/**
* <code> logout </code>
* Esta función permite limpiar de memoria el keystore.
* @throws javax.security.auth.login.LoginException
*/
public void logout() throws LoginException {
this.aprov.logout();
}
/**
* Instancia la clase <code>sun.security.pkcs11.SunPKCS11</code>
* dinamicamente, usando Java Reflection.
*
* @return una instancia de <code>sun.security.pkcs11.SunPKCS11</code>
*/
@SuppressWarnings("unchecked")
private Provider createSunPKCS11Provider(InputStream configStream) throws ProviderException, KeyStoreException {
try {
Class sunPkcs11Class = Class.forName(SUN_PKCS11_PROVIDER_CLASS);
Constructor pkcs11Constr = sunPkcs11Class.getConstructor(InputStream.class);
Provider pkcs11Provider = (Provider) pkcs11Constr.newInstance(configStream);
return pkcs11Provider;
} catch (ClassNotFoundException e) {
throw new KeyStoreException(e);
} catch (NoSuchMethodException e) {
throw new KeyStoreException(e);
} catch (InvocationTargetException e) {
throw new KeyStoreException(e.getMessage(), e.getCause());
} catch (IllegalAccessException e) {
throw new KeyStoreException(e);
} catch (InstantiationException e) {
throw new KeyStoreException(e);
}
}
}

View File

@ -0,0 +1,139 @@
/** Programa para La firma electrónica de archivos
* Desarrollado y Modificado por la Subsecretaría de Tecnologías de la Información
* de la Secretaría Nacional de la Administración Pública del Ecuador
* Firma Digital firmadigital.informatica.gob.ec
*------------------------------------------------------------------------------
* This program is free software: you can redistribute it and/or
modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
License
* along with this program. If not, see http://www.gnu.org/licenses. [^]
*------------------------------------------------------------------------------
**/
package com.fp.firma.keystore;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.security.AuthProvider;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.Provider;
import java.security.Security;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.security.auth.login.LoginException;
/**
* Esta clase se usa para obtener el keystore (Con el se pueden obtener luego los certificados dentro del token) en Windows
*/
public class WindowsJDK5KeyStoreProvider_SD implements KeyStoreProvider {
//private static final byte[] PKCS11_CONFIG = "name = SmartCard\nlibrary = C:\\WINDOWS\\SYSTEM32\\DKCK201.DLL \ndisabledMechanisms = { CKM_SHA1_RSA_PKCS }".getBytes();
// esta linea corrige el error de la ubicación de Windows
// para trabajar con iKey
private static final String windowsDir_SD = "name = ePass3003\nlibrary = C:\\WINDOWS\\SYSTEM32\\SecurityDataCsp11_3003.dll \ndisabledMechanisms = { CKM_SHA1_RSA_PKCS } \n\r showInfo = true";
private static final byte[] PKCS11_CONFIG_SD = windowsDir_SD.getBytes();
private static final String SUN_PKCS11_PROVIDER_CLASS = "sun.security.pkcs11.SunPKCS11";
private AuthProvider aprov;
/**
* <code> getKeystore </code>
* Esta funcion se utiliza para obtener el keystore de java para manejar luego la clave privada y los certificados dentro del token
* @param password Se pasa la clave del token
* @return
* @throws java.security.KeyStoreException
*/
@Override
public KeyStore getKeystore(char[] password) throws KeyStoreException {
try {
// empieza intentando con eToken
InputStream configStream = new ByteArrayInputStream(PKCS11_CONFIG_SD);
Provider sunPKCS11Provider = this.createSunPKCS11Provider(configStream);
Security.addProvider(sunPKCS11Provider);
KeyStore.Builder ksBuilder = KeyStore.Builder.newInstance(
"PKCS11",
null,
new KeyStore.CallbackHandlerProtection(new SimpleCallbackHandler(null, password))); //cmdLineHdlr
KeyStore ks = ksBuilder.getKeyStore();
// Estas lineas se añadieron para controlar mejor el logout del token
aprov = (AuthProvider) Security.getProvider(sunPKCS11Provider.getName());
aprov.setCallbackHandler(new SimpleCallbackHandler(null, password)); //cmdLineHdlr
try {
aprov.login(null, null);
} catch (LoginException ex) {
Logger.getLogger(WindowsJDK5KeyStoreProvider_SD.class.getName()).log(Level.SEVERE, null, ex);
throw new LoginException( /*ex*/);
}
return ks; //keyStore
} catch (LoginException ex) {
Logger.getLogger(WindowsJDK5KeyStoreProvider_SD.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("error en el loginExcep" + ex);
} catch (KeyStoreException e) {
System.out.println("e:" + e.getCause().toString().length());
throw new KeyStoreException(e);
}
// } catch (Exception e){
// System.out.println("Error en el keystore:" + e);
// throw new KeyStoreException(e);
// }
return null;
}
/**
* <code> logout </code>
* Esta función permite limpiar de memoria el keystore.
* @throws javax.security.auth.login.LoginException
*/
public void logout() throws LoginException {
this.aprov.logout();
}
/**
* Instancia la clase <code>sun.security.pkcs11.SunPKCS11</code>
* dinamicamente, usando Java Reflection.
*
* @return una instancia de <code>sun.security.pkcs11.SunPKCS11</code>
*/
@SuppressWarnings("unchecked")
private Provider createSunPKCS11Provider(InputStream configStream) throws KeyStoreException {
try {
Class sunPkcs11Class = Class.forName(SUN_PKCS11_PROVIDER_CLASS);
Constructor pkcs11Constr = sunPkcs11Class.getConstructor(InputStream.class);
Provider pkcs11Provider = (Provider) pkcs11Constr.newInstance(configStream);
return pkcs11Provider;
} catch (ClassNotFoundException e) {
throw new KeyStoreException(e);
} catch (NoSuchMethodException e) {
throw new KeyStoreException(e);
} catch (InvocationTargetException e) {
throw new KeyStoreException(e);
} catch (IllegalAccessException e) {
throw new KeyStoreException(e);
} catch (InstantiationException e) {
throw new KeyStoreException(e);
}
}
}

View File

@ -0,0 +1,144 @@
/** Programa para La firma electrónica de archivos
* Desarrollado y Modificado por la Subsecretaría de Tecnologías de la Información
* de la Secretaría Nacional de la Administración Pública del Ecuador
* Firma Digital firmadigital.informatica.gob.ec
*------------------------------------------------------------------------------
* This program is free software: you can redistribute it and/or
modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
License
* along with this program. If not, see http://www.gnu.org/licenses. [^]
*------------------------------------------------------------------------------
**/
package com.fp.firma.keystore;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.security.AuthProvider;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.Provider;
import java.security.Security;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.security.auth.login.LoginException;
/**
* Esta clase se usa para obtener el keystore (Con el se pueden obtener luego los certificados dentro del token iKEY) en Windows
*/
public class WindowsJDK5KeyStoreProvider_iKey implements KeyStoreProvider {
//private static final byte[] PKCS11_CONFIG = "name = SmartCard\nlibrary = C:\\WINDOWS\\SYSTEM32\\DKCK201.DLL \ndisabledMechanisms = { CKM_SHA1_RSA_PKCS }".getBytes();
// esta linea corrige el error de la ubicación de Windows
// para trabajar con iKey
private static String windowsDir_iKey ="name = SmartCard\nlibrary = "+ System.getenv("WINDIR") + "\\SYSTEM32\\DKCK201.DLL \ndisabledMechanisms = { CKM_SHA1_RSA_PKCS } \n showInfo = true";
private static final byte[] PKCS11_CONFIG_IKEY = windowsDir_iKey.getBytes();
private static final String SUN_PKCS11_PROVIDER_CLASS = "sun.security.pkcs11.SunPKCS11";
private AuthProvider aprov;
/**
* <code> getKeystore </code>
* Esta funcion se utiliza para obtener el keystore de java para manejar luego la clave privada y los certificados dentro del token
* @param password Se pasa la clave del token
* @return
* @throws java.security.KeyStoreException
*/
@Override
public KeyStore getKeystore(char[] password) throws KeyStoreException {
try {
// empieza intentando con eToken
InputStream configStream = new ByteArrayInputStream(PKCS11_CONFIG_IKEY);
Provider sunPKCS11Provider = this.createSunPKCS11Provider(configStream);
Security.addProvider(sunPKCS11Provider);
KeyStore.Builder ksBuilder = KeyStore.Builder.newInstance(
"PKCS11",
null,
new KeyStore.CallbackHandlerProtection( new SimpleCallbackHandler(null,password ) )); //cmdLineHdlr
KeyStore ks = ksBuilder.getKeyStore();
// Estas lineas se añadieron para controlar mejor el logout del token
aprov = (AuthProvider) Security.getProvider( sunPKCS11Provider.getName() );
aprov.setCallbackHandler( new SimpleCallbackHandler(null,password ) ); //cmdLineHdlr
try {
aprov.login(null, null);
} catch (LoginException ex) {
Logger.getLogger(WindowsJDK5KeyStoreProvider_iKey.class.getName()).log(Level.SEVERE, null, ex);
throw new LoginException( /*ex*/ );
}
return ks; //keyStore
}
catch (LoginException ex) {
Logger.getLogger(WindowsJDK5KeyStoreProvider_iKey.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("error en el loginExcep" + ex);
} catch (KeyStoreException e) {
System.out.println("e:"+ e.getCause().toString().length() );
throw new KeyStoreException(e);
}
// } catch (Exception e){
// System.out.println("Error en el keystore:" + e);
// throw new KeyStoreException(e);
// }
return null;
}
/**
* <code> logout </code>
* Esta función permite limpiar de memoria el keystore.
* @throws javax.security.auth.login.LoginException
*/
public void logout() throws LoginException{
this.aprov.logout();
}
/**
* Instancia la clase <code>sun.security.pkcs11.SunPKCS11</code>
* dinamicamente, usando Java Reflection.
*
* @return una instancia de <code>sun.security.pkcs11.SunPKCS11</code>
*/
@SuppressWarnings("unchecked")
private Provider createSunPKCS11Provider(InputStream configStream) throws KeyStoreException {
try {
Class sunPkcs11Class = Class.forName(SUN_PKCS11_PROVIDER_CLASS);
Constructor pkcs11Constr = sunPkcs11Class.getConstructor(InputStream.class);
Provider pkcs11Provider = (Provider) pkcs11Constr.newInstance(configStream);
return pkcs11Provider;
} catch (ClassNotFoundException e) {
throw new KeyStoreException(e);
} catch (NoSuchMethodException e) {
throw new KeyStoreException(e);
} catch (InvocationTargetException e) {
throw new KeyStoreException(e);
} catch (IllegalAccessException e) {
throw new KeyStoreException(e);
} catch (InstantiationException e) {
throw new KeyStoreException(e);
}
}
}

View File

@ -0,0 +1,53 @@
/*
* Copyright (C) 2009 Libreria para Firma Digital development team.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*/
package com.fp.firma.keystore;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import com.fp.firma.common.FirmasException;
/**
* Implementaci&oacute;n de KeyStoreProvider para acceder al keystore del sistema operativo
* Microsoft Windows.
*
* Utiliza funcionalidad disponible desde el JDK6 en adelante para acceder al MS CAPI.
*
*/
public class WindowsJDK6KeyStoreProvider implements KeyStoreProvider {
public KeyStore getKeystore(char[] password) throws KeyStoreException {
try {
KeyStore keyStore = KeyStore.getInstance("Windows-MY");
keyStore.load(null, password);
return keyStore;
} catch (NoSuchAlgorithmException e) {
throw new KeyStoreException(e);
} catch (CertificateException e) {
throw new KeyStoreException(e);
} catch (IOException e) {
if(e.getCause() instanceof UnrecoverableKeyException){
throw new FirmasException(e);
} else{
throw new KeyStoreException(e);
}
} catch (Throwable e) {
if ((e instanceof UnrecoverableKeyException)) {
throw new FirmasException(e);
} else{
throw new KeyStoreException(e);
}
}
}
}

View File

@ -0,0 +1,43 @@
/*
* Copyright (C) 2009 Libreria para Firma Digital development team.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*/
package com.fp.firma.keystore;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
/**
* Implementacion de KeyStoreProvider para acceder al keystore del sistema operativo
* Microsoft Windows.
*
* Utiliza funcionalidad disponible desde el JDK6 en adelante para acceder al MS CAPI.
*
*/
public class WindowsKeyStoreProvider implements KeyStoreProvider {
private static final String MICROSOFT_WINDOWS_PROVIDER_TYPE = "Windows-MY";
@Override
public KeyStore getKeystore(char[] password) throws KeyStoreException {
try {
KeyStore keyStore = KeyStore.getInstance(MICROSOFT_WINDOWS_PROVIDER_TYPE);
keyStore.load(null, password);
return keyStore;
} catch (NoSuchAlgorithmException e) {
throw new KeyStoreException(e);
} catch (CertificateException e) {
throw new KeyStoreException(e);
} catch (IOException e) {
throw new KeyStoreException(e);
}
}
}

View File

@ -0,0 +1,62 @@
10
dir
4669
svn://172.17.26.185/COMACO/sources/appletFirma/src/main/resources
svn://172.17.26.185/COMACO
2014-12-31T05:22:02.287651Z
3703
dcruz
a11ad980-3ca8-45f0-88f7-f0e618c262b7
firmessages_es.properties
file
2022-07-28T03:40:24.020722Z
3474bb130f9466563b3dd13b5fbb1efb
2014-12-31T05:22:02.287651Z
3703
dcruz
has-props
2185

View File

@ -0,0 +1,9 @@
K 14
svn:executable
V 1
*
K 13
svn:mime-type
V 10
text/plain
END

View File

@ -0,0 +1,48 @@
###################################################
##### S\u00edmbolos unicode
#####\u00e1 -> á
#####\u00e9 -> é
#####\u00ed -> í
#####\u00f3 -> ó
#####\u00fa -> ú
#####\u00c1 -> Á
#####\u00c9 -> É
#####\u00cd -> Í
#####\u00d3 -> Ó
#####\u00da -> Ú
#####\u00f1 -> ñ
#####\u00d1 -> Ñ
#####\u0020 -> Espacio en blanco
###################################################
#========================================================================================
#=======CODIGO EXCEPCIONES===============================================================
#========================================================================================
FIR-0001=ERROR AL ESTABLECER CONEXI\u00D3N AL SERVICIO\: {0}
FIR-0002=ERROR, CERTIFICADO REVOCADO POR {0} CON FECHA {1}
FIR-0005=ERROR, ES OBLIGATORIO CARGAR UN ARCHIVO
FIR-0006=ERROR, LA CONTRASE\u00d1A INGRESADA ES INCORRECTA
FIR-0007=ERROR, EL CAMPO PASSWORD ES OBLIGATORIO
#========================================================================================
#=======OIDs GENERALES DE IDENTIFICACION DEL USUARIO EN EL CERTIFICADO===================
#========================================================================================
oid.cedula_pasaporte=1.3.6.1.4.1.37947.3.1
oid.nombres_persona=1.3.6.1.4.1.37947.3.2
oid.apellido_persona1=1.3.6.1.4.1.37947.3.3
oid.apellido_persona2=1.3.6.1.4.1.37947.3.4
oid.cargo=1.3.6.1.4.1.37947.3.5
oid.institucion=1.3.6.1.4.1.37947.3.6
oid.direccion=1.3.6.1.4.1.37947.3.7
oid.telefono=1.3.6.1.4.1.37947.3.8
oid.ciudad=1.3.6.1.4.1.37947.3.9
oid.razon_social=1.3.6.1.4.1.37947.3.10
oid.ruc=1.3.6.1.4.1.37947.3.11
#========================================================================================
#=======RUTAS DE LOS DIRECTORIOS DEL REPOSITORIO DE CERTIFICADOS=========================
#========================================================================================
dir.ruta.base.repositorio=/media/store/maia/jboss-eap-6.0/digital_repository
dir.nombre.carpeta.usuarios=users
nombre.certificado.raiz=CARAIZ.cer
nombre.certificado.subordinado=CASUBORDINADO.cer
service.url.address.ocsp=http://ocsp.digsigtrust.com:80
#service.url.address.ocsp=http://ocsp.openvalidation.org:80

View File

@ -0,0 +1,48 @@
###################################################
##### S\u00edmbolos unicode
#####\u00e1 -> á
#####\u00e9 -> é
#####\u00ed -> í
#####\u00f3 -> ó
#####\u00fa -> ú
#####\u00c1 -> Á
#####\u00c9 -> É
#####\u00cd -> Í
#####\u00d3 -> Ó
#####\u00da -> Ú
#####\u00f1 -> ñ
#####\u00d1 -> Ñ
#####\u0020 -> Espacio en blanco
###################################################
#========================================================================================
#=======CODIGO EXCEPCIONES===============================================================
#========================================================================================
FIR-0001=ERROR AL ESTABLECER CONEXI\u00D3N AL SERVICIO\: {0}
FIR-0002=ERROR, CERTIFICADO REVOCADO POR {0} CON FECHA {1}
FIR-0005=ERROR, ES OBLIGATORIO CARGAR UN ARCHIVO
FIR-0006=ERROR, LA CONTRASE\u00d1A INGRESADA ES INCORRECTA
FIR-0007=ERROR, EL CAMPO PASSWORD ES OBLIGATORIO
#========================================================================================
#=======OIDs GENERALES DE IDENTIFICACION DEL USUARIO EN EL CERTIFICADO===================
#========================================================================================
oid.cedula_pasaporte=1.3.6.1.4.1.37947.3.1
oid.nombres_persona=1.3.6.1.4.1.37947.3.2
oid.apellido_persona1=1.3.6.1.4.1.37947.3.3
oid.apellido_persona2=1.3.6.1.4.1.37947.3.4
oid.cargo=1.3.6.1.4.1.37947.3.5
oid.institucion=1.3.6.1.4.1.37947.3.6
oid.direccion=1.3.6.1.4.1.37947.3.7
oid.telefono=1.3.6.1.4.1.37947.3.8
oid.ciudad=1.3.6.1.4.1.37947.3.9
oid.razon_social=1.3.6.1.4.1.37947.3.10
oid.ruc=1.3.6.1.4.1.37947.3.11
#========================================================================================
#=======RUTAS DE LOS DIRECTORIOS DEL REPOSITORIO DE CERTIFICADOS=========================
#========================================================================================
dir.ruta.base.repositorio=/media/store/maia/jboss-eap-6.0/digital_repository
dir.nombre.carpeta.usuarios=users
nombre.certificado.raiz=CARAIZ.cer
nombre.certificado.subordinado=CASUBORDINADO.cer
service.url.address.ocsp=http://ocsp.digsigtrust.com:80
#service.url.address.ocsp=http://ocsp.openvalidation.org:80

View File

@ -0,0 +1,31 @@
10
dir
4669
svn://172.17.26.185/COMACO/sources/appletFirma/src/test
svn://172.17.26.185/COMACO
2014-12-31T05:22:02.287651Z
3703
dcruz
a11ad980-3ca8-45f0-88f7-f0e618c262b7
java
dir

View File

@ -0,0 +1,31 @@
10
dir
4669
svn://172.17.26.185/COMACO/sources/appletFirma/src/test/java
svn://172.17.26.185/COMACO
2014-12-31T05:22:02.287651Z
3703
dcruz
a11ad980-3ca8-45f0-88f7-f0e618c262b7
com
dir

View File

@ -0,0 +1,31 @@
10
dir
4669
svn://172.17.26.185/COMACO/sources/appletFirma/src/test/java/com
svn://172.17.26.185/COMACO
2014-12-31T05:22:02.287651Z
3703
dcruz
a11ad980-3ca8-45f0-88f7-f0e618c262b7
fp
dir

View File

@ -0,0 +1,31 @@
10
dir
4669
svn://172.17.26.185/COMACO/sources/appletFirma/src/test/java/com/fp
svn://172.17.26.185/COMACO
2014-12-31T05:22:02.287651Z
3703
dcruz
a11ad980-3ca8-45f0-88f7-f0e618c262b7
firma
dir

View File

@ -0,0 +1,31 @@
10
dir
4669
svn://172.17.26.185/COMACO/sources/appletFirma/src/test/java/com/fp/firma
svn://172.17.26.185/COMACO
2014-12-31T05:22:02.287651Z
3703
dcruz
a11ad980-3ca8-45f0-88f7-f0e618c262b7
applet
dir

View File

@ -0,0 +1,96 @@
10
dir
4669
svn://172.17.26.185/COMACO/sources/appletFirma/src/test/java/com/fp/firma/applet
svn://172.17.26.185/COMACO
2014-12-31T05:22:02.287651Z
3703
dcruz
a11ad980-3ca8-45f0-88f7-f0e618c262b7
AppTest.java
file
2022-07-28T03:40:23.474720Z
344982b9ae13a54e1ca56bbb62751f55
2014-12-31T05:22:02.287651Z
3703
dcruz
has-props
647
PruebaFirma.java
file
2022-07-28T03:40:23.474720Z
16809319f5505f378ce18fb335a59914
2014-12-31T05:22:02.287651Z
3703
dcruz
has-props
1324

View File

@ -0,0 +1,9 @@
K 14
svn:executable
V 1
*
K 13
svn:mime-type
V 10
text/plain
END

View File

@ -0,0 +1,9 @@
K 14
svn:executable
V 1
*
K 13
svn:mime-type
V 10
text/plain
END

View File

@ -0,0 +1,38 @@
package com.fp.firma.applet;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}

View File

@ -0,0 +1,39 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.fp.firma.applet;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import com.fp.firma.common.CertificateUtils;
import com.itextpdf.text.Rectangle;
/**
*
* @author dcruz
*/
public class PruebaFirma {
// @Test
public static void main(String[] args){
try {
InputStream is = new FileInputStream("C:\\Users\\abenalcazar\\dwhelper\\Downloads\\Tutorial_de_Maven_3_Erick_Camacho.pdf");
String password = "Password#1";
byte[] array = CertificateUtils.sign(is, null, password, "Firmado digitalmente", "Por firmar", Boolean.FALSE, Boolean.FALSE, new Rectangle(50, 50, 200, 200), 1, "Firma 2", "2");
is.close();
System.out.println("Tam array "+ array != null ? array.length:0);
FileOutputStream os = new FileOutputStream("C:\\Users\\abenalcazar\\dwhelper\\Downloads\\Tutorial_de_Maven_3_Erick_Camacho.pdf");
os.write(array);
os.flush();
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Throwable e){
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,38 @@
package com.fp.firma.applet;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}

Some files were not shown because too many files have changed in this diff Show More