List of usage examples for org.bouncycastle.jce.provider BouncyCastleProvider PROVIDER_NAME
String PROVIDER_NAME
To view the source code for org.bouncycastle.jce.provider BouncyCastleProvider PROVIDER_NAME.
Click Source Link
From source file:org.qipki.crypto.digest.DigesterTest.java
License:Open Source License
@Test public void testWithoutQi4j() throws UnsupportedEncodingException, GeneralSecurityException { Security.addProvider(new BouncyCastleProvider()); testDigester(new DigesterImpl(new DefaultCryptoContext(), new CryptCodexImpl())); Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME); }
From source file:org.qipki.crypto.x509.X509ExtensionsReaderTest.java
License:Open Source License
@AfterClass public static void afterClass() { Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME); }
From source file:org.qipki.crypto.x509.X509GeneratorImpl.java
License:Open Source License
@Override public X509CRL generateX509CRL(X509Certificate caCertificate, PrivateKey caPrivateKey) { try {/*from w ww .j av a 2 s . c o m*/ X509V2CRLGenerator crlGen = new X509V2CRLGenerator(); crlGen.setIssuerDN(caCertificate.getSubjectX500Principal()); crlGen.setThisUpdate(new DateTime().minus(Time.CLOCK_SKEW).toDate()); crlGen.setNextUpdate(new DateTime().minus(Time.CLOCK_SKEW).plusHours(12).toDate()); crlGen.setSignatureAlgorithm(SignatureAlgorithm.SHA256withRSA.jcaString()); crlGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCertificate)); crlGen.addExtension(X509Extensions.CRLNumber, false, new CRLNumber(BigInteger.ONE)); return crlGen.generate(caPrivateKey, BouncyCastleProvider.PROVIDER_NAME); } catch (GeneralSecurityException ex) { throw new CryptoFailure("Unable to generate CRL", ex); } }
From source file:org.qipki.crypto.x509.X509GeneratorImpl.java
License:Open Source License
@Override public X509CRL updateX509CRL(X509Certificate caCertificate, PrivateKey caPrivateKey, X509Certificate revokedCertificate, RevocationReason reason, X509CRL previousCRL, BigInteger lastCRLNumber) { try {/*from w ww. j a va2 s. c o m*/ X509V2CRLGenerator crlGen = new X509V2CRLGenerator(); crlGen.setIssuerDN(caCertificate.getSubjectX500Principal()); DateTime skewedNow = new DateTime().minus(Time.CLOCK_SKEW); crlGen.setThisUpdate(skewedNow.toDate()); crlGen.setNextUpdate(skewedNow.plusHours(12).toDate()); crlGen.setSignatureAlgorithm(SignatureAlgorithm.SHA256withRSA.jcaString()); crlGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCertificate)); crlGen.addExtension(X509Extensions.CRLNumber, false, new CRLNumber(lastCRLNumber)); crlGen.addCRL(previousCRL); crlGen.addCRLEntry(revokedCertificate.getSerialNumber(), skewedNow.toDate(), reason.reason()); return crlGen.generate(caPrivateKey, BouncyCastleProvider.PROVIDER_NAME); } catch (GeneralSecurityException ex) { throw new CryptoFailure("Unable to update CRL", ex); } }
From source file:org.sinekartads.core.pdf.PDFTools.java
License:Open Source License
public static FinalizedSignature<SignatureType.SignCategory, SignDisposition.PDF, SecurityLevel.VerifyResult, PDFSignatureInfo> sign( SignedSignature<SignatureType.SignCategory, SignDisposition.PDF, SecurityLevel.VerifyResult, PDFSignatureInfo> signedSignature, // X509Certificate certificate, InputStream is, OutputStream os) throws SignatureException { //// signAndMark(doc, certificate, is, os, null, null, null, null, null); // signAndMark(signatureInfo, certificate, is, os, null, null, null); // }// w ww . j av a 2 s .com // // public static void signAndMark(PDFSignatureInfo doc, // X509Certificate certificate, InputStream is, OutputStream os, // String tsaUrl, String tsaUser, String tsaPassword) { //// signAndMark(doc, certificate, is, os, tsaUrl, tsaUser, tsaPassword, null, null); //// } //// //// public static void signAndMark(DigitalSignatureDocument doc, //// X509Certificate certificate, InputStream is, OutputStream os, //// String tsaUrl, String tsaUser, String tsaPassword, Collection<CrlClient> crlList, OcspClient ocspClient) { try { PDFSignatureInfo signature = (PDFSignatureInfo) signedSignature; TSAClient tsaClient = null; TsRequestInfo tsRequest = signature.getTsRequest(); if (tsRequest != null && StringUtils.isNotBlank(tsRequest.getTsUrl())) { tsaClient = new TSAClientBouncyCastle(tsRequest.getTsUrl(), tsRequest.getTsUsername(), tsRequest.getTsPassword()); } // if (tsaUrl!=null) { // tsaClient = new TSAClientBouncyCastle(tsaUrl, tsaUser, tsaPassword); // } int estimatedSize = 0; CryptoStandard sigtype = CryptoStandard.CMS; // creo il reader del pdf PdfReader reader = new PdfReader(is); // creo lo stamper (se il pdf e' gia' firmato, controfirma, // altrimenti firma PdfStamper stamper = null; if (isPdfSigned(reader)) { if (tracer.isDebugEnabled()) tracer.debug("document already signed, i will apply another sign"); stamper = PdfStamper.createSignature(reader, os, '\0', null, true); } else { if (tracer.isDebugEnabled()) tracer.debug("document never signed before, this is first"); stamper = PdfStamper.createSignature(reader, os, '\0'); } // questo e' il certificato su cui lavorare Certificate[] chain = signature.getRawX509Certificates(); // Certificate[] chain = new Certificate[1]; // chain[0] = certificate; // creo la signature apparence PdfSignatureAppearance sap = stamper.getSignatureAppearance(); ExternalDigest externalDigest = new BouncyCastleDigest(); // inizio codice copiato da MakeSignature // Collection<byte[]> crlBytes = null; // int i = 0; // while (crlBytes == null && i < chain.length) // crlBytes = MakeSignature.processCrl(chain[i++], crlList); if (estimatedSize == 0) { estimatedSize = 8192; // if (crlBytes != null) { // for (byte[] element : crlBytes) { // estimatedSize += element.length + 10; // } // } // if (ocspClient != null) estimatedSize += 4192; // if (tsaClient != null) estimatedSize += 4192; } sap.setCertificate(chain[0]); sap.setReason(signature.getReason()); sap.setLocation(signature.getLocation()); Calendar cal = Calendar.getInstance(); cal.setTime(signature.getSigningTime()); sap.setSignDate(cal); sap.getStamper().setUnicodeModDate(signature.getUnicodeModDate()); sap.getStamper().setFileId(signature.getFileId()); PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED); dic.setReason(sap.getReason()); dic.setLocation(sap.getLocation()); dic.setContact(sap.getContact()); dic.setDate(new PdfDate(sap.getSignDate())); // time-stamp will over-rule this sap.setCryptoDictionary(dic); HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer>(); exc.put(PdfName.CONTENTS, new Integer(estimatedSize * 2 + 2)); sap.preClose(exc); String hashAlgorithm = signature.getDigestAlgorithm().getName(); PdfPKCS7 sgn = new PdfPKCS7(null, chain, hashAlgorithm, BouncyCastleProvider.PROVIDER_NAME, externalDigest, false); InputStream data = sap.getRangeStream(); byte hash[] = DigestAlgorithms.digest(data, externalDigest.getMessageDigest(hashAlgorithm)); // byte[] ocsp = null; // if (chain.length >= 2 && ocspClient != null) { // ocsp = ocspClient.getEncoded((X509Certificate) chain[0], (X509Certificate) chain[1], null); // } sgn.setExternalDigest(signature.getDigitalSignature(), null, "RSA"); // byte[] encodedSig = sgn.getEncodedPKCS7(hash, _getSignDate(doc.getSignDate()), tsaClient, ocsp, crlBytes, sigtype); byte[] encodedSig = sgn.getEncodedPKCS7(hash, cal, tsaClient, null, null, sigtype); if (estimatedSize + 2 < encodedSig.length) throw new IOException("Not enough space"); ASN1EncodableVector extraDataVectorEncoding = new ASN1EncodableVector(); // extraDataVectorEncoding.add(new DERObjectIdentifier("1.2.840.114283")); // encoding attribute extraDataVectorEncoding.add(new DERGeneralString("115.105.110.101.107.97.114.116.97")); // applico la firma al PDF byte[] extraDataVectorEncodingBytes = new DERSequence(new DERSequence(extraDataVectorEncoding)) .getEncoded(); byte[] paddedSig = new byte[estimatedSize]; System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length); System.arraycopy(extraDataVectorEncodingBytes, 0, paddedSig, encodedSig.length, extraDataVectorEncodingBytes.length); // encoding attribute PdfDictionary dic2 = new PdfDictionary(); dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true)); sap.close(dic2); // this should be already done, but ... // closing streams try { is.close(); } catch (IOException e) { tracer.error("error on input stream", e); } try { os.flush(); } catch (IOException e) { tracer.error("error on output stream", e); } try { os.close(); } catch (IOException e) { tracer.error("error on output stream", e); } return signature.finalizeSignature(); // } catch (MarkFailedException e) { // throw e; } catch (Exception e) { tracer.error("Unable to sign PDF.", e); throw new SignatureException("Unable to sign PDF.", e); } }
From source file:org.sinekartads.core.pdf.PDFTools.java
License:Open Source License
public static DigestSignature<SignatureType.SignCategory, SignDisposition.PDF, SecurityLevel.VerifyResult, PDFSignatureInfo> calculateFingerPrint( ChainSignature<SignatureType.SignCategory, SignDisposition.PDF, SecurityLevel.VerifyResult, PDFSignatureInfo> chainSignature, // X509Certificate certificate, InputStream is) throws SignatureException { // calculateFingerPrint(doc, certificate, is, null, null, null, null, null); // }//from w w w .j a va 2 s . com // // public static void calculateFingerPrint(DigitalSignatureDocument doc, // X509Certificate certificate, InputStream is, Collection<CrlClient> crlList, OcspClient ocspClient, String tsaUrl, String tsaUser, String tsaPassword) { try { // TSAClient tsaClient=null; // // if (tsaUrl!=null) { // tsaClient = new SinekartaTSAClient(tsaUrl, tsaUser, tsaPassword); // } // int estimatedSize = 0; CryptoStandard sigtype = CryptoStandard.CMS; // FIXME qui c'era CMS PDFSignatureInfo signature = (PDFSignatureInfo) chainSignature; // creo il reader del pdf PdfReader reader = new PdfReader(is); // creo lo stamper (se il pdf e' gia' firmato, controfirma, // altrimenti firma PdfStamper stamper = null; if (isPdfSigned(reader)) { if (tracer.isDebugEnabled()) tracer.debug("calculating finger print for document already signed"); stamper = PdfStamper.createSignature(reader, null, '\0', null, true); } else { if (tracer.isDebugEnabled()) tracer.debug("calculating finger print for document never signed before"); stamper = PdfStamper.createSignature(reader, null, '\0'); } // questo e' il certificato su cui lavorare Certificate[] chain = signature.getRawX509Certificates(); // Certificate[] chain = new Certificate[1]; // chain[0] = certificate; // creo la signature apparence PdfSignatureAppearance sap = stamper.getSignatureAppearance(); ExternalDigest externalDigest = new BouncyCastleDigest(); // inizio codice copiato da MakeSignature // Collection<byte[]> crlBytes = null; // int i = 0; // while (crlBytes == null && i < chain.length) // crlBytes = MakeSignature.processCrl(chain[i++], crlList); if (estimatedSize == 0) { estimatedSize = 8192; // if (crlBytes != null) { // for (byte[] element : crlBytes) { // estimatedSize += element.length + 10; // } // } // if (ocspClient != null) estimatedSize += 4192; // if (tsaClient != null) estimatedSize += 4192; } Calendar now = Calendar.getInstance(); PdfDate date = new PdfDate(now); sap.setSignDate(now); signature.setSigningTime(now.getTime()); signature.setUnicodeModDate(date.toUnicodeString()); sap.setCertificate(chain[0]); sap.setReason(signature.getReason()); sap.setLocation(signature.getLocation()); PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED); dic.setReason(sap.getReason()); dic.setLocation(sap.getLocation()); dic.setContact(sap.getContact()); dic.setDate(date); // time-stamp will over-rule this sap.setCryptoDictionary(dic); HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer>(); exc.put(PdfName.CONTENTS, new Integer(estimatedSize * 2 + 2)); sap.preClose(exc); String hashAlgorithm = signature.getDigestAlgorithm().getName(); PdfPKCS7 sgn = new PdfPKCS7(null, chain, hashAlgorithm, BouncyCastleProvider.PROVIDER_NAME, externalDigest, false); // String hashAlgorithm = Constants.SHA256; // PdfPKCS7 sgn = new PdfPKCS7(null, chain, hashAlgorithm, Constants.BC, externalDigest, false); InputStream data = sap.getRangeStream(); byte hash[] = DigestAlgorithms.digest(data, externalDigest.getMessageDigest(hashAlgorithm)); // byte[] ocsp = null; // if (chain.length >= 2 && ocspClient != null) { // ocsp = ocspClient.getEncoded((X509Certificate) chain[0], (X509Certificate) chain[1], null); // } // byte[] authenticatedAttributeBytes = sgn.getAuthenticatedAttributeBytes(hash, now, ocsp, crlBytes, sigtype); byte[] authenticatedAttributeBytes = sgn.getAuthenticatedAttributeBytes(hash, now, null, null, sigtype); // calcolo dell'impronta MessageDigest digester = MessageDigest.getInstance(signature.getDigestAlgorithm().getName()); byte[] fingerPrint = digester.digest(authenticatedAttributeBytes); // byte[] fingerPrint = Util.digest256(authenticatedAttributeBytes); signature.setAuthenticatedAttributeBytes(authenticatedAttributeBytes); signature.setFileId(sap.getStamper().getFileId()); // signature.setFileIDByteContent(TextUtil.byteToHex(sap.getStamper().getFileID().getBytes())); signature.setUnicodeModDate(sap.getStamper().getUnicodeModDate()); // signature.setModDateUnicodeString(sap.getStamper().getModDate().toUnicodeString()); signature.setSigningTime(now.getTime()); // SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSSZ"); // signature.setSignDate(sdf.format(now.getTime())); // this should be already done, but ... // closing streams try { is.close(); } catch (IOException e) { tracer.error("error on input stream", e); } return signature.toDigestSignature(DigestInfo.getInstance(signature.getDigestAlgorithm(), fingerPrint)); } catch (Exception e) { tracer.error("Unable to calculate finger print of PDF.", e); // throw new PDFException("Unable calculate finger print of PDF.", e); throw new SignatureException("Unable calculate finger print of PDF.", e); } }
From source file:org.sinekartads.integration.cms.SignCMSonAlfresco.java
License:Open Source License
@Test public void test() throws Exception { if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { Security.addProvider(new BouncyCastleProvider()); }//w w w . ja va 2 s . c o m SignNOApplet applet = new SignNOApplet(); try { // Main options boolean applyMark = true; boolean useFakeSmartCard = true; String driver; String scPin; if (useFakeSmartCard) { driver = "fake"; scPin = "123"; } else { driver = "libbit4ipki.so"; scPin = "18071971"; } // Test products String[] aliases; String alias; X509Certificate certificate; X509Certificate[] certificateChain; byte[] fingerPrint; byte[] digitalSignature; // Communication unities DocumentDTO[] documents; String jsonResp; SkdsDocumentDetailsResponse detailsResp; SkdsPreSignResponse preSignResp; SkdsPostSignResponse postSignResp; AppletResponseDTO appletResponse; SignatureDTO emptySignatureDTO; SignatureDTO chainSignatureDTO; SignatureDTO digestSignatureDTO; SignatureDTO signedSignatureDTO; SignatureDTO finalizedSignatureDTO; VerifyDTO verifyDTO; // Init the applet try { AppletRequestDTO req = new AppletRequestDTO(); req.setDriver(driver); appletResponse = applet.selectDriver(req); } catch (Exception e) { tracer.error("error during the applet initialization", e); throw e; } // Login with the smartCard try { AppletRequestDTO req = new AppletRequestDTO(); req.setDriver(driver); req.setPin(scPin); appletResponse = applet.login(req); aliases = (String[]) JSONUtils.deserializeJSON(String[].class, extractJSON(appletResponse)); } catch (Exception e) { tracer.error("error during the applet login", e); throw e; } // Choose the signing alias StringBuilder buf = new StringBuilder(); for (String a : aliases) { buf.append(a).append(" "); } alias = aliases[0]; tracer.info(String.format("available aliases: %s", buf)); tracer.info(String.format("signing alias: %s", alias)); // Load the certificate chain from the applet try { AppletRequestDTO req = new AppletRequestDTO(); req.setDriver(driver); req.setPin(scPin); req.setAlias(alias); appletResponse = applet.selectCertificate(req); certificate = (X509Certificate) X509Utils.rawX509CertificateFromHex(extractJSON(appletResponse)); tracer.info(String.format("certificate: %s", certificate)); certificateChain = new X509Certificate[] { certificate }; } catch (Exception e) { tracer.error("error during the certificate selection", e); throw e; } // FindRefByName String sourceRef = null; try { SkdsFindRefByNameRequest req = new SkdsFindRefByNameRequest(); req.setName(SOURCE_NAME); SkdsFindRefByNameResponse findResp = postJsonRequest(req, SkdsFindRefByNameResponse.class); if (ResultCode.valueOf(findResp.getResultCode()) == ResultCode.SUCCESS) { sourceRef = findResp.getNodeRef(); } else { throw new Exception(findResp.getMessage()); } } catch (Exception e) { tracer.error("error during the pre sign phase", e); throw e; } // DocumentDetails try { // String sourceRef = getNodeRefId("pippo.txt"); SkdsDocumentDetailsRequest req = new SkdsDocumentDetailsRequest(); req.setNodeRefs(new String[] { sourceRef }); // req.setNodeRefs ( new String[] {SOURCE_REF} ); detailsResp = postJsonRequest(req, SkdsDocumentDetailsResponse.class); if (ResultCode.valueOf(detailsResp.getResultCode()) == ResultCode.SUCCESS) { documents = detailsResp.documentsFromBase64(); } else { throw new Exception(detailsResp.getMessage()); } String fileName = documents[0].getBaseDocument().getFileName(); if (applyMark) { documents[0].setDestName(fileName + ".p7m.tsd"); } else { documents[0].setDestName(fileName + ".p7m"); } } catch (Exception e) { tracer.error("error during the pre sign phase", e); throw e; } // empty signature - initialized with the SHA256withRSA and RSA algorithms emptySignatureDTO = new SignatureDTO(); emptySignatureDTO.setSignAlgorithm(conf.getSignatureAlgorithm().getName()); emptySignatureDTO.setDigestAlgorithm(conf.getDigestAlgorithm().getName()); emptySignatureDTO.signCategoryToString(SignCategory.CMS); // Add to the empty signature the timeStamp request if needed TimeStampRequestDTO tsRequestDTO = new TimeStampRequestDTO(); if (applyMark) { tsRequestDTO.timestampDispositionToString(SignDisposition.TimeStamp.ENVELOPING); tsRequestDTO.messageImprintAlgorithmToString(DigestAlgorithm.SHA256); tsRequestDTO.nounceToString(BigInteger.TEN); tsRequestDTO.setTsUrl("http://ca.signfiles.com/TSAServer.aspx"); } emptySignatureDTO.setTimeStampRequest(tsRequestDTO); // chain signature - contains the certificate chain chainSignatureDTO = TemplateUtils.Instantiation.clone(emptySignatureDTO); chainSignatureDTO.certificateChainToHex(certificateChain); documents[0].setSignatures(new SignatureDTO[] { chainSignatureDTO }); // PreSign phase - join the content with the certificate chain and evaluate the digest try { SkdsPreSignRequest req = new SkdsPreSignRequest(); req.documentsToBase64(documents); preSignResp = postJsonRequest(req, SkdsPreSignResponse.class); if (ResultCode.valueOf(preSignResp.getResultCode()) == ResultCode.SUCCESS) { documents = preSignResp.documentsFromBase64(); digestSignatureDTO = documents[0].getSignatures()[0]; } else { throw new Exception(preSignResp.getMessage()); } } catch (Exception e) { tracer.error("error during the pre sign phase", e); throw e; } // signed signature - sign the digest with the smartCard to obtain the digitalSignature try { fingerPrint = digestSignatureDTO.getDigest().fingerPrintFromHex(); tracer.info(String.format("fingerPrint: %s", HexUtils.encodeHex(fingerPrint))); AppletRequestDTO req = new AppletRequestDTO(); req.setDriver(driver); req.setPin(scPin); req.setAlias(alias); req.setHexDigest(HexUtils.encodeHex(fingerPrint)); appletResponse = applet.signDigest(req); digitalSignature = HexUtils.decodeHex((String) extractJSON(appletResponse)); tracer.info(String.format("digitalSignature: %s", HexUtils.encodeHex(digitalSignature))); signedSignatureDTO = TemplateUtils.Instantiation.clone(digestSignatureDTO); signedSignatureDTO.digitalSignatureToHex(digitalSignature); documents[0].getSignatures()[0] = signedSignatureDTO; } catch (Exception e) { tracer.error("error during the digital signature evaluation", e); throw e; } // PostSign phase - add the digitalSignature to the envelope and store the result into the JCLResultDTO try { SkdsPostSignRequest req = new SkdsPostSignRequest(); req.documentsToBase64(documents); postSignResp = postJsonRequest(req, SkdsPostSignResponse.class); if (ResultCode.valueOf(postSignResp.getResultCode()) == ResultCode.SUCCESS) { documents = postSignResp.documentsFromBase64(); finalizedSignatureDTO = documents[0].getSignatures()[0]; } else { throw new Exception(postSignResp.getMessage()); } } catch (Exception e) { tracer.error("error during the envelope generation", e); throw e; } // // Verify phase - load the envelope content and verify the nested signature // try { // jsonResp = signatureService.verify ( envelopeHex, null, null, VerifyResult.VALID.name() ); // verifyDTO = extractResult ( VerifyDTO.class, jsonResp ); // } catch(Exception e) { // tracer.error("error during the envelope verification", e); // throw e; // } // // // finalized signature - enveloped signed and eventually marked, not modifiable anymore // try { // verifyResult = (VerifyInfo) converter.toVerifyInfo( verifyDTO ); // } catch(Exception e) { // tracer.error("unable to obtain the verifyInfo from the DTO", e); // throw e; // } // // try { // for(VerifiedSignature < ?, ?, VerifyResult, ?> verifiedSignature : verifyResult.getSignatures() ) { // tracer.info(String.format ( "signature validity: %s", verifiedSignature.getVerifyResult().name() )); // tracer.info(String.format ( "signature type: %s", verifiedSignature.getSignType().name() )); // tracer.info(String.format ( "disposition: %s", verifiedSignature.getDisposition().name() )); // tracer.info(String.format ( "digest algorithm: %s", verifiedSignature.getDigest().getAlgorithm().name() )); // tracer.info(String.format ( "finger print: %s", HexUtils.encodeHex(verifiedSignature.getDigest().getFingerPrint()) )); // tracer.info(String.format ( "counter signature: %s", verifiedSignature.isCounterSignature() )); // tracer.info(String.format ( "signature algorithm: %s", verifiedSignature.getSignAlgorithm().name() )); // tracer.info(String.format ( "digital signature: %s", HexUtils.encodeHex(verifiedSignature.getDigitalSignature()) )); // tracer.info(String.format ( "reason: %s", verifiedSignature.getReason() )); // tracer.info(String.format ( "signing location: %s", verifiedSignature.getLocation() )); // tracer.info(String.format ( "signing time: %s", formatDate(verifiedSignature.getSigningTime()) )); // tracer.info(String.format ( "\n ")); // tracer.info(String.format ( "signing certificate chain: ")); // for ( X509Certificate cert : verifiedSignature.getRawX509Certificates() ) { // showCertificate(cert); // } // if ( verifiedSignature.getTimeStamps() != null ) { // tracer.info(String.format ( "\n ")); // tracer.info(String.format ( "timestamps: ")); // for ( TimeStampInfo mark : verifiedSignature.getTimeStamps() ) { // tracer.info(String.format ( "timestamp validity: %s", mark.getVerifyResult().name() )); // tracer.info(String.format ( "timestamp authority: %s", mark.getTsaName() )); // tracer.info(String.format ( "timestamp authority: %s", mark.getTsaName() )); // tracer.info(String.format ( "message imprint alg: %s", mark.getMessageInprintInfo().getAlgorithm().name() )); // tracer.info(String.format ( "message imprint: %s", HexUtils.encodeHex(mark.getMessageInprintInfo().getFingerPrint()) )); // tracer.info(String.format ( "digest algorithm: %s", mark.getDigestAlgorithm().name() )); // tracer.info(String.format ( "digital signature: %s", HexUtils.encodeHex(mark.getDigitalSignature()) )); // tracer.info(String.format ( "signature algorithm: %s", mark.getSignAlgorithm().name() )); // tracer.info(String.format ( "timestamp certificate: ")); // for ( X509Certificate cert : mark.getRawX509Certificates() ) { // showCertificate(cert); // } // } // } // } // } catch(Exception e) { // tracer.error("unable to print the verify results", e); // throw e; // } // } finally { applet.close(); } }
From source file:org.sinekartads.integration.pdf.SignPDFonAlfresco.java
License:Open Source License
@Test public void test() throws Exception { if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { Security.addProvider(new BouncyCastleProvider()); }/* www . ja va 2 s. c om*/ SignNOApplet applet = new SignNOApplet(); try { // Main options boolean applyMark = false; boolean useFakeSmartCard = false; String driver; String scPin; if (useFakeSmartCard) { driver = "fake"; scPin = "123"; } else { driver = "libbit4ipki.so"; scPin = "18071971"; } // Test products String[] aliases; String alias; X509Certificate certificate; X509Certificate[] certificateChain; byte[] fingerPrint; byte[] digitalSignature; // Communication unities DocumentDTO[] documents; String jsonResp; SkdsDocumentDetailsResponse detailsResp; SkdsPreSignResponse preSignResp; SkdsPostSignResponse postSignResp; AppletResponseDTO appletResponse; SignatureDTO emptySignatureDTO; SignatureDTO chainSignatureDTO; SignatureDTO digestSignatureDTO; SignatureDTO signedSignatureDTO; SignatureDTO finalizedSignatureDTO; VerifyDTO verifyDTO; // Init the applet try { AppletRequestDTO req = new AppletRequestDTO(); req.setDriver(driver); appletResponse = applet.selectDriver(req); } catch (Exception e) { tracer.error("error during the applet initialization", e); throw e; } // Login with the smartCard try { AppletRequestDTO req = new AppletRequestDTO(); req.setDriver(driver); req.setPin(scPin); appletResponse = applet.login(req); aliases = (String[]) JSONUtils.deserializeJSON(String[].class, extractJSON(appletResponse)); } catch (Exception e) { tracer.error("error during the applet login", e); throw e; } // Choose the signing alias StringBuilder buf = new StringBuilder(); for (String a : aliases) { buf.append(a).append(" "); } alias = aliases[0]; tracer.info(String.format("available aliases: %s", buf)); tracer.info(String.format("signing alias: %s", alias)); // Load the certificate chain from the applet try { AppletRequestDTO req = new AppletRequestDTO(); req.setDriver(driver); req.setPin(scPin); req.setAlias(alias); appletResponse = applet.selectCertificate(req); certificate = (X509Certificate) X509Utils.rawX509CertificateFromHex(extractJSON(appletResponse)); tracer.info(String.format("certificate: %s", certificate)); certificateChain = new X509Certificate[] { certificate }; } catch (Exception e) { tracer.error("error during the certificate selection", e); throw e; } // FindRefByName String sourceRef = null; try { SkdsFindRefByNameRequest req = new SkdsFindRefByNameRequest(); req.setName(SOURCE_NAME); SkdsFindRefByNameResponse findResp = postJsonRequest(req, SkdsFindRefByNameResponse.class); if (ResultCode.valueOf(findResp.getResultCode()) == ResultCode.SUCCESS) { sourceRef = findResp.getNodeRef(); } else { throw new Exception(findResp.getMessage()); } } catch (Exception e) { tracer.error("error during the pre sign phase", e); throw e; } // DocumentDetails try { SkdsDocumentDetailsRequest req = new SkdsDocumentDetailsRequest(); req.setNodeRefs(new String[] { sourceRef }); detailsResp = postJsonRequest(req, SkdsDocumentDetailsResponse.class); if (ResultCode.valueOf(detailsResp.getResultCode()) == ResultCode.SUCCESS) { documents = detailsResp.documentsFromBase64(); } else { throw new Exception(detailsResp.getMessage()); } Assert.isTrue(StringUtils.equals(documents[0].getBaseDocument().getMimetype(), "application/pdf")); String baseName = FilenameUtils.getBaseName(documents[0].getBaseDocument().getFileName()); if (applyMark) { documents[0].setDestName(baseName + "_mrk.pdf"); } else { documents[0].setDestName(baseName + "_sgn.pdf"); } } catch (Exception e) { tracer.error("error during the pre sign phase", e); throw e; } // empty signature - initialized with the SHA256withRSA and RSA algorithms emptySignatureDTO = new SignatureDTO(); emptySignatureDTO.setSignAlgorithm(conf.getSignatureAlgorithm().getName()); emptySignatureDTO.setDigestAlgorithm(conf.getDigestAlgorithm().getName()); emptySignatureDTO.signCategoryToString(SignCategory.PDF); emptySignatureDTO.setPdfSignName("Signature"); emptySignatureDTO.setPdfRevision("1"); emptySignatureDTO.pdfCoversWholeDocumentToString(true); // Add to the empty signature the timeStamp request if needed TimeStampRequestDTO tsRequestDTO = new TimeStampRequestDTO(); if (applyMark) { tsRequestDTO.timestampDispositionToString(SignDisposition.TimeStamp.ENVELOPING); tsRequestDTO.messageImprintAlgorithmToString(DigestAlgorithm.SHA256); tsRequestDTO.nounceToString(BigInteger.TEN); tsRequestDTO.setTsUrl("http://ca.signfiles.com/TSAServer.aspx"); } emptySignatureDTO.setTimeStampRequest(tsRequestDTO); // chain signature - contains the certificate chain chainSignatureDTO = TemplateUtils.Instantiation.clone(emptySignatureDTO); chainSignatureDTO.certificateChainToHex(certificateChain); documents[0].setSignatures(new SignatureDTO[] { chainSignatureDTO }); // PreSign phase - join the content with the certificate chain and evaluate the digest try { SkdsPreSignRequest req = new SkdsPreSignRequest(); req.documentsToBase64(documents); preSignResp = postJsonRequest(req, SkdsPreSignResponse.class); if (ResultCode.valueOf(preSignResp.getResultCode()) == ResultCode.SUCCESS) { documents = preSignResp.documentsFromBase64(); digestSignatureDTO = documents[0].getSignatures()[0]; } else { throw new Exception(preSignResp.getMessage()); } } catch (Exception e) { tracer.error("error during the pre sign phase", e); throw e; } // signed signature - sign the digest with the smartCard to obtain the digitalSignature try { fingerPrint = digestSignatureDTO.getDigest().fingerPrintFromHex(); tracer.info(String.format("fingerPrint: %s", HexUtils.encodeHex(fingerPrint))); AppletRequestDTO req = new AppletRequestDTO(); req.setDriver(driver); req.setPin(scPin); req.setAlias(alias); req.setHexDigest(HexUtils.encodeHex(fingerPrint)); appletResponse = applet.signDigest(req); digitalSignature = HexUtils.decodeHex((String) extractJSON(appletResponse)); tracer.info(String.format("digitalSignature: %s", HexUtils.encodeHex(digitalSignature))); signedSignatureDTO = TemplateUtils.Instantiation.clone(digestSignatureDTO); signedSignatureDTO.digitalSignatureToHex(digitalSignature); documents[0].getSignatures()[0] = signedSignatureDTO; } catch (Exception e) { tracer.error("error during the digital signature evaluation", e); throw e; } // PostSign phase - add the digitalSignature to the envelope and store the result into the JCLResultDTO try { SkdsPostSignRequest req = new SkdsPostSignRequest(); req.documentsToBase64(documents); postSignResp = postJsonRequest(req, SkdsPostSignResponse.class); if (ResultCode.valueOf(postSignResp.getResultCode()) == ResultCode.SUCCESS) { documents = postSignResp.documentsFromBase64(); finalizedSignatureDTO = documents[0].getSignatures()[0]; } else { throw new Exception(postSignResp.getMessage()); } } catch (Exception e) { tracer.error("error during the envelope generation", e); throw e; } // // Verify phase - load the envelope content and verify the nested signature // try { // jsonResp = signatureService.verify ( envelopeHex, null, null, VerifyResult.VALID.name() ); // verifyDTO = extractResult ( VerifyDTO.class, jsonResp ); // } catch(Exception e) { // tracer.error("error during the envelope verification", e); // throw e; // } // // // finalized signature - enveloped signed and eventually marked, not modifiable anymore // try { // verifyResult = (VerifyInfo) converter.toVerifyInfo( verifyDTO ); // } catch(Exception e) { // tracer.error("unable to obtain the verifyInfo from the DTO", e); // throw e; // } // // try { // for(VerifiedSignature < ?, ?, VerifyResult, ?> verifiedSignature : verifyResult.getSignatures() ) { // tracer.info(String.format ( "signature validity: %s", verifiedSignature.getVerifyResult().name() )); // tracer.info(String.format ( "signature type: %s", verifiedSignature.getSignType().name() )); // tracer.info(String.format ( "disposition: %s", verifiedSignature.getDisposition().name() )); // tracer.info(String.format ( "digest algorithm: %s", verifiedSignature.getDigest().getAlgorithm().name() )); // tracer.info(String.format ( "finger print: %s", HexUtils.encodeHex(verifiedSignature.getDigest().getFingerPrint()) )); // tracer.info(String.format ( "counter signature: %s", verifiedSignature.isCounterSignature() )); // tracer.info(String.format ( "signature algorithm: %s", verifiedSignature.getSignAlgorithm().name() )); // tracer.info(String.format ( "digital signature: %s", HexUtils.encodeHex(verifiedSignature.getDigitalSignature()) )); // tracer.info(String.format ( "reason: %s", verifiedSignature.getReason() )); // tracer.info(String.format ( "signing location: %s", verifiedSignature.getLocation() )); // tracer.info(String.format ( "signing time: %s", formatDate(verifiedSignature.getSigningTime()) )); // tracer.info(String.format ( "\n ")); // tracer.info(String.format ( "signing certificate chain: ")); // for ( X509Certificate cert : verifiedSignature.getRawX509Certificates() ) { // showCertificate(cert); // } // if ( verifiedSignature.getTimeStamps() != null ) { // tracer.info(String.format ( "\n ")); // tracer.info(String.format ( "timestamps: ")); // for ( TimeStampInfo mark : verifiedSignature.getTimeStamps() ) { // tracer.info(String.format ( "timestamp validity: %s", mark.getVerifyResult().name() )); // tracer.info(String.format ( "timestamp authority: %s", mark.getTsaName() )); // tracer.info(String.format ( "timestamp authority: %s", mark.getTsaName() )); // tracer.info(String.format ( "message imprint alg: %s", mark.getMessageInprintInfo().getAlgorithm().name() )); // tracer.info(String.format ( "message imprint: %s", HexUtils.encodeHex(mark.getMessageInprintInfo().getFingerPrint()) )); // tracer.info(String.format ( "digest algorithm: %s", mark.getDigestAlgorithm().name() )); // tracer.info(String.format ( "digital signature: %s", HexUtils.encodeHex(mark.getDigitalSignature()) )); // tracer.info(String.format ( "signature algorithm: %s", mark.getSignAlgorithm().name() )); // tracer.info(String.format ( "timestamp certificate: ")); // for ( X509Certificate cert : mark.getRawX509Certificates() ) { // showCertificate(cert); // } // } // } // } // } catch(Exception e) { // tracer.error("unable to print the verify results", e); // throw e; // } } finally { applet.close(); } }
From source file:org.sinekartads.integration.xml.SignXMLonAlfresco.java
License:Open Source License
@Test public void test() throws Exception { if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { Security.addProvider(new BouncyCastleProvider()); }/*w w w . j av a 2s . co m*/ SignNOApplet applet = new SignNOApplet(); try { // Main options boolean applyMark = false; boolean useFakeSmartCard = false; String driver; String scPin; if (useFakeSmartCard) { driver = "fake"; scPin = "123"; } else { driver = "libbit4ipki.so"; scPin = "18071971"; } // Test products String[] aliases; String alias; X509Certificate certificate; X509Certificate[] certificateChain; byte[] fingerPrint; byte[] digitalSignature; // Communication unities DocumentDTO[] documents; String jsonResp; SkdsDocumentDetailsResponse detailsResp; SkdsPreSignResponse preSignResp; SkdsPostSignResponse postSignResp; AppletResponseDTO appletResponse; SignatureDTO emptySignatureDTO; SignatureDTO chainSignatureDTO; SignatureDTO digestSignatureDTO; SignatureDTO signedSignatureDTO; SignatureDTO finalizedSignatureDTO; VerifyDTO verifyDTO; // Init the applet try { AppletRequestDTO req = new AppletRequestDTO(); req.setDriver(driver); appletResponse = applet.selectDriver(req); } catch (Exception e) { tracer.error("error during the applet initialization", e); throw e; } // Login with the smartCard try { AppletRequestDTO req = new AppletRequestDTO(); req.setDriver(driver); req.setPin(scPin); appletResponse = applet.login(req); aliases = (String[]) JSONUtils.deserializeJSON(String[].class, extractJSON(appletResponse)); } catch (Exception e) { tracer.error("error during the applet login", e); throw e; } // Choose the signing alias StringBuilder buf = new StringBuilder(); for (String a : aliases) { buf.append(a).append(" "); } alias = aliases[0]; tracer.info(String.format("available aliases: %s", buf)); tracer.info(String.format("signing alias: %s", alias)); // Load the certificate chain from the applet try { AppletRequestDTO req = new AppletRequestDTO(); req.setDriver(driver); req.setPin(scPin); req.setAlias(alias); appletResponse = applet.selectCertificate(req); certificate = (X509Certificate) X509Utils.rawX509CertificateFromHex(extractJSON(appletResponse)); tracer.info(String.format("certificate: %s", certificate)); certificateChain = new X509Certificate[] { certificate }; } catch (Exception e) { tracer.error("error during the certificate selection", e); throw e; } // FindRefByName String sourceRef = null; try { SkdsFindRefByNameRequest req = new SkdsFindRefByNameRequest(); req.setName(SOURCE_NAME); SkdsFindRefByNameResponse findResp = postJsonRequest(req, SkdsFindRefByNameResponse.class); if (ResultCode.valueOf(findResp.getResultCode()) == ResultCode.SUCCESS) { sourceRef = findResp.getNodeRef(); } else { throw new Exception(findResp.getMessage()); } } catch (Exception e) { tracer.error("error during the pre sign phase", e); throw e; } // DocumentDetails try { SkdsDocumentDetailsRequest req = new SkdsDocumentDetailsRequest(); req.setNodeRefs(new String[] { sourceRef }); detailsResp = postJsonRequest(req, SkdsDocumentDetailsResponse.class); if (ResultCode.valueOf(detailsResp.getResultCode()) == ResultCode.SUCCESS) { documents = detailsResp.documentsFromBase64(); } else { throw new Exception(detailsResp.getMessage()); } Assert.isTrue(StringUtils.equals(documents[0].getBaseDocument().getMimetype(), "text/xml")); String baseName = FilenameUtils.getBaseName(documents[0].getBaseDocument().getFileName()); if (applyMark) { documents[0].setDestName(baseName + "_t.pdf"); } else { documents[0].setDestName(baseName + "_bes.pdf"); } } catch (Exception e) { tracer.error("error during the pre sign phase", e); throw e; } // empty signature - initialized with the SHA256withRSA and RSA algorithms emptySignatureDTO = new SignatureDTO(); emptySignatureDTO.setSignAlgorithm(conf.getSignatureAlgorithm().getName()); emptySignatureDTO.setDigestAlgorithm(conf.getDigestAlgorithm().getName()); emptySignatureDTO.signCategoryToString(SignCategory.XML); // Add to the empty signature the timeStamp request if needed TimeStampRequestDTO tsRequestDTO = new TimeStampRequestDTO(); if (applyMark) { tsRequestDTO.timestampDispositionToString(SignDisposition.TimeStamp.ENVELOPING); tsRequestDTO.messageImprintAlgorithmToString(DigestAlgorithm.SHA256); tsRequestDTO.nounceToString(BigInteger.TEN); tsRequestDTO.setTsUrl("http://ca.signfiles.com/TSAServer.aspx"); } emptySignatureDTO.setTimeStampRequest(tsRequestDTO); // chain signature - contains the certificate chain chainSignatureDTO = TemplateUtils.Instantiation.clone(emptySignatureDTO); chainSignatureDTO.certificateChainToHex(certificateChain); documents[0].setSignatures(new SignatureDTO[] { chainSignatureDTO }); // PreSign phase - join the content with the certificate chain and evaluate the digest try { SkdsPreSignRequest req = new SkdsPreSignRequest(); req.documentsToBase64(documents); preSignResp = postJsonRequest(req, SkdsPreSignResponse.class); if (ResultCode.valueOf(preSignResp.getResultCode()) == ResultCode.SUCCESS) { documents = preSignResp.documentsFromBase64(); digestSignatureDTO = documents[0].getSignatures()[0]; } else { throw new Exception(preSignResp.getMessage()); } } catch (Exception e) { tracer.error("error during the pre sign phase", e); throw e; } // signed signature - sign the digest with the smartCard to obtain the digitalSignature try { fingerPrint = digestSignatureDTO.getDigest().fingerPrintFromHex(); tracer.info(String.format("fingerPrint: %s", HexUtils.encodeHex(fingerPrint))); AppletRequestDTO req = new AppletRequestDTO(); req.setDriver(driver); req.setPin(scPin); req.setAlias(alias); req.setHexDigest(HexUtils.encodeHex(fingerPrint)); appletResponse = applet.signDigest(req); digitalSignature = HexUtils.decodeHex((String) extractJSON(appletResponse)); tracer.info(String.format("digitalSignature: %s", HexUtils.encodeHex(digitalSignature))); signedSignatureDTO = TemplateUtils.Instantiation.clone(digestSignatureDTO); signedSignatureDTO.digitalSignatureToHex(digitalSignature); documents[0].getSignatures()[0] = signedSignatureDTO; } catch (Exception e) { tracer.error("error during the digital signature evaluation", e); throw e; } // PostSign phase - add the digitalSignature to the envelope and store the result into the JCLResultDTO try { SkdsPostSignRequest req = new SkdsPostSignRequest(); req.documentsToBase64(documents); postSignResp = postJsonRequest(req, SkdsPostSignResponse.class); if (ResultCode.valueOf(postSignResp.getResultCode()) == ResultCode.SUCCESS) { documents = postSignResp.documentsFromBase64(); finalizedSignatureDTO = documents[0].getSignatures()[0]; } else { throw new Exception(postSignResp.getMessage()); } } catch (Exception e) { tracer.error("error during the envelope generation", e); throw e; } // // Verify phase - load the envelope content and verify the nested signature // try { // jsonResp = signatureService.verify ( envelopeHex, null, null, VerifyResult.VALID.name() ); // verifyDTO = extractResult ( VerifyDTO.class, jsonResp ); // } catch(Exception e) { // tracer.error("error during the envelope verification", e); // throw e; // } // // // finalized signature - enveloped signed and eventually marked, not modifiable anymore // try { // verifyResult = (VerifyInfo) converter.toVerifyInfo( verifyDTO ); // } catch(Exception e) { // tracer.error("unable to obtain the verifyInfo from the DTO", e); // throw e; // } // // try { // for(VerifiedSignature < ?, ?, VerifyResult, ?> verifiedSignature : verifyResult.getSignatures() ) { // tracer.info(String.format ( "signature validity: %s", verifiedSignature.getVerifyResult().name() )); // tracer.info(String.format ( "signature type: %s", verifiedSignature.getSignType().name() )); // tracer.info(String.format ( "disposition: %s", verifiedSignature.getDisposition().name() )); // tracer.info(String.format ( "digest algorithm: %s", verifiedSignature.getDigest().getAlgorithm().name() )); // tracer.info(String.format ( "finger print: %s", HexUtils.encodeHex(verifiedSignature.getDigest().getFingerPrint()) )); // tracer.info(String.format ( "counter signature: %s", verifiedSignature.isCounterSignature() )); // tracer.info(String.format ( "signature algorithm: %s", verifiedSignature.getSignAlgorithm().name() )); // tracer.info(String.format ( "digital signature: %s", HexUtils.encodeHex(verifiedSignature.getDigitalSignature()) )); // tracer.info(String.format ( "reason: %s", verifiedSignature.getReason() )); // tracer.info(String.format ( "signing location: %s", verifiedSignature.getLocation() )); // tracer.info(String.format ( "signing time: %s", formatDate(verifiedSignature.getSigningTime()) )); // tracer.info(String.format ( "\n ")); // tracer.info(String.format ( "signing certificate chain: ")); // for ( X509Certificate cert : verifiedSignature.getRawX509Certificates() ) { // showCertificate(cert); // } // if ( verifiedSignature.getTimeStamps() != null ) { // tracer.info(String.format ( "\n ")); // tracer.info(String.format ( "timestamps: ")); // for ( TimeStampInfo mark : verifiedSignature.getTimeStamps() ) { // tracer.info(String.format ( "timestamp validity: %s", mark.getVerifyResult().name() )); // tracer.info(String.format ( "timestamp authority: %s", mark.getTsaName() )); // tracer.info(String.format ( "timestamp authority: %s", mark.getTsaName() )); // tracer.info(String.format ( "message imprint alg: %s", mark.getMessageInprintInfo().getAlgorithm().name() )); // tracer.info(String.format ( "message imprint: %s", HexUtils.encodeHex(mark.getMessageInprintInfo().getFingerPrint()) )); // tracer.info(String.format ( "digest algorithm: %s", mark.getDigestAlgorithm().name() )); // tracer.info(String.format ( "digital signature: %s", HexUtils.encodeHex(mark.getDigitalSignature()) )); // tracer.info(String.format ( "signature algorithm: %s", mark.getSignAlgorithm().name() )); // tracer.info(String.format ( "timestamp certificate: ")); // for ( X509Certificate cert : mark.getRawX509Certificates() ) { // showCertificate(cert); // } // } // } // } // } catch(Exception e) { // tracer.error("unable to print the verify results", e); // throw e; // } } finally { applet.close(); } }
From source file:org.sonatype.nexus.crypto.internal.CryptoHelperImpl.java
License:Open Source License
/** * Configures the {@link BouncyCastleProvider} if its has not already been added. * * @return The {@link BouncyCastleProvider} instance. *///from w ww . jav a 2 s .c om public static Provider configureProvider() { Provider provider = Security.getProvider(BouncyCastleProvider.PROVIDER_NAME); if (provider == null) { provider = new BouncyCastleProvider(); Security.addProvider(provider); } return provider; }