List of usage examples for java.security Security addProvider
public static int addProvider(Provider provider)
From source file:test.integ.be.fedict.hsm.jca.HSMProxySignatureTest.java
@Test public void testSignAuthnCertCredential() throws Exception { LOG.debug("sign"); // operate/*from w w w .j a v a 2 s . co m*/ Security.addProvider(new BeIDProvider()); KeyStore beidKeyStore = KeyStore.getInstance("BeID"); beidKeyStore.load(null); X509Certificate authnCert = (X509Certificate) beidKeyStore.getCertificate("Authentication"); PrivateKey authnPrivateKey = (PrivateKey) beidKeyStore.getKey("Authentication", null); Security.addProvider(new HSMProxyProvider()); KeyStore hsmProxyKeyStore = KeyStore.getInstance("HSMProxy"); HSMProxyKeyStoreParameter keyStoreParameter = new HSMProxyKeyStoreParameter(authnPrivateKey, authnCert, "https://www.e-contract.be/hsm-proxy-ws/dss", // "http://localhost/hsm-proxy-ws/dss", new MyHSMProxyAudit()); keyStoreParameter.setProxy("proxy.yourict.net", 8080); hsmProxyKeyStore.load(keyStoreParameter); PrivateKey hsmPrivateKey = (PrivateKey) hsmProxyKeyStore.getKey("alias", null); Signature signature = Signature.getInstance("SHA1withRSA"); signature.initSign(hsmPrivateKey); byte[] toBeSigned = "hello world".getBytes(); signature.update(toBeSigned); byte[] signatureValue = signature.sign(); assertNotNull(signatureValue); }
From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImplTest.java
/** * @throws java.lang.Exception//from w w w . j av a 2s.c o m */ @BeforeClass public static void setUpBeforeClass() throws Exception { // Just in case, add the BouncyCastle provider // It gets added from the CredentialManagerImpl constructor as well // but we may need some crypto operations before we invoke the Cred. Manager Security.addProvider(new BouncyCastleProvider()); // Create a test username and password for a service serviceURI = new URI("http://someservice"); usernamePassword = new UsernamePassword("testuser", "testpasswd"); // Load the test private key and its certificate File privateKeyCertFile = new File(privateKeyFileURL.getPath()); KeyStore pkcs12Keystore = java.security.KeyStore.getInstance("PKCS12", "BC"); // We have to use the BC provider here as the certificate chain is not loaded if we use whichever provider is first in Java!!! FileInputStream inStream = new FileInputStream(privateKeyCertFile); pkcs12Keystore.load(inStream, privateKeyAndPKCS12KeystorePassword.toCharArray()); // KeyStore pkcs12Keystore = credentialManager.loadPKCS12Keystore(privateKeyCertFile, privateKeyPassword); Enumeration<String> aliases = pkcs12Keystore.aliases(); while (aliases.hasMoreElements()) { // The test-private-key-cert.p12 file contains only one private key // and corresponding certificate entry String alias = aliases.nextElement(); if (pkcs12Keystore.isKeyEntry(alias)) { // is it a (private) key entry? privateKey = pkcs12Keystore.getKey(alias, privateKeyAndPKCS12KeystorePassword.toCharArray()); privateKeyCertChain = pkcs12Keystore.getCertificateChain(alias); break; } } inStream.close(); // Load the test trusted certificate (belonging to *.Google.com) File trustedCertFile = new File(trustedCertficateFileURL.getPath()); inStream = new FileInputStream(trustedCertFile); CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); trustedCertficate = (X509Certificate) certFactory.generateCertificate(inStream); try { inStream.close(); } catch (Exception e) { // Ignore } keystoreChangedObserver = new Observer<KeystoreChangedEvent>() { @Override public void notify(Observable<KeystoreChangedEvent> sender, KeystoreChangedEvent message) throws Exception { // TODO Auto-generated method stub } }; }
From source file:org.apache.synapse.commons.crypto.CryptoUtil.java
/** * Method to initialise crypto util. which will generate the required chiper etc. * * @param secureVaultProperties//from w ww. ja va 2 s . c om * @throws org.apache.axis2.AxisFault */ public void init(Properties secureVaultProperties) throws AxisFault { //Create a KeyStore Information for private key entry KeyStore IdentityKeyStoreInformation identityInformation = KeyStoreInformationFactory .createIdentityKeyStoreInformation(secureVaultProperties); String identityKeyPass = null; String identityStorePass = null; if (identityInformation != null) { identityKeyPass = identityInformation.getKeyPasswordProvider().getResolvedSecret(); identityStorePass = identityInformation.getKeyStorePasswordProvider().getResolvedSecret(); } if (!Util.validatePasswords(identityStorePass, identityKeyPass)) { if (log.isDebugEnabled()) { log.info("Either Identity or Trust keystore password is mandatory" + " in order to initialized secret manager."); } throw new AxisFault("Error inititialising cryptoutil, required parameters not provided"); } IdentityKeyStoreWrapper identityKeyStoreWrapper = new IdentityKeyStoreWrapper(); identityKeyStoreWrapper.init(identityInformation, identityKeyPass); algorithm = MiscellaneousUtil.getProperty(secureVaultProperties, CryptoConstants.CIPHER_ALGORITHM, CryptoConstants.CIPHER_ALGORITHM_DEFAULT); String provider = MiscellaneousUtil.getProperty(secureVaultProperties, CryptoConstants.SECURITY_PROVIDER, null); String cipherType = MiscellaneousUtil.getProperty(secureVaultProperties, CryptoConstants.CIPHER_TYPE, null); String inTypeString = MiscellaneousUtil.getProperty(secureVaultProperties, CryptoConstants.INPUT_ENCODE_TYPE, null); inType = Util.getEncodeDecodeType(inTypeString, EncodeDecodeTypes.BASE64); String outTypeString = MiscellaneousUtil.getProperty(secureVaultProperties, CryptoConstants.OUTPUT_ENCODE_TYPE, null); outType = Util.getEncodeDecodeType(outTypeString, null); CipherInformation cipherInformation = new CipherInformation(); cipherInformation.setAlgorithm(algorithm); cipherInformation.setCipherOperationMode(CipherOperationMode.DECRYPT); cipherInformation.setType(cipherType); cipherInformation.setInType(null); //skipping decoding encoding in securevault cipherInformation.setOutType(null); //skipping decoding encoding in securevault if (provider != null && !provider.isEmpty()) { if (CryptoConstants.BOUNCY_CASTLE_PROVIDER.equals(provider)) { Security.addProvider(new BouncyCastleProvider()); cipherInformation.setProvider(provider); } //todo need to add other providers if there are any. } baseCipher = CipherFactory.createCipher(cipherInformation, identityKeyStoreWrapper); isInitialized = true; }
From source file:org.apache.hadoop.yarn.server.resourcemanager.security.TestX509SecurityHandler.java
@BeforeClass public static void beforeClass() throws Exception { Security.addProvider(new BouncyCastleProvider()); BASE_DIR_FILE.mkdirs();//from w w w. ja va2 s . co m classPath = KeyStoreTestUtil.getClasspathDir(TestX509SecurityHandler.class); }
From source file:com.recomdata.datasetexplorer.proxy.HttpClient.java
/** * private method to get the URLConnection * @param str URL string/*from ww w . jav a2 s .c o m*/ */ private URLConnection getURLConnection(String str) throws MalformedURLException { try { if (isHttps) { /* when communicating with the server which has unsigned or invalid * certificate (https), SSLException or IOException is thrown. * the following line is a hack to avoid that */ Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol"); if (isProxy) { System.setProperty("https.proxyHost", proxyHost); System.setProperty("https.proxyPort", proxyPort + ""); } } else { if (isProxy) { System.setProperty("http.proxyHost", proxyHost); System.setProperty("http.proxyPort", proxyPort + ""); } } SSLUtilities.trustAllHostnames(); SSLUtilities.trustAllHttpsCertificates(); URL url = new URL(str); URLConnection uc = url.openConnection(); if (isHttps) { /*((HttpsURLConnection)uc).setHostnameVerifier(new HostnameVerifier() { public boolean verify (String hostname, String session) { return true; } });*/ } // set user agent to mimic a common browser String ua = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)"; uc.setRequestProperty("user-agent", ua); return uc; } catch (MalformedURLException me) { throw new MalformedURLException(str + " is not a valid URL"); } catch (Exception e) { e.printStackTrace(); return null; } }
From source file:org.forgerock.openidm.security.impl.KeystoreResourceProviderTest.java
@BeforeClass public void runInitalSetup() throws Exception { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); KeyStore keyStore = KeyStore.getInstance(KEYSTORE_TYPE); keyStore.load(null, KEYSTORE_PASSWORD.toCharArray()); keystoreFile = File.createTempFile(KEYSTORE, KEYSTORE_TYPE); FileOutputStream fileOutputStream = new FileOutputStream(keystoreFile); keyStore.store(fileOutputStream, KEYSTORE_PASSWORD.toCharArray()); fileOutputStream.close();/*from w w w .j a v a2 s .com*/ keyStoreHandler = new JcaKeyStoreHandler(KEYSTORE_TYPE, keystoreFile.getAbsolutePath(), KEYSTORE_PASSWORD); }
From source file:org.sinekartads.integration.xml.SignXMLonAlfresco.java
@Test public void test() throws Exception { if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { Security.addProvider(new BouncyCastleProvider()); }/* ww w. j a v a 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(), "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.sinekartads.integration.pdf.SignPDFonAlfresco.java
@Test public void test() throws Exception { if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { Security.addProvider(new BouncyCastleProvider()); }//from w w w .jav a2s . com 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:com.eucalyptus.auth.crypto.StringCrypto.java
public StringCrypto(String format, String provider) { this.asymmetricFormat = format; this.provider = provider; Security.addProvider(new BouncyCastleProvider()); if (Security.getProvider(this.provider) == null) throw new RuntimeException("cannot find security provider " + this.provider); keystore = SystemCredentials.getKeyStore(); if (keystore == null) throw new RuntimeException("cannot load keystore or find the key"); }
From source file:crypttools.PGPCryptoBC.java
public String signData(String data, String passphrase) throws Exception { Security.addProvider(new BouncyCastleProvider()); InputStream keyInputStream = new ByteArrayInputStream(this.armoredSecretKey); PGPSecretKey pgpSecretKey = readSecretKey(keyInputStream); PGPPrivateKey pgpPrivateKey = pgpSecretKey.extractPrivateKey( new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(passphrase.toCharArray())); PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator( new JcaPGPContentSignerBuilder(pgpSecretKey.getPublicKey().getAlgorithm(), PGPUtil.SHA1) .setProvider("BC")); signatureGenerator.init(PGPSignature.BINARY_DOCUMENT, pgpPrivateKey); @SuppressWarnings("unchecked") Iterator<String> it = pgpSecretKey.getPublicKey().getUserIDs(); if (it.hasNext()) { PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator(); spGen.setSignerUserID(false, it.next()); signatureGenerator.setHashedSubpackets(spGen.generate()); }// www . j a v a 2 s. co m ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); OutputStream outputStream = new ArmoredOutputStream(byteOutputStream); PGPCompressedDataGenerator compressDataGenerator = new PGPCompressedDataGenerator(PGPCompressedData.ZLIB); BCPGOutputStream bcOutputStream = new BCPGOutputStream(compressDataGenerator.open(outputStream)); signatureGenerator.generateOnePassVersion(false).encode(bcOutputStream); PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator(); File fileToSign = File.createTempFile("temp", ".scrap"); FileUtils.writeStringToFile(fileToSign, data); OutputStream literalDataGenOutputStream = literalDataGenerator.open(bcOutputStream, PGPLiteralData.BINARY, fileToSign); FileInputStream fis = new FileInputStream(fileToSign); int ch; while ((ch = fis.read()) >= 0) { literalDataGenOutputStream.write(ch); signatureGenerator.update((byte) ch); } literalDataGenerator.close(); fis.close(); signatureGenerator.generate().encode(bcOutputStream); compressDataGenerator.close(); outputStream.close(); fileToSign.delete(); return new String(byteOutputStream.toByteArray(), "UTF-8"); }