public static void main(String[] args) throws Exception { java.security.Security.addProvider(new cryptix.jce.provider.CryptixCrypto()); java.security.Security.addProvider(new cryptix.openpgp.provider.CryptixOpenPGP()); readKeyrings(); decodeKeyRings(); writeMsg(); }
public void initialise() throws InitialisationException { try { java.security.Security.addProvider(new cryptix.jce.provider.CryptixCrypto()); java.security.Security.addProvider(new cryptix.openpgp.provider.CryptixOpenPGP()); factory = new PGPSecurityContextFactory(); } catch (Exception e) { throw new InitialisationException(CoreMessages.failedToCreate("PGPProvider"), e, this); } }
static { try { Security.addProvider((Provider) Class.forName(DEFAULT_JCE).newInstance()); } catch (Exception e) { log.info(e); try { Security.addProvider((Provider) Class.forName(IBM_JCE).newInstance()); } catch (Exception ex) { log.info(ex); } } }
public void initialise() throws InitialisationException { try { java.security.Security.addProvider(new cryptix.jce.provider.CryptixCrypto()); java.security.Security.addProvider(new cryptix.openpgp.provider.CryptixOpenPGP()); principalsKeyBundleMap = new HashMap(); readPublicKeyRing(); readPrivateKeyBundle(); } catch (Exception e) { logger.error("errore in inizializzazione:" + e.getMessage(), e); throw new InitialisationException(CoreMessages.failedToCreate("PGPKeyRingImpl"), e, this); } }
/** * Loads our X509 PEPPOL certificate togheter with our private key and initializes a * MdnMimeMessageFactory instance. */ @Override public void init(ServletConfig servletConfig) { KeystoreManager keystoreManager = KeystoreManager.getInstance(); X509Certificate ourCertificate = keystoreManager.getOurCertificate(); PrivateKey ourPrivateKey = keystoreManager.getOurPrivateKey(); mdnMimeMessageFactory = new MdnMimeMessageFactory(ourCertificate, ourPrivateKey); // Gives us access to BouncyCastle Security.addProvider(new BouncyCastleProvider()); // Gives us access to the Message repository holding the received messages messageRepository = MessageRepositoryFactory.getInstance(); // Creates the receiver for inbound messages inboundMessageReceiver = new InboundMessageReceiver(); // Locates an instance of the repository used for storage of raw statistics rawStatisticsRepository = RawStatisticsRepositoryFactoryProvider.getInstance().getInstanceForRawStatistics(); // fetch the CN of our certificate ourAccessPointIdentifier = AccessPointIdentifier.valueOf(KeystoreManager.getInstance().getOurCommonName()); }
public boolean generateKeys() { PublicKey keyPub; PrivateKey keyPri; SecureRandom rand; Security.addProvider(new ABAProvider()); rand = new SecureRandom(); rand.setSeed(System.currentTimeMillis()); try { KeyPairGenerator fact; KeyPair keyPair; fact = KeyPairGenerator.getInstance("RSA", "ABA"); fact.initialize(1024, rand); keyPair = fact.generateKeyPair(); keyPub = keyPair.getPublic(); keyPri = keyPair.getPrivate(); pubKey = bytesToHexStr(keyPub.getEncoded()); priKey = bytesToHexStr(keyPri.getEncoded()); } catch (Exception e) { return false; } return true; }
public void send(String mailto, String subject, String textMessage, String contentType) throws FileNotFoundException, MessagingException { Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); Properties props = new Properties(); props.put("mail.smtp.user", smtpUsername); props.put("mail.smtp.host", smtpHost); props.put("mail.smtp.port", smtpPort); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtps.auth", "true"); props.put("mail.smtp.debug", "true"); props.put("mail.smtp.socketFactory.port", smtpPort); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); props.put("mail.smtp.ssl", "true"); Authenticator auth = new SMTPAuthenticator(); Session smtpSession = Session.getInstance(props, auth); smtpSession.setDebug(true); Message message = new MimeMessage(smtpSession); InternetAddress[] address = {new InternetAddress(mailto)}; message.setRecipients(Message.RecipientType.TO, address); message.setSubject(subject); message.setSentDate(new Date()); message.setContent(textMessage, contentType); Transport tr = smtpSession.getTransport("smtp"); tr.connect(smtpHost, smtpUsername, smtpPassword); tr.sendMessage(message, message.getAllRecipients()); tr.close(); }
/** * Decrypt a partialy file encrypted. Generate a signle file, totally decrypted. * * @param password String password used to crypt the file * @param output String path to the output file * @throws FileNotFoundException * @throws IOException * @throws GeneralSecurityException */ public void decrypt(String password, String output) throws FileNotFoundException, IOException, GeneralSecurityException { this.prefix = FileUtility.unaggregate(this.file, this.marker); // use the API Security.addProvider(new BouncyCastleProvider()); // create a new crypter FileCrypter crypter = new FileCrypter(); // get key to be used from the password SecretKeySpec key = Password.getKey(password); // decrypt the second file (which is supposed to be crypted) crypter.decryptFile( key, this.file + FileUtility.extension_crypt, FileUtility.tmp + this.prefix + "-2" + FileUtility.extension_tmp); // recompose the file with an encrypted part in one single file FileUtility.recompose(this.prefix, output); // clean temporary files FileUtility.clean(); }
public SunSSLTransportFactory(Properties properties) throws GeneralSecurityException { X509TrustManager trustManager; HostnameVerifier hostnameVerifier; SSLContext sslContext; Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); url = (URL) properties.get(XmlRpcTransportFactory.TRANSPORT_URL); auth = properties.getProperty(XmlRpcTransportFactory.TRANSPORT_AUTH); trustManager = (X509TrustManager) properties.get(TRANSPORT_TRUSTMANAGER); if (trustManager == null) { trustManager = openTrustManager; } hostnameVerifier = (HostnameVerifier) properties.get(TRANSPORT_HOSTNAMEVERIFIER); if (hostnameVerifier == null) { hostnameVerifier = openHostnameVerifier; } sslContext = SSLContext.getInstance(SecurityTool.getSecurityProtocol()); X509TrustManager[] tmArray = new X509TrustManager[] {trustManager}; sslContext.init(null, tmArray, new SecureRandom()); // Set the default SocketFactory and HostnameVerifier // for javax.net.ssl.HttpsURLConnection if (sslContext != null) { HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); } HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier); }
/** {@inheritDoc} */ public synchronized void start(StartContext context) throws StartException { Security.addProvider(new JBossSaslProvider()); ProtocolChannelClient<ManagementChannel> client; try { ProtocolChannelClient.Configuration<ManagementChannel> configuration = new ProtocolChannelClient.Configuration<ManagementChannel>(); configuration.setEndpoint(endpointInjector.getValue()); configuration.setUri( new URI( "remote://" + hcAddressInjector.getValue().getHostName() + ":" + hcAddressInjector.getValue().getPort())); configuration.setChannelFactory(new ManagementChannelFactory()); client = ProtocolChannelClient.create(configuration); } catch (Exception e) { throw new StartException(e); } try { client.connect(new ClientCallbackHandler()); channel = client.openChannel(RemotingServices.SERVER_CHANNEL); channel.startReceiving(); } catch (IOException e) { throw new StartException("Failed to start remote Host Controller connection", e); } }
/** Set up the CryptixCrypto provider if we're on a platform that requires it. */ static { if (USE_CRYPTIX) { // Use reflection to load the Cryptix Provider. // It's safest that way (since we don't want to include // the cryptix jar on all installations, and Java // may try to load the class otherwise). try { Class clazz = Class.forName("cryptix.jce.provider.CryptixCrypto"); Object o = clazz.newInstance(); Security.addProvider((Provider) o); } catch (ClassNotFoundException e) { // NLogger.error( TigerTree.class, e, e ); } catch (IllegalAccessException e) { // NLogger.error( TigerTree.class, e, e ); } catch (InstantiationException e) { // NLogger.error( TigerTree.class, e, e ); } catch (ExceptionInInitializerError e) { // NLogger.error( TigerTree.class, e, e ); } catch (SecurityException e) { // NLogger.error( TigerTree.class, e, e ); } catch (ClassCastException e) { // NLogger.error( TigerTree.class, e, e ); } } }
@Before public void setUp() throws Exception { this.servletTester = new ServletTester(); String pathSpec = "/test.ocsp"; this.servletTester.addServlet(OcspResponderTestServlet.class, pathSpec); this.servletTester.start(); String servletUrl = this.servletTester.createSocketConnector(true); this.ocspUri = new URI(servletUrl + pathSpec); this.testedInstance = new OnlineOcspRepository(); OcspResponderTestServlet.reset(); this.rootKeyPair = TrustTestUtils.generateKeyPair(); DateTime notBefore = new DateTime(); DateTime notAfter = notBefore.plusMonths(1); this.rootCertificate = TrustTestUtils.generateSelfSignedCertificate( this.rootKeyPair, "CN=TestRoot", notBefore, notAfter); KeyPair keyPair = TrustTestUtils.generateKeyPair(); this.certificate = TrustTestUtils.generateCertificate( keyPair.getPublic(), "CN=Test", notBefore, notAfter, this.rootCertificate, this.rootKeyPair.getPrivate()); // required for org.bouncycastle.ocsp.CertificateID Security.addProvider(new BouncyCastleProvider()); }
static { try { MessageDigest.getInstance("MD4"); } catch (NoSuchAlgorithmException e) { Security.addProvider(new BouncyCastleProvider()); } }
/** * Generates an OCSP request using BouncyCastle. * * @param issuerCert certificate of the issues * @param serialNumber serial number * @return an OCSP request * @throws OCSPException * @throws IOException */ private static OCSPReq generateOCSPRequest(X509Certificate issuerCert, BigInteger serialNumber) throws OCSPException, IOException { // Add provider BC Security.addProvider(new repack.org.bouncycastle.jce.provider.BouncyCastleProvider()); // Generate the id for the certificate we are looking for CertificateID id = new CertificateID(CertificateID.HASH_SHA1, issuerCert, serialNumber); // basic request generation with nonce OCSPReqGenerator gen = new OCSPReqGenerator(); gen.addRequest(id); // create details for nonce extension Vector oids = new Vector(); Vector values = new Vector(); oids.add(OCSPObjectIdentifiers.id_pkix_ocsp_nonce); values.add( new X509Extension( false, new DEROctetString(new DEROctetString(PdfEncryption.createDocumentId()).getEncoded()))); gen.setRequestExtensions(new X509Extensions(oids, values)); return gen.generate(); }
@Before public void before() { Security.addProvider(new BouncyCastleProvider()); /** BouncyCastleProvider为默认的provider */ // Security.insertProviderAt(new BouncyCastleProvider(), 1); }
@Before public void setup() throws CertificateEncodingException, InvalidKeyException, IllegalStateException, NoSuchAlgorithmException, SignatureException, NoSuchProviderException, InvalidKeySpecException, IOException { Security.addProvider(new BouncyCastleProvider()); burpCertificateStore = new BurpCertificateStore(); // Single Certificate BurpCertificateBuilder b1 = new BurpCertificateBuilder("CN=example.net"); BurpCertificate c1 = b1.generateSelfSignedCertificate(); burpCertificateStore.addCertificate(c1); // Single Certificate BurpCertificateBuilder b2 = new BurpCertificateBuilder("CN=foobar.net"); BurpCertificate c2 = b2.generateSelfSignedCertificate(); burpCertificateStore.addCertificate(c2); // Single Certificate BurpCertificateBuilder b3 = new BurpCertificateBuilder("CN=gugus.lan"); BurpCertificate c3 = b3.generateSelfSignedCertificate(); burpCertificateStore.addCertificate(c3); // Certificate Chain CertificateTabController certificateTabController = new CertificateTabController(new CertificateTab()); List<BurpCertificate> certificateChain = certificateTabController.importCertificateChain("src/test/resources/hsr_chain.pem"); burpCertificateStore.addCertificateChain(certificateChain); certificateTabController.cloneCertificateChain(certificateChain); }
public static void sendSmtpSslMessage( String smtpHost, String smtpSslPort, String username, String password, String from, String to, String subject, String content, List<String> filenames, boolean debug) { logger.info("Send mail to {}, content: {}.", to, content); Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); Properties props = new Properties(); props.put("mail.transport.protocol", "smtp"); props.put("mail.host", smtpHost); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", smtpSslPort); props.put("mail.smtp.socketFactory.port", smtpSslPort); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); props.put("mail.debug", debug ? "true" : "false"); Session session = Session.getDefaultInstance(props, new UsrPwdAuthenticator(username, password)); session.setDebug(debug); sendMimeMessage(from, to, subject, content, filenames, session); logger.info("Mail sent"); }
private static Key loadKeyEncryptionKey() throws Exception { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); PEMReader pr = new PEMReader(new FileReader(EncryptTool.PRIVATE_KEY)); KeyPair k = (KeyPair) pr.readObject(); pr.close(); return k.getPrivate(); }
/** Add crypto providers. */ @Before public void setUp() { // Add Bouncy Castle Security Provider Security.addProvider(new BouncyCastleProvider()); PowerAuthConfiguration.INSTANCE.setKeyConvertor( CryptoProviderUtilFactory.getCryptoProviderUtils()); }
public static void main(String[] args) throws Exception { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); Misc func = new Misc(); // initialize the key generator (KG) and generate the public/private key pair SecureRandom random = new SecureRandom(); KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "BC"); generator.initialize(1024, random); KeyPair pair = generator.generateKeyPair(); /* initialize KG for digital signature and generate public/private keys for digital signatures It is generally not recommended to use the same public/private key pair for both encryption and digital signatures */ KeyPairGenerator generatorTwo = KeyPairGenerator.getInstance("RSA"); generatorTwo.initialize(1024); KeyPair sigKeyPair = generatorTwo.generateKeyPair(); byte[] sigPubKey = sigKeyPair.getPublic().getEncoded(); byte[] sigPrivKey = sigKeyPair.getPrivate().getEncoded(); byte[] pubKey = pair.getPublic().getEncoded(); byte[] privKey = pair.getPrivate().getEncoded(); // output the generated keys func.outputText(func.byteToHex(sigPubKey), "alice-dspk.txt"); func.outputText(func.byteToHex(sigPrivKey), "alice-dspvk.txt"); func.outputText(func.byteToHex(pubKey), "bob-pkepk.txt"); func.outputText(func.byteToHex(privKey), "bob-pkepvk.txt"); // clear sensitive data func.clear(sigPubKey); func.clear(sigPrivKey); func.clear(pubKey); func.clear(privKey); }
public boolean send() { try { Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); Properties props = new Properties(); props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.host", "smtp.gmail.com"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); props.put("mail.debug", "true"); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); Session session = Session.getDefaultInstance(props, new GJMailAuthenticator()); session.setDebug(true); Transport transport = session.getTransport(); InternetAddress addressFrom = new InternetAddress("*****@*****.**"); MimeMessage message = new MimeMessage(session); message.setSender(addressFrom); message.setSubject(subject); message.setContent(text, "text/html"); InternetAddress addressTo = new InternetAddress(to); message.setRecipient(Message.RecipientType.TO, addressTo); transport.connect(); Transport.send(message); transport.close(); System.out.println("DONE"); } catch (Exception e) { e.printStackTrace(); return false; } return true; }
/** * Create a self-signed X.509 Certificate. From * http://bfo.com/blog/2011/03/08/odds_and_ends_creating_a_new_x_509_certificate.html. * * @param dn the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB" * @param pair the KeyPair * @param days how many days from now the Certificate is valid for * @param algorithm the signing algorithm, eg "SHA1withRSA" * @return the self-signed certificate * @throws CertificateException thrown if a security error or an IO error ocurred. */ public static X509Certificate generateCertificate( String dn, KeyPair pair, int days, String algorithm) throws CertificateException { try { Security.addProvider(new BouncyCastleProvider()); AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(pair.getPrivate().getEncoded()); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded()); ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam); X500Name name = new X500Name(dn); Date from = new Date(); Date to = new Date(from.getTime() + days * 86400000L); BigInteger sn = new BigInteger(64, new SecureRandom()); X509v1CertificateBuilder v1CertGen = new X509v1CertificateBuilder(name, sn, from, to, name, subPubKeyInfo); X509CertificateHolder certificateHolder = v1CertGen.build(sigGen); return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder); } catch (CertificateException ce) { throw ce; } catch (Exception e) { throw new CertificateException(e); } }
private DESedeEncryptor() { try { // 检测是否有 TripleDES 加密的供应程序 // 如无,明确地安装SunJCE 供应程序 try { Cipher.getInstance(DESEDE); } catch (Exception e) { logger.error("Installling SunJCE provider."); Provider sunjce = new com.sun.crypto.provider.SunJCE(); Security.addProvider(sunjce); } // 得到 DESSede keys keyFactory = SecretKeyFactory.getInstance(DESEDE); // 创建一个 DESede 密码 encryptCipher = Cipher.getInstance(DESEDE); decryptCipher = Cipher.getInstance(DESEDE); // 为 CBC 模式创建一个用于初始化的 vector 对象 // IvParameters = new IvParameterSpec(new byte[] { 12, 34, 56, // 78, 90, // 87, 65, 43 }); } catch (Exception e) { // 记录加密或解密操作错误 logger.error("It's not support DESede encrypt arithmetic in this system!", e); } }
/* Ejemplo de uso de funciones de resumen Hash * carga el fichero que recibe como parametro y genera el resumen */ public static void main(String[] args) throws Exception { // Comprobar argumentos if (args.length != 1) { mensajeAyuda(); System.exit(1); } /* Cargar "provider" (sólo si no se usa el que viene por defecto) */ Security.addProvider(new BouncyCastleProvider()); // Usa provider BC /* Crear función resumen */ // MessageDigest messageDigest = MessageDigest.getInstance("MD5"); // Usa MD5 MessageDigest messageDigest = MessageDigest.getInstance("SHA-1"); // Usar SHA-1 /* Leer fichero de 1k en 1k y pasar fragmentos leidos a la funcion resumen */ byte[] buffer = new byte[1000]; int leidos = in.read(buffer, 0, 1000); while (leidos != -1) { messageDigest.update(buffer); // Pasa texto claro a la función resumen leidos = in.read(buffer, 0, 1000); } in.close(); byte[] resumen = messageDigest.digest(); // Completar el resumen // Mostrar resumen System.out.println("RESUMEN:"); mostrarBytes(resumen); System.out.println(); }
public static void sfSendEmail(String subject, String message) throws Exception { String SMTP_HOST_NAME = "smtp.gmail.com"; String SMTP_PORT = "465"; // message = "Test Email Notification From Monitor"; // subject = "Test Email Notification From Monitor"; String from = "*****@*****.**"; String[] recipients = { "*****@*****.**", "*****@*****.**", "*****@*****.**" }; String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; // String[] recipients = { "*****@*****.**"}; // String[] recipients = { "*****@*****.**", "*****@*****.**", // "*****@*****.**", "*****@*****.**", "*****@*****.**", // "*****@*****.**", "*****@*****.**"}; // String[] recipients = {"*****@*****.**"}; Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); boolean debug = true; Properties props = new Properties(); props.put("mail.smtp.host", SMTP_HOST_NAME); props.put("mail.smtp.auth", "true"); // props.put("mail.debug", "true"); props.put("mail.smtp.port", SMTP_PORT); props.put("mail.smtp.socketFactory.port", SMTP_PORT); props.put("mail.smtp.socketFactory.class", SSL_FACTORY); props.put("mail.smtp.socketFactory.fallback", "false"); Session session = Session.getDefaultInstance( props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication( "*****@*****.**", "els102sensorweb"); } }); // session.setDebug(debug); Message msg = new MimeMessage(session); InternetAddress 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.setContent(message, "text/plain"); Transport.send(msg); System.out.println("Sucessfully Sent mail to All Users"); }
public TestingKeys(final String keysFilePath) throws Exception { Security.addProvider(new BouncyCastleProvider()); // load keys: File keysFile = new File(this.getClass().getResource(TestSigningUtils.KEYS_FILE).getFile()); KeyStoreService storeService = new KeyStoreService(keysFile, "temp"); storeService.setDefaultAlias(TestSigningUtils.ownerCertUri); storeService.init(); privateKeys.put( TestSigningUtils.needCertUri, storeService.getPrivateKey(TestSigningUtils.needCertUri)); privateKeys.put( TestSigningUtils.ownerCertUri, storeService.getPrivateKey(TestSigningUtils.ownerCertUri)); privateKeys.put( TestSigningUtils.nodeCertUri, storeService.getPrivateKey(TestSigningUtils.nodeCertUri)); publicKeys.put( TestSigningUtils.needCertUri, storeService.getCertificate(TestSigningUtils.needCertUri).getPublicKey()); publicKeys.put( TestSigningUtils.ownerCertUri, storeService.getCertificate(TestSigningUtils.ownerCertUri).getPublicKey()); publicKeys.put( TestSigningUtils.nodeCertUri, storeService.getCertificate(TestSigningUtils.nodeCertUri).getPublicKey()); }
private static void bcDES() throws Exception { Security.addProvider(new BouncyCastleProvider()); // Key convert DESKeySpec desKeySpec = new DESKeySpec(bytesKey); SecretKeyFactory factory = SecretKeyFactory.getInstance("DES", "BC"); SecretKey desKey = factory.generateSecret(desKeySpec); Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, desKey); System.out.println("BC" + cipher.getProvider()); byte[] result = cipher.doFinal("ABC".getBytes()); String hexResult = Hex.encodeHexString(result); System.out.println(hexResult); cipher.init(Cipher.DECRYPT_MODE, desKey); result = cipher.doFinal( Hex.decodeHex(hexResult.toCharArray()) // result ); System.out.println(new String(result)); }
@Test public void testCMD() throws Exception { Authentication auth = new SkeletonKeyClientBuilder() .username("wburke") .password("geheim") .authentication("Skeleton Key"); ResteasyClient client = new ResteasyClient(); WebTarget target = client.target(generateBaseUrl()); String tiny = target.path("tokens").path("url").request().post(Entity.json(auth), String.class); System.out.println(tiny); System.out.println("tiny.size: " + tiny.length()); Security.addProvider(new BouncyCastleProvider()); KeyPair keyPair = KeyPairGenerator.getInstance("RSA", "BC").generateKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); X509Certificate cert = KeyTools.generateTestCertificate(keyPair); byte[] signed = p7s(privateKey, cert, null, tiny.getBytes()); CMSSignedData data = new CMSSignedData(signed); byte[] bytes = (byte[]) data.getSignedContent().getContent(); System.out.println("BYTES: " + new String(bytes)); System.out.println("size:" + signed.length); System.out.println("Base64.size: " + Base64.encodeBytes(signed).length()); SignerInformation signer = (SignerInformation) data.getSignerInfos().getSigners().iterator().next(); System.out.println("valid: " + signer.verify(cert, "BC")); }
private static Properties getImapMailProperties(Account account) { Properties props = new Properties(); if (account.getReceiveProtocolType().contains("gmail")) { props.put("mail.imap.host", "imap.gmail.com"); props.put("mail.imap.port", "143"); props.put("mail.imap.auth", "true"); props.put("mail.store.protocol", "imap"); props.put("mail.imap.starttls.enable", "true"); props.put("mail.imap.socketFactory.port", "993"); props.put("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.iamp.socketFactory.fallback", "false"); } else { props.setProperty("mail.imap.port", account.getReceivePort()); props.setProperty("mail.imap.connectiontimeout", "30000"); if ("ssl".equals(account.getReceiveTs())) { Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.setProperty("mail.imap.socketFactory.fallback", "false"); props.setProperty("mail.imap.socketFactory.port", account.getReceivePort()); } else if ("tls".equals(account.getReceiveTs())) { props.setProperty("mail.imap.starttls.enable", "true"); java.security.Security.setProperty( "ssl.SocketFactory.provider", "com.archermind.txtbl.mail.DummySSLSocketFactory"); } } return props; }
@BeforeClass public static void create() throws Exception { final WildFlyElytronProvider provider = new WildFlyElytronProvider(); Security.addProvider(provider); providerName = provider.getName(); endpoint = Endpoint.builder().setEndpointName("test").build(); NetworkServerProvider networkServerProvider = endpoint.getConnectionProviderInterface("remote", NetworkServerProvider.class); final SecurityDomain.Builder domainBuilder = SecurityDomain.builder(); final SimpleMapBackedSecurityRealm mainRealm = new SimpleMapBackedSecurityRealm(); domainBuilder.addRealm("mainRealm", mainRealm).build(); domainBuilder.setDefaultRealmName("mainRealm"); domainBuilder.setPermissionMapper((permissionMappable, roles) -> PermissionVerifier.ALL); final PasswordFactory passwordFactory = PasswordFactory.getInstance("clear"); mainRealm.setPasswordMap( "bob", passwordFactory.generatePassword(new ClearPasswordSpec("pass".toCharArray()))); final SaslServerFactory saslServerFactory = new ServiceLoaderSaslServerFactory(RemoteChannelCloseTest.class.getClassLoader()); final SaslAuthenticationFactory.Builder builder = SaslAuthenticationFactory.builder(); builder.setSecurityDomain(domainBuilder.build()); builder.setFactory(saslServerFactory); builder.addMechanism( SaslMechanismInformation.Names.SCRAM_SHA_256, MechanismConfiguration.EMPTY); final SaslAuthenticationFactory saslAuthenticationFactory = builder.build(); streamServer = networkServerProvider.createServer( new InetSocketAddress("localhost", 30123), OptionMap.EMPTY, saslAuthenticationFactory); }