List of usage examples for java.security SecureRandom SecureRandom
public SecureRandom()
From source file:com.tremolosecurity.unison.proxy.auth.twitter.TwitterAuth.java
public void init(ServletContext ctx, HashMap<String, Attribute> init) { secureRandom = new SecureRandom(); }
From source file:eu.mrbussy.security.crypto.pgp.PGPEncryptor.java
public void encryptFile(File inputFile, File outputFile) throws IOException, NoSuchProviderException, PGPException { if (pedg == null) { pedg = new PGPEncryptedDataGenerator(PGPEncryptedData.CAST5, checkIntegrity, new SecureRandom(), "BC"); try {/*from www . jav a 2s . c o m*/ pedg.addMethod(publicKey); } catch (PGPException e) { throw new PGPException("Error when creating PGP encryptino data generator."); } } OutputStream fileOutStream = new FileOutputStream(outputFile); if (isArmored) { fileOutStream = new ArmoredOutputStream(fileOutStream); } OutputStream encryptdOutStream = pedg.open(fileOutStream, new byte[1 << 16]); PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(PGPCompressedData.ZIP); OutputStream compressedOutStream = comData.open(encryptdOutStream); try { PGPSignatureGenerator sg = null; if (isSigning) { InputStream keyInputStream = new FileInputStream(new File(signingPrivateKeyFilePath)); PGPSecretKey secretKey = PGPUtils.findSecretKey(keyInputStream); PGPPrivateKey privateKey = secretKey.extractPrivateKey(signingPrivateKeyPassword.toCharArray(), "BC"); sg = new PGPSignatureGenerator(secretKey.getPublicKey().getAlgorithm(), PGPUtil.SHA1, "BC"); sg.initSign(PGPSignature.BINARY_DOCUMENT, privateKey); Iterator it = secretKey.getPublicKey().getUserIDs(); if (it.hasNext()) { PGPSignatureSubpacketGenerator ssg = new PGPSignatureSubpacketGenerator(); ssg.setSignerUserID(false, (String) it.next()); sg.setHashedSubpackets(ssg.generate()); } sg.generateOnePassVersion(false).encode(compressedOutStream); } PGPLiteralDataGenerator lg = new PGPLiteralDataGenerator(); OutputStream literalDataOutStream = lg.open(compressedOutStream, PGPLiteralData.BINARY, inputFile); byte[] bytes = IOUtils.toByteArray(new FileInputStream(inputFile)); literalDataOutStream.write(bytes); if (isSigning) { sg.update(bytes); sg.generate().encode(compressedOutStream); } literalDataOutStream.close(); lg.close(); compressedOutStream.close(); comData.close(); pedg.close(); fileOutStream.close(); } catch (PGPException e) { System.err.println(e); if (e.getUnderlyingException() != null) { e.getUnderlyingException().printStackTrace(); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (SignatureException e) { e.printStackTrace(); } }
From source file:com.github.seratch.signedrequest4j.SignedRequestApacheHCImpl.java
@Override public HttpResponse doRequest(String url, HttpMethod method, RequestBody body, String charset) throws IOException { HttpClient httpClient = new DefaultHttpClient(); HttpUriRequest request = getRequest(method, url); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeoutMillis); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeoutMillis); httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, USER_AGENT); httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, charset); for (String name : headersToOverwrite.keySet()) { request.setHeader(name, headersToOverwrite.get(name)); }//from w w w .j a v a 2 s . c o m String oAuthNonce = String.valueOf(new SecureRandom().nextLong()); Long oAuthTimestamp = System.currentTimeMillis() / 1000; String signature = getSignature(url, method, oAuthNonce, oAuthTimestamp); String authorizationHeader = getAuthorizationHeader(signature, oAuthNonce, oAuthTimestamp); request.setHeader("Authorization", authorizationHeader); if (method == HttpMethod.POST) { HttpPost postRequest = (HttpPost) request; BasicHttpEntity entity = new BasicHttpEntity(); entity.setContent(new ByteArrayInputStream(body.getBody())); entity.setContentType(body.getContentType()); postRequest.setEntity(entity); } else if (method == HttpMethod.PUT) { HttpPut putRequest = (HttpPut) request; BasicHttpEntity entity = new BasicHttpEntity(); entity.setContent(new ByteArrayInputStream(body.getBody())); entity.setContentType(body.getContentType()); putRequest.setEntity(entity); } org.apache.http.HttpResponse apacheHCResponse = httpClient.execute(request); if (apacheHCResponse.getStatusLine().getStatusCode() >= 400) { HttpResponse httpResponse = toReturnValue(apacheHCResponse, charset); throw new HttpException(apacheHCResponse.getStatusLine().getReasonPhrase(), httpResponse); } return toReturnValue(apacheHCResponse, charset); }
From source file:com.titilink.common.app.EncryptDecryptUtil.java
public void testDES() throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException { ////from ww w. j a v a2s . c om DESKeySpec desKeySpec = new DESKeySpec("SECURITY".getBytes(Charset.forName("UTF-8"))); SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = secretKeyFactory.generateSecret(desKeySpec); //?? Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.ENCRYPT_MODE, secretKey, new SecureRandom()); byte[] cipherData = cipher .doFinal("this is a security text from server".getBytes(Charset.forName("UTF-8"))); //? Cipher cipher1 = Cipher.getInstance("DES"); cipher1.init(Cipher.DECRYPT_MODE, secretKey, new SecureRandom()); byte[] plainData = cipher1.doFinal(cipherData); System.out.println(new String(plainData, Charset.forName("UTF-8"))); }
From source file:net.solarnetwork.pki.bc.test.BCCertificateServiceTest.java
@Test public void signCertificate() throws Exception { X509Certificate cert = service.generateCertificate(TEST_DN, publicKey, privateKey); String csr = service.generatePKCS10CertificateRequestString(cert, privateKey); KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048, new SecureRandom()); KeyPair caKeypair = keyGen.generateKeyPair(); X509Certificate caCert = service.generateCertificationAuthorityCertificate(TEST_CA_DN, caKeypair.getPublic(), caKeypair.getPrivate()); X509Certificate signed = service.signCertificate(csr, caCert, caKeypair.getPrivate()); assertEquals("Issuer", caCert.getSubjectX500Principal(), signed.getIssuerX500Principal()); assertEquals("Subject", cert.getSubjectX500Principal(), signed.getSubjectX500Principal()); }
From source file:co.cask.cdap.security.server.ExternalAuthenticationServerSSLTest.java
@Override protected HttpClient getHTTPClient() throws Exception { SSLContext sslContext = SSLContext.getInstance("SSL"); // set up a TrustManager that trusts everything sslContext.init(null, new TrustManager[] { new X509TrustManager() { @Override/* w ww. j a va 2 s . c om*/ public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException { // } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException { // } } }, new SecureRandom()); SSLSocketFactory sf = new SSLSocketFactory(sslContext); Scheme httpsScheme = new Scheme("https", getAuthServerPort(), sf); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(httpsScheme); // apache HttpClient version >4.2 should use BasicClientConnectionManager ClientConnectionManager cm = new BasicClientConnectionManager(schemeRegistry); return new DefaultHttpClient(cm); }
From source file:net.seleucus.wsp.crypto.FwknopSymmetricCrypto.java
public static String encrypt(byte[] key, String message) throws NoSuchAlgorithmException, IOException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { SecureRandom sr = new SecureRandom(); byte[] salt = new byte[8]; sr.nextBytes(salt);/*w w w . j a v a2 s . co m*/ byte[][] key_and_iv = deriveKeyAndIV(salt, key); SecretKeySpec enc_key; enc_key = new SecretKeySpec(key_and_iv[0], "AES"); Cipher aes = Cipher.getInstance("AES/CBC/PKCS5Padding"); IvParameterSpec iv = new IvParameterSpec(key_and_iv[1]); aes.init(Cipher.ENCRYPT_MODE, enc_key, iv); byte[] salted = "Salted__".getBytes("UTF-8"); byte[] cipher = aes.doFinal(message.getBytes("UTF-8")); byte[] result = new byte[salted.length + salt.length + cipher.length]; // now we need to glue: "Salted__" + salt + cipher System.arraycopy(salted, 0, result, 0, salted.length); System.arraycopy(salt, 0, result, salted.length, salt.length); System.arraycopy(cipher, 0, result, salted.length + salt.length, cipher.length); // remove = and FWKNOP_ENCRYPTION_HEADER return Base64.encodeBase64String(result).replace("=", "").replace(FWKNOP_ENCRYPTION_HEADER, ""); }
From source file:it.publisys.liferay.hook.shibboleth.ShibbolethPostLogoutAction.java
/** * Effettua una {@link HttpURLConnection} inviando anche i cookies * * @param url url/* ww w . j a va2s . c o m*/ * @param cookies cookies * @return response code */ private int _connect(String url, String cookies) { int responseCode = -1; try { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public void checkClientTrusted(java.security.cert.X509Certificate[] xcs, String string) throws CertificateException { } public void checkServerTrusted(java.security.cert.X509Certificate[] xcs, String string) throws CertificateException { } public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } } }; SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception ex) { ex.printStackTrace(System.err); } HttpURLConnection connection = null; try { URL _url = new URL(url); connection = (HttpURLConnection) _url.openConnection(Proxy.NO_PROXY); connection.setRequestProperty("Cookie", cookies); connection.setReadTimeout(5000); connection.setRequestMethod("GET"); responseCode = connection.getResponseCode(); _log.info("Logout Shibb response code: " + responseCode); if (responseCode == 200 && _log.isDebugEnabled()) { BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); StringBuilder _buffer = new StringBuilder(); String line = null; while ((line = br.readLine()) != null) { _buffer.append(line); } _log.debug(_buffer.toString()); } finally { if (br != null) { br.close(); } } } } catch (MalformedURLException mue) { mue.printStackTrace(System.err); } catch (IOException ioe) { ioe.printStackTrace(System.err); } finally { try { if (connection != null) { connection.disconnect(); } } catch (Exception ex) { ex.printStackTrace(System.out); } } return responseCode; }
From source file:co.cask.cdap.security.tools.KeyStores.java
/** * Generate an X.509 certificate//w ww . java 2 s . c o m * * @param dn Distinguished name for the owner of the certificate, it will also be the signer of the certificate. * @param pair Key pair used for signing the certificate. * @param days Validity of the certificate. * @param algorithm Name of the signature algorithm used. * @return A X.509 certificate */ private static X509Certificate getCertificate(String dn, KeyPair pair, int days, String algorithm) throws IOException, CertificateException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { // Calculate the validity interval of the certificate Date from = new Date(); Date to = DateUtils.addDays(from, days); CertificateValidity interval = new CertificateValidity(from, to); // Generate a random number to use as the serial number for the certificate BigInteger sn = new BigInteger(64, new SecureRandom()); // Create the name of the owner based on the provided distinguished name X500Name owner = new X500Name(dn); // Create an info objects with the provided information, which will be used to create the certificate X509CertInfo info = new X509CertInfo(); info.set(X509CertInfo.VALIDITY, interval); info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn)); // This certificate will be self signed, hence the subject and the issuer are same. info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(owner)); info.set(X509CertInfo.ISSUER, new CertificateIssuerName(owner)); info.set(X509CertInfo.KEY, new CertificateX509Key(pair.getPublic())); info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3)); AlgorithmId algo = new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid); info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algo)); // Create the certificate and sign it with the private key X509CertImpl cert = new X509CertImpl(info); PrivateKey privateKey = pair.getPrivate(); cert.sign(privateKey, algorithm); return cert; }