List of usage examples for java.security Security addProvider
public static int addProvider(Provider provider)
From source file:test.integ.be.fedict.commons.eid.client.JCATest.java
@Test public void testSwingParent2() throws Exception { Security.addProvider(new BeIDProvider()); MyFrame myFrame = new MyFrame(); final KeyStore keyStore = KeyStore.getInstance("BeID"); keyStore.load(myFrame);//from w ww . java 2 s .com final PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null); final Signature signature = Signature.getInstance("SHA1withRSA"); signature.initSign(authnPrivateKey); final byte[] toBeSigned = "hello world".getBytes(); signature.update(toBeSigned); byte[] signatureValue = signature.sign(); Certificate[] certificateChain = keyStore.getCertificateChain("Authentication"); signature.initVerify(certificateChain[0]); signature.update(toBeSigned); assertTrue(signature.verify(signatureValue)); }
From source file:org.collectionspace.chain.csp.webui.userdetails.UserDetailsReset.java
private Boolean doEmail(String csid, String emailparam, Request in, JSONObject userdetails) throws UIException, JSONException { String token = createToken(csid); EmailData ed = spec.getEmailData();//from w ww . j a v a 2 s.c o m String[] recipients = new String[1]; /* ABSTRACT EMAIL STUFF : WHERE do we get the content of emails from? cspace-config.xml */ String messagebase = ed.getPasswordResetMessage(); String link = ed.getBaseURL() + ed.getLoginUrl() + "?token=" + token + "&email=" + emailparam; String message = messagebase.replaceAll("\\{\\{link\\}\\}", link); String greeting = userdetails.getJSONObject("fields").getString("screenName"); message = message.replaceAll("\\{\\{greeting\\}\\}", greeting); message = message.replaceAll("\\\\n", "\\\n"); message = message.replaceAll("\\\\r", "\\\r"); String SMTP_HOST_NAME = ed.getSMTPHost(); String SMTP_PORT = ed.getSMTPPort(); String subject = ed.getPasswordResetSubject(); String from = ed.getFromAddress(); if (ed.getToAddress().isEmpty()) { recipients[0] = emailparam; } else { recipients[0] = ed.getToAddress(); } Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); boolean debug = false; Properties props = new Properties(); props.put("mail.smtp.host", SMTP_HOST_NAME); props.put("mail.smtp.auth", ed.doSMTPAuth()); props.put("mail.debug", ed.doSMTPDebug()); props.put("mail.smtp.port", SMTP_PORT); Session session = Session.getDefaultInstance(props); // XXX fix to allow authpassword /username session.setDebug(debug); Message msg = new MimeMessage(session); InternetAddress addressFrom; try { addressFrom = new InternetAddress(from); msg.setFrom(addressFrom); InternetAddress[] addressTo = new InternetAddress[recipients.length]; for (int i = 0; i < recipients.length; i++) { addressTo[i] = new InternetAddress(recipients[i]); } msg.setRecipients(Message.RecipientType.TO, addressTo); // Setting the Subject and Content Type msg.setSubject(subject); msg.setText(message); Transport.send(msg); } catch (AddressException e) { throw new UIException("AddressException: " + e.getMessage()); } catch (MessagingException e) { throw new UIException("MessagingException: " + e.getMessage()); } return true; }
From source file:org.wildfly.security.credential.store.KeystorePasswordStoreTest.java
/** * Register security provider containing {@link org.wildfly.security.credential.store.CredentialStoreSpi} implementation. *///from w w w. j a v a 2 s. co m @BeforeClass public static void setup() throws Exception { for (Provider provider : providers) { Security.addProvider(provider); } cleanCredentialStores(); // setup vaults that need to be complete before a test starts CredentialStoreBuilder.get().setKeyStoreFile(stores.get("TWO")).setKeyStoreType("JCEKS") .setKeyStorePassword("secret_store_TWO").addPassword("alias1", "secret-password-1") .addPassword("alias2", "secret-password-2").build(); CredentialStoreBuilder.get().setKeyStoreFile(stores.get("THREE")).setKeyStoreType("JCEKS") .setKeyStorePassword("secret_store_THREE").addPassword("db-pass-1", "1-secret-info") .addPassword("db-pass-2", "2-secret-info").addPassword("db-pass-3", "3-secret-info") .addPassword("db-pass-4", "4-secret-info").addPassword("db-pass-5", "5-secret-info").build(); CredentialStoreBuilder.get().setKeyStoreFile(stores.get("TO_DELETE")) .setKeyStorePassword("secret_store_DELETE").addPassword("alias1", "secret-password-1") .addPassword("alias2", "secret-password-2").build(); }
From source file:com.playonlinux.core.gpg.SignatureChecker.java
private void initVerify(PGPSignature pgpSignature, PGPPublicKey pgpSigningKey) throws PGPException, NoSuchProviderException { try {/* w w w . j a v a 2 s . co m*/ pgpSignature.initVerify(pgpSigningKey, "BC"); } catch (NoSuchProviderException e) { LOGGER.debug("No security provider found. Adding bouncy castle. This message can be ignored", e); Security.addProvider(new BouncyCastleProvider()); pgpSignature.initVerify(pgpSigningKey, "BC"); } }
From source file:org.forgerock.openidm.security.impl.EntryResourceProviderTest.java
@BeforeClass public void setUp() { Security.addProvider(new BouncyCastleProvider()); }
From source file:SignPdf.java
/** * Add a signature and a cryptographic timestamp to a pdf document. See www.ietf.org/rfc/rfc3161.txt. Proves that this * pdf had the current content at the current point in time. * * @param originalPdf/*from w w w . j ava 2s .c o m*/ * @param targetPdf * @param pk * @param certChain * @param revoked * @param tsaAddress * address of a rfc 3161 compatible timestamp server * @param reason * reason for the signature * @param location * location of signing * @param contact * emailaddress of the person who is signing * @throws IOException * @throws DocumentException * @throws SignatureException */ public static void signAndTimestamp(final InputStream originalPdf, final OutputStream targetPdf, final PrivateKey pk, final X509Certificate[] certChain, final CRL[] revoked, final String tsaAddress, final String reason, final String location, final String contact) throws IOException, DocumentException, SignatureException { // only an estimate, depends on the certificates returned by the TSA final int timestampSize = 4400; Security.addProvider(new BouncyCastleProvider()); final PdfReader reader = new PdfReader(originalPdf); final PdfStamper stamper = PdfStamper.createSignature(reader, targetPdf, '\0'); final PdfSignatureAppearance sap = stamper.getSignatureAppearance(); // comment next lines to have an invisible signature Rectangle cropBox = reader.getCropBox(1); float width = 50; float height = 50; Rectangle rectangle = new Rectangle(cropBox.getRight(width) - 20, cropBox.getTop(height) - 20, cropBox.getRight() - 20, cropBox.getTop() - 20); sap.setVisibleSignature(rectangle, 1, null); //sap.setVisibleSignature(new Rectangle(450, 650, 500, 700), 1, null); sap.setLayer2Text(""); final PdfSigGenericPKCS sig = new PdfSigGenericPKCS.PPKMS("BC"); final HashMap<PdfName, Integer> exclusionSizes = new HashMap<PdfName, Integer>(); // some informational fields sig.setReason(reason); sig.setLocation(location); sig.setContact(contact); sig.setName(PdfPKCS7.getSubjectFields(certChain[0]).getField("CN")); sig.setDate(new PdfDate(Calendar.getInstance())); // signing stuff final byte[] digest = new byte[256]; final byte[] rsaData = new byte[20]; sig.setExternalDigest(digest, rsaData, "RSA"); sig.setSignInfo(pk, certChain, revoked); final PdfString contents = (PdfString) sig.get(PdfName.CONTENTS); // *2 to get hex size, +2 for delimiters PdfLiteral contentsLit = new PdfLiteral((contents.toString().length() + timestampSize) * 2 + 2); exclusionSizes.put(PdfName.CONTENTS, new Integer(contentsLit.getPosLength())); sig.put(PdfName.CONTENTS, contentsLit); // certification; will display dialog or blue bar in Acrobat Reader sap.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED); // process all the information set above sap.setCryptoDictionary(sig); sap.preClose(exclusionSizes); // calculate digest (hash) try { final MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); final byte[] buf = new byte[8192]; int n; final InputStream inp = sap.getRangeStream(); while ((n = inp.read(buf)) != -1) { messageDigest.update(buf, 0, n); } final byte[] hash = messageDigest.digest(); // make signature (SHA1 the hash, prepend algorithm ID, pad, and encrypt with RSA) final Signature sign = Signature.getInstance("SHA1withRSA"); sign.initSign(pk); sign.update(hash); final byte[] signature = sign.sign(); // prepare the location of the signature in the target PDF contentsLit = (PdfLiteral) sig.get(PdfName.CONTENTS); final byte[] outc = new byte[(contentsLit.getPosLength() - 2) / 2]; final PdfPKCS7 pkcs7 = sig.getSigner(); pkcs7.setExternalDigest(signature, hash, "RSA"); final PdfDictionary dic = new PdfDictionary(); byte[] ssig = pkcs7.getEncodedPKCS7(); try { // try to retrieve cryptographic timestamp from configured tsa server ssig = pkcs7.getEncodedPKCS7(null, null, new TSAClientBouncyCastle(tsaAddress), null); } catch (final RuntimeException e) { log.error("Could not retrieve timestamp from server.", e); } System.arraycopy(ssig, 0, outc, 0, ssig.length); // add the timestamped signature dic.put(PdfName.CONTENTS, new PdfString(outc).setHexWriting(true)); // finish up sap.close(dic); } catch (final InvalidKeyException e) { throw new RuntimeException("Internal implementation error! No such signature type.", e); } catch (final NoSuchAlgorithmException e) { throw new RuntimeException("Internal implementation error! No such algorithm type.", e); } }
From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImplIT.java
/** * @throws java.lang.Exception/* ww w. java2 s. co m*/ */ @BeforeClass @Ignore public static void setUpBeforeCLass() throws Exception { Security.addProvider(new BouncyCastleProvider()); // Create some test username and passwords for services serviceURI = new URI("http://someservice"); usernamePassword = new UsernamePassword("testuser", "testpasswd"); serviceURI2 = new URI("http://someservice2"); usernamePassword2 = new UsernamePassword("testuser2", "testpasswd2"); serviceURI3 = new URI("http://someservice3"); usernamePassword3 = new UsernamePassword("testuser3", "testpasswd3"); // 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(trustedCertficateGoogleFileURL.getPath()); inStream = new FileInputStream(trustedCertFile); CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); trustedCertficateGoogle = (X509Certificate) certFactory.generateCertificate(inStream); try { inStream.close(); } catch (Exception e) { // Ignore } // Load the test trusted certificate (belonging to heater.cs.man.ac.uk) File trustedCertFile2 = new File(trustedCertficateHeaterFileURL.getPath()); inStream = new FileInputStream(trustedCertFile2); trustedCertficateHeater = (X509Certificate) certFactory.generateCertificate(inStream); try { inStream.close(); } catch (Exception e) { // Ignore } credentialManager = new CredentialManagerImpl(); // // The code below sets up the Keystore and Truststore files and loads some data into them // // and saves them into a temp directory. These files can later be used for testing the Credential // // Manager with non-empty keystores. // Random randomGenerator = new Random(); // String credentialManagerDirectoryPath = System // .getProperty("java.io.tmpdir") // + System.getProperty("file.separator") // + "taverna-security-" // + randomGenerator.nextInt(1000000); // System.out.println("Credential Manager's directory path: " // + credentialManagerDirectoryPath); // credentialManagerDirectory = new File(credentialManagerDirectoryPath); // credentialManager.setConfigurationDirectoryPath(credentialManagerDirectory); // // // Create the dummy master password provider // masterPasswordProvider = new DummyMasterPasswordProvider(); // masterPasswordProvider.setMasterPassword(masterPassword); // List<MasterPasswordProvider> masterPasswordProviders = new ArrayList<MasterPasswordProvider>(); // masterPasswordProviders.add(masterPasswordProvider); // credentialManager.setMasterPasswordProviders(masterPasswordProviders); // // // Add some stuff into Credential Manager // credentialManager.addUsernameAndPasswordForService(usernamePassword, serviceURI); // credentialManager.addUsernameAndPasswordForService(usernamePassword2, serviceURI2); // credentialManager.addUsernameAndPasswordForService(usernamePassword3, serviceURI3); // credentialManager.addKeyPair(privateKey, privateKeyCertChain); // credentialManager.addTrustedCertificate(trustedCertficate); // Set up a random temp directory and copy the test keystore files // from resources/security Random randomGenerator = new Random(); String credentialManagerDirectoryPath = System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + "taverna-security-" + randomGenerator.nextInt(1000000); System.out.println("Credential Manager's directory path: " + credentialManagerDirectoryPath); credentialManagerDirectory = new File(credentialManagerDirectoryPath); if (!credentialManagerDirectory.exists()) { credentialManagerDirectory.mkdir(); } URL keystoreFileURL = CredentialManagerImplIT.class.getResource("/security/t2keystore.ubr"); File keystoreFile = new File(keystoreFileURL.getPath()); File keystoreDestFile = new File(credentialManagerDirectory, "taverna-keystore.ubr"); URL truststroreFileURL = CredentialManagerImplIT.class.getResource("/security/t2truststore.ubr"); File truststoreFile = new File(truststroreFileURL.getPath()); File truststoreDestFile = new File(credentialManagerDirectory, "taverna-truststore.ubr"); FileUtils.copyFile(keystoreFile, keystoreDestFile); FileUtils.copyFile(truststoreFile, truststoreDestFile); credentialManager.setConfigurationDirectoryPath(credentialManagerDirectory); // Create the dummy master password provider masterPasswordProvider = new DummyMasterPasswordProvider(); masterPasswordProvider.setMasterPassword(masterPassword); List<MasterPasswordProvider> masterPasswordProviders = new ArrayList<MasterPasswordProvider>(); masterPasswordProviders.add(masterPasswordProvider); credentialManager.setMasterPasswordProviders(masterPasswordProviders); // Set an empty list for trust confirmation providers credentialManager.setTrustConfirmationProviders(new ArrayList<TrustConfirmationProvider>()); keystoreChangedObserver = new Observer<KeystoreChangedEvent>() { @Override public void notify(Observable<KeystoreChangedEvent> sender, KeystoreChangedEvent message) throws Exception { // TODO Auto-generated method stub } }; credentialManager.addObserver(keystoreChangedObserver); }
From source file:test.integ.be.e_contract.mycarenet.cxf.ScenarioTest.java
/** * First we clean the eHealthBox. Then we publish to ourself. Next we * download this message./* www . j a v a 2 s.c om*/ * * @throws Exception */ @Test public void testScenario() throws Exception { // STS EHealthSTSClient client = new EHealthSTSClient("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService"); Security.addProvider(new BeIDProvider()); KeyStore keyStore = KeyStore.getInstance("BeID"); keyStore.load(null); PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null); X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication"); KeyStore eHealthKeyStore = KeyStore.getInstance("PKCS12"); FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path()); eHealthKeyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray()); Enumeration<String> aliasesEnum = eHealthKeyStore.aliases(); String alias = aliasesEnum.nextElement(); X509Certificate eHealthCertificate = (X509Certificate) eHealthKeyStore.getCertificate(alias); PrivateKey eHealthPrivateKey = (PrivateKey) eHealthKeyStore.getKey(alias, this.config.getEHealthPKCS12Password().toCharArray()); List<Attribute> attributes = new LinkedList<Attribute>(); attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin")); attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin")); List<AttributeDesignator> attributeDesignators = new LinkedList<AttributeDesignator>(); attributeDesignators.add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin")); attributeDesignators .add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin")); attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth", "urn:be:fgov:person:ssin:nurse:boolean")); Element assertion = client.requestAssertion(authnCertificate, authnPrivateKey, eHealthCertificate, eHealthPrivateKey, attributes, attributeDesignators); assertNotNull(assertion); String assertionString = client.toString(assertion); // eHealthBox: remove all messages. EHealthBoxConsultationClient eHealthBoxClient = new EHealthBoxConsultationClient( "https://services-acpt.ehealth.fgov.be/ehBoxConsultation/v3"); eHealthBoxClient.setCredentials(eHealthPrivateKey, assertionString); GetMessageListResponseType messageList = eHealthBoxClient.getMessagesList(); for (Message message : messageList.getMessage()) { String messageId = message.getMessageId(); LOG.debug("message id: " + messageId); eHealthBoxClient.deleteMessage(messageId); } // eHealthBox: publish via SOAP attachment EHealthBoxPublicationClient publicationClient = new EHealthBoxPublicationClient( "https://services-acpt.ehealth.fgov.be/ehBoxPublication/v3"); ObjectFactory objectFactory = new ObjectFactory(); PublicationMessageType publicationMessage = objectFactory.createPublicationMessageType(); String publicationId = UUID.randomUUID().toString().substring(1, 13); LOG.debug("publication id: " + publicationId); publicationMessage.setPublicationId(publicationId); DestinationContextType destinationContext = objectFactory.createDestinationContextType(); publicationMessage.getDestinationContext().add(destinationContext); destinationContext.setQuality("NURSE"); destinationContext.setType("INSS"); destinationContext.setId(getUserIdentifier(authnCertificate)); ContentContextType contentContext = objectFactory.createContentContextType(); publicationMessage.setContentContext(contentContext); PublicationContentType publicationContent = objectFactory.createPublicationContentType(); contentContext.setContent(publicationContent); PublicationDocumentType publicationDocument = objectFactory.createPublicationDocumentType(); publicationContent.setDocument(publicationDocument); publicationDocument.setTitle("test"); publicationDocument.setMimeType("application/octet-stream"); publicationDocument.setDownloadFileName("test.dat"); byte[] data = new byte[1024 * 256]; DataSource dataSource = new ByteArrayDataSource(data, "application/octet-stream"); DataHandler dataHandler = new DataHandler(dataSource); publicationDocument.setEncryptableBinaryContent(dataHandler); MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); byte[] digest = messageDigest.digest(data); publicationDocument.setDigest(Base64.encodeBase64String(digest)); ContentSpecificationType contentSpecification = objectFactory.createContentSpecificationType(); contentContext.setContentSpecification(contentSpecification); contentSpecification.setContentType("DOCUMENT"); publicationClient.setCredentials(eHealthPrivateKey, assertionString); publicationClient.publish(publicationMessage); Thread.sleep(1000 * 5); LOG.debug("GET MESSAGES LIST"); messageList = eHealthBoxClient.getMessagesList(); for (Message message : messageList.getMessage()) { String messageId = message.getMessageId(); LOG.debug("message id: " + messageId); LOG.debug("GET FULL MESSAGE"); GetFullMessageResponseType getFullMessageResponse = eHealthBoxClient.getMessage(messageId); ConsultationMessageType consultationMessage = getFullMessageResponse.getMessage(); be.e_contract.mycarenet.ehbox.jaxb.consultation.protocol.ContentContextType consultationContentContext = consultationMessage .getContentContext(); ConsultationContentType consultationContent = consultationContentContext.getContent(); ConsultationDocumentType consultationDocument = consultationContent.getDocument(); byte[] encryptableTextContent = consultationDocument.getEncryptableTextContent(); if (null != encryptableTextContent) { LOG.debug("result EncryptableTextContent: " + encryptableTextContent.length); } else { LOG.debug("no EncryptableTextContent"); } DataHandler resultDataHandler = consultationDocument.getEncryptableBinaryContent(); if (null != resultDataHandler) { LOG.debug("result EncryptableBinaryContent"); byte[] resultData = IOUtils.toByteArray(resultDataHandler.getInputStream()); LOG.debug("result data size: " + resultData.length); } LOG.debug("DELETE MESSAGE"); eHealthBoxClient.deleteMessage(messageId); } }
From source file:de.sandmage.opportunisticmail.crypto.OpenPGP.java
public String getEncryptedMessage(byte[] data) { Security.addProvider(new BouncyCastleProvider()); try {//from w ww .j a v a 2s . c o m ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStream out = new ArmoredOutputStream(baos); byte[] compressedData = compressFile(data, CompressionAlgorithmTags.ZIP); PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator( new JcePGPDataEncryptorBuilder(PGPEncryptedData.AES_128).setWithIntegrityPacket(true) .setSecureRandom(new SecureRandom()).setProvider("BC")); encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(this.publicKey).setProvider("BC")); OutputStream cOut = encGen.open(out, compressedData.length); cOut.write(compressedData); cOut.close(); out.close(); baos.flush(); return new String(baos.toByteArray()); } catch (PGPException | IOException e) { e.printStackTrace(); } return null; }
From source file:org.signserver.module.xades.signer.XAdESSignerUnitTest.java
@BeforeClass public static void setUpClass() throws Exception { Security.addProvider(new BouncyCastleProvider()); tokenRSA = generateToken(KeyType.RSA); tokenDSA = generateToken(KeyType.DSA); tokenECDSA = generateToken(KeyType.ECDSA); tokenWithIntermediateCert = generateTokenWithIntermediateCert(); }