/** * Prueba la firma de un PDF protegido con contraseña contra modificación. * * @throws Exception en cualquier error */ @SuppressWarnings("static-method") @Test public void testModificationPasswordSignature() throws Exception { Logger.getLogger("es.gob.afirma").setLevel(Level.WARNING); // $NON-NLS-1$ final PrivateKeyEntry pke; final KeyStore ks = KeyStore.getInstance("PKCS12"); // $NON-NLS-1$ ks.load(ClassLoader.getSystemResourceAsStream(CERT_PATH), CERT_PASS.toCharArray()); pke = (PrivateKeyEntry) ks.getEntry(CERT_ALIAS, new KeyStore.PasswordProtection(CERT_PASS.toCharArray())); final AOSigner signer = new AOPDFSigner(); final byte[] testPdf = AOUtil.getDataFromInputStream(ClassLoader.getSystemResourceAsStream(TEST_FILE_PWD_MOD)); Assert.assertTrue( "No se ha reconocido como un PDF", signer.isValidDataFile(testPdf)); // $NON-NLS-1$ final String prueba = "Firma PAdES de PDF con contrasena en SHA512withRSA"; // $NON-NLS-1$ System.out.println(prueba); final Properties extraParams = new Properties(); extraParams.put("headLess", "true"); // $NON-NLS-1$ //$NON-NLS-2$ extraParams.put("userPassword", "1111"); // $NON-NLS-1$ //$NON-NLS-2$ final byte[] result = signer.sign( testPdf, "SHA512withRSA", //$NON-NLS-1$ pke.getPrivateKey(), pke.getCertificateChain(), extraParams); Assert.assertNotNull(prueba, result); final File out = File.createTempFile("TEST-PWD", ".pdf"); // $NON-NLS-1$ //$NON-NLS-2$ final FileOutputStream fos = new FileOutputStream(out); fos.write(result); fos.flush(); fos.close(); System.out.println( "Temporal para comprobacion manual: " + out.getAbsolutePath()); // $NON-NLS-1$ }
/** * Returns the CertificateInfo for the given signing configuration. * * @return the certificate info if it could be loaded. * @throws KeytoolException If the password is wrong. * @throws FileNotFoundException If the store file cannot be found. */ @NonNull public static CertificateInfo getCertificateInfo( @Nullable String storeType, @NonNull File storeFile, @NonNull String storePassword, @NonNull String keyPassword, @NonNull String keyAlias) throws KeytoolException, FileNotFoundException { try { KeyStore keyStore = KeyStore.getInstance(storeType != null ? storeType : KeyStore.getDefaultType()); FileInputStream fis = new FileInputStream(storeFile); keyStore.load(fis, storePassword.toCharArray()); fis.close(); char[] keyPasswordArray = keyPassword.toCharArray(); PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(keyAlias, new KeyStore.PasswordProtection(keyPasswordArray)); if (entry == null) { throw new KeytoolException( String.format( "No key with alias '%1$s' found in keystore %2$s", keyAlias, storeFile.getAbsolutePath())); } return new CertificateInfo(entry.getPrivateKey(), (X509Certificate) entry.getCertificate()); } catch (FileNotFoundException e) { throw e; } catch (Exception e) { throw new KeytoolException( String.format( "Failed to read key %1$s from store \"%2$s\": %3$s", keyAlias, storeFile, e.getMessage()), e); } }
/** * Prueba la firma de un PDF certificado. * * @throws Exception en cualquier error */ @SuppressWarnings("static-method") @Test public void testCertificatedSignature() throws Exception { Logger.getLogger("es.gob.afirma").setLevel(Level.WARNING); // $NON-NLS-1$ final PrivateKeyEntry pke; final KeyStore ks = KeyStore.getInstance("PKCS12"); // $NON-NLS-1$ ks.load(ClassLoader.getSystemResourceAsStream(CERT_PATH), CERT_PASS.toCharArray()); pke = (PrivateKeyEntry) ks.getEntry(CERT_ALIAS, new KeyStore.PasswordProtection(CERT_PASS.toCharArray())); final AOSigner signer = new AOPDFSigner(); final byte[] testPdf = AOUtil.getDataFromInputStream(ClassLoader.getSystemResourceAsStream(TEST_FILES[0])); Assert.assertTrue( "No se ha reconocido como un PDF", signer.isValidDataFile(testPdf)); // $NON-NLS-1$ String prueba = "Firma certificada PAdES de documento PDF indicando la propiedad certificationLevel"; //$NON-NLS-1$ String[] certificationLevels = new String[] { "Firma de autor. No se permite ningun cambio posterior en el documento", //$NON-NLS-1$ "Firma de autor certificada para formularios. Se permite unicamente el relleno posterior de los campos del formulario", //$NON-NLS-1$ "Firma certificada. Se permite unicamente el relleno posterior de los campos del formulario o el anadido de firmas de aprobacion" //$NON-NLS-1$ }; System.out.println(prueba); Properties extraParams = new Properties(); for (int i = 1; i <= certificationLevels.length; i++) { extraParams.put("certificationLevel", Integer.toString(i)); // $NON-NLS-1$ System.out.println(certificationLevels[i - 1]); byte[] result = signer.sign( testPdf, "SHA512withRSA", //$NON-NLS-1$ pke.getPrivateKey(), pke.getCertificateChain(), extraParams); final File tempFile = File.createTempFile("afirmaPDF", ".pdf"); // $NON-NLS-1$ //$NON-NLS-2$ final FileOutputStream fos = new FileOutputStream(tempFile); fos.write(result); fos.close(); // Logger.getLogger("es.gob.afirma").info( //$NON-NLS-1$ // "Fichero temporal para la comprobacion manual del resultado: " + //$NON-NLS-1$ // tempFile.getAbsolutePath()); System.out.println( "Fichero temporal para la comprobacion manual del resultado: " + //$NON-NLS-1$ tempFile.getAbsolutePath()); } }
/** * Prueba la firma de un PDF certificado. * * @throws Exception en cualquier error */ @SuppressWarnings("static-method") @Test public void testCertifiedSignature() throws Exception { Logger.getLogger("es.gob.afirma").setLevel(Level.WARNING); // $NON-NLS-1$ final PrivateKeyEntry pke; final KeyStore ks = KeyStore.getInstance("PKCS12"); // $NON-NLS-1$ ks.load(ClassLoader.getSystemResourceAsStream(CERT_PATH), CERT_PASS.toCharArray()); pke = (PrivateKeyEntry) ks.getEntry(CERT_ALIAS, new KeyStore.PasswordProtection(CERT_PASS.toCharArray())); final AOSigner signer = new AOPDFSigner(); final byte[] testPdf = AOUtil.getDataFromInputStream(ClassLoader.getSystemResourceAsStream(TEST_FILE_CTF)); Assert.assertTrue( "No se ha reconocido como un PDF", signer.isValidDataFile(testPdf)); // $NON-NLS-1$ String prueba = "Firma PAdES de PDF certificado en SHA512withRSA indicando allowSigningCertifiedPdfs=true"; //$NON-NLS-1$ System.out.println(prueba); Properties extraParams = new Properties(); extraParams.put("allowSigningCertifiedPdfs", "true"); // $NON-NLS-1$ //$NON-NLS-2$ byte[] result = signer.sign( testPdf, "SHA512withRSA", //$NON-NLS-1$ pke.getPrivateKey(), pke.getCertificateChain(), extraParams); Assert.assertNotNull(prueba, result); Assert.assertTrue(signer.isSign(result)); prueba = "Firma PAdES de PDF certificado en SHA512withRSA indicando unicamente headLess=true"; //$NON-NLS-1$ System.out.println(prueba); extraParams = new Properties(); extraParams.put("headLess", "true"); // $NON-NLS-1$ //$NON-NLS-2$ boolean failed = false; try { result = signer.sign( testPdf, "SHA512withRSA", //$NON-NLS-1$ pke.getPrivateKey(), pke.getCertificateChain(), extraParams); } catch (final Exception e) { failed = true; } Assert.assertTrue("Deberia haber fallado", failed); // $NON-NLS-1$ prueba = "Firma PAdES de PDF certificado en SHA512withRSA indicando unicamente allowSigningCertifiedPdfs=false"; //$NON-NLS-1$ System.out.println(prueba); extraParams = new Properties(); extraParams.put("allowSigningCertifiedPdfs", "false"); // $NON-NLS-1$ //$NON-NLS-2$ failed = false; try { result = signer.sign( testPdf, "SHA512withRSA", //$NON-NLS-1$ pke.getPrivateKey(), pke.getCertificateChain(), extraParams); } catch (final Exception e) { failed = true; } Assert.assertTrue("Deberia haber fallado", failed); // $NON-NLS-1$ }
/** * Prueba de firma convencional. * * @throws Exception en cualquier error */ @SuppressWarnings("static-method") @Test public void testSignature() throws Exception { Assert.assertEquals( "file.signed.pdf", AOPDFSigner.getSignedName("file.pdf")); // $NON-NLS-1$ //$NON-NLS-2$ Logger.getLogger("es.gob.afirma").setLevel(Level.WARNING); // $NON-NLS-1$ final PrivateKeyEntry pke; final X509Certificate cert; final KeyStore ks = KeyStore.getInstance("PKCS12"); // $NON-NLS-1$ ks.load(ClassLoader.getSystemResourceAsStream(CERT_PATH), CERT_PASS.toCharArray()); pke = (PrivateKeyEntry) ks.getEntry(CERT_ALIAS, new KeyStore.PasswordProtection(CERT_PASS.toCharArray())); cert = (X509Certificate) ks.getCertificate(CERT_ALIAS); final AOSigner signer = new AOPDFSigner(); String prueba; for (final Properties extraParams : PADES_MODES) { for (final String algo : ALGOS) { for (final String file : TEST_FILES) { final byte[] testPdf = AOUtil.getDataFromInputStream(ClassLoader.getSystemResourceAsStream(file)); Assert.assertTrue( "No se ha reconocido como un PDF", signer.isValidDataFile(testPdf)); // $NON-NLS-1$ prueba = "Firma PAdES en modo '" + //$NON-NLS-1$ extraParams.getProperty("mode") + //$NON-NLS-1$ "' con el algoritmo ': " + //$NON-NLS-1$ algo + "' y el fichero '" + //$NON-NLS-1$ file + "'"; //$NON-NLS-1$ System.out.println(prueba); final byte[] result = signer.sign( testPdf, algo, pke.getPrivateKey(), pke.getCertificateChain(), extraParams); Assert.assertNotNull(prueba, result); Assert.assertTrue(signer.isSign(result)); AOTreeModel tree = signer.getSignersStructure(result, false); Assert.assertEquals( "Datos", ((AOTreeNode) tree.getRoot()).getUserObject()); // $NON-NLS-1$ Assert.assertEquals( "ANF Usuario Activo", ((AOTreeNode) tree.getRoot()).getChildAt(0).getUserObject()); // $NON-NLS-1$ tree = signer.getSignersStructure(result, true); Assert.assertEquals( "Datos", ((AOTreeNode) tree.getRoot()).getUserObject()); // $NON-NLS-1$ final AOSimpleSignInfo simpleSignInfo = (AOSimpleSignInfo) ((AOTreeNode) tree.getRoot()).getChildAt(0).getUserObject(); // Assert.assertNotNull(simpleSignInfo.getSigningTime()); Assert.assertEquals(cert, simpleSignInfo.getCerts()[0]); Assert.assertEquals(result, signer.getData(result)); Assert.assertEquals( AOSignConstants.SIGN_FORMAT_PDF, signer.getSignInfo(result).getFormat()); final File saveFile = File.createTempFile(algo, ".pdf"); // $NON-NLS-1$ final OutputStream os = new FileOutputStream(saveFile); os.write(result); os.flush(); os.close(); System.out.println( "Temporal para comprobacion manual: " + saveFile.getAbsolutePath()); // $NON-NLS-1$ } } } }
/** * Prueba de PDF con sello de tiempo contra la TSA de CATCert. * * @throws Exception */ @SuppressWarnings("static-method") @Test @Ignore public void testTimestampedSignature() throws Exception { Logger.getLogger("es.gob.afirma").setLevel(Level.WARNING); // $NON-NLS-1$ final PrivateKeyEntry pke; final KeyStore ks = KeyStore.getInstance("PKCS12"); // $NON-NLS-1$ ks.load(ClassLoader.getSystemResourceAsStream(CERT_PATH), CERT_PASS.toCharArray()); pke = (PrivateKeyEntry) ks.getEntry(CERT_ALIAS, new KeyStore.PasswordProtection(CERT_PASS.toCharArray())); final AOSigner signer = new AOPDFSigner(); final byte[] testPdf = AOUtil.getDataFromInputStream(ClassLoader.getSystemResourceAsStream(TEST_FILES[0])); final String prueba = "Firma PAdES de PDF con sello de tiempo en SHA512withRSA"; // $NON-NLS-1$ System.out.println(prueba); final Properties extraParams = new Properties(); // ********* TSA CATCERT ******************************************************************** // ****************************************************************************************** extraParams.put("tsaURL", CMSTimestamper.CATCERT_TSP); // $NON-NLS-1$ extraParams.put("tsaPolicy", CMSTimestamper.CATCERT_POLICY); // $NON-NLS-1$ extraParams.put("tsaRequireCert", CMSTimestamper.CATCERT_REQUIRECERT); // $NON-NLS-1$ extraParams.put("tsaHashAlgorithm", "SHA1"); // $NON-NLS-1$ //$NON-NLS-2$ // ****************************************************************************************** // ********* FIN TSA CATCERT **************************************************************** // //********** TSA AFIRMA // ******************************************************************** // // //****************************************************************************************** // extraParams.put("tsaURL", "https://10.253.252.184:10318/tsamap/TspHttpServer"); // //$NON-NLS-1$ //$NON-NLS-2$ // //extraParams.put("tsaURL", // "socket://10.253.252.184:318/tsamap/TspHttpServer"/*"http://des-tsafirma.redsara.es:318/tsamap/TspHttpServer"*/); //$NON-NLS-1$ //$NON-NLS-2$ // extraParams.put("tsaPolicy", "1.3.4.6.1.3.4.6"); //$NON-NLS-1$ //$NON-NLS-2$ // extraParams.put("tsaRequireCert", "true"); //$NON-NLS-1$ //$NON-NLS-2$ // extraParams.put("tsaHashAlgorithm", "SHA1"); //$NON-NLS-1$ //$NON-NLS-2$ // extraParams.put("tsaHashAlgorithm", "SHA1"); //$NON-NLS-1$ //$NON-NLS-2$ // extraParams.put("tsaExtensionOid", "1.3.4.6.1.3.4.6"); //$NON-NLS-1$//$NON-NLS-2$ // extraParams.put("tsaExtensionValueBase64", "NOMBRE_APP_AFIRMA_EN_BASE64"); // //$NON-NLS-1$ //$NON-NLS-2$ // extraParams.put("tsaUsr", "USUARIO"); //$NON-NLS-1$ //$NON-NLS-2$ // extraParams.put("tsaPwd", "CONTRASENA"); //$NON-NLS-1$ //$NON-NLS-2$ // // //****************************************************************************************** // //********** FIN TSA AFIRMA // **************************************************************** final byte[] result = signer.sign( testPdf, "SHA512withRSA", //$NON-NLS-1$ pke.getPrivateKey(), pke.getCertificateChain(), extraParams); final File saveFile = File.createTempFile("TSA-", ".pdf"); // $NON-NLS-1$ //$NON-NLS-2$ final OutputStream os = new FileOutputStream(saveFile); os.write(result); os.flush(); os.close(); System.out.println( "Temporal para comprobacion manual: " + saveFile.getAbsolutePath()); // $NON-NLS-1$ Assert.assertNotNull(prueba, result); Assert.assertTrue(signer.isSign(result)); }
private boolean doExport(IProgressMonitor monitor) { try { // if needed, create the keystore and/or key. if (mKeystoreCreationMode || mKeyCreationMode) { final ArrayList<String> output = new ArrayList<String>(); boolean createdStore = KeystoreHelper.createNewStore( mKeystore, null /*storeType*/, mKeystorePassword, mKeyAlias, mKeyPassword, mDName, mValidity, new IKeyGenOutput() { @Override public void err(String message) { output.add(message); } @Override public void out(String message) { output.add(message); } }); if (createdStore == false) { // keystore creation error! displayError(output.toArray(new String[output.size()])); return false; } // keystore is created, now load the private key and certificate. KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream fis = new FileInputStream(mKeystore); keyStore.load(fis, mKeystorePassword.toCharArray()); fis.close(); PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) keyStore.getEntry( mKeyAlias, new KeyStore.PasswordProtection(mKeyPassword.toCharArray())); if (entry != null) { mPrivateKey = entry.getPrivateKey(); mCertificate = (X509Certificate) entry.getCertificate(); } else { // this really shouldn't happen since we now let the user choose the key // from a list read from the store. displayError("Could not find key"); return false; } } // check the private key/certificate again since it may have been created just above. if (mPrivateKey != null && mCertificate != null) { boolean runZipAlign = false; String path = AdtPlugin.getOsAbsoluteZipAlign(); File zipalign = new File(path); runZipAlign = zipalign.isFile(); File apkExportFile = mDestinationFile; if (runZipAlign) { // create a temp file for the original export. apkExportFile = File.createTempFile("androidExport_", ".apk"); } // export the signed apk. ExportHelper.exportReleaseApk(mProject, apkExportFile, mPrivateKey, mCertificate, monitor); // align if we can if (runZipAlign) { String message = zipAlign(path, apkExportFile, mDestinationFile); if (message != null) { displayError(message); return false; } } else { AdtPlugin.displayWarning( "Export Wizard", "The zipalign tool was not found in the SDK.\n\n" + "Please update to the latest SDK and re-export your application\n" + "or run zipalign manually.\n\n" + "Aligning applications allows Android to use application resources\n" + "more efficiently."); } return true; } } catch (Throwable t) { displayError(t); } return false; }