List of usage examples for java.security SecureRandom getInstance
public static SecureRandom getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:com.qut.middleware.deployer.logic.RegisterESOELogic.java
private String generatePassphrase() { SecureRandom random;// w ww . ja v a 2s. c om String passphrase; byte[] buf; try { /* Attempt to get the specified RNG instance */ random = SecureRandom.getInstance("SHA1PRNG"); } catch (NoSuchAlgorithmException nsae) { this.logger.error("NoSuchAlgorithmException when trying to create SecureRandom instance " //$NON-NLS-1$ + nsae.getLocalizedMessage()); this.logger.debug(nsae.getLocalizedMessage(), nsae); random = new SecureRandom(); } buf = new byte[Constants.PASSPHRASE_LENGTH]; random.nextBytes(buf); passphrase = new String(Hex.encodeHex(buf)); return passphrase; }
From source file:com.tremolosecurity.proxy.auth.SAML2Auth.java
@Override public void init(ServletContext ctx, HashMap<String, Attribute> init) { this.cfgMgr = (ConfigManager) ctx.getAttribute(ProxyConstants.TREMOLO_CONFIG); try {/* w ww . j a v a 2s . c o m*/ InitializationService.initialize(); } catch (InitializationException e1) { logger.warn("Could not initialize opensaml", e1); } try { this.random = SecureRandom.getInstance("SHA1PRNG"); } catch (NoSuchAlgorithmException e) { logger.error("could not load secure random"); } this.defaultRelayStates = new HashMap<String, String>(); if (init.containsKey("defaultRelayStates")) { for (String map : init.get("defaultRelayStates").getValues()) { String referer = map.substring(0, map.indexOf('|')); String relaystate = map.substring(map.indexOf('|') + 1); logger.info("Default Relay State - '" + referer + "' --> '" + relaystate + "'"); this.defaultRelayStates.put(referer, relaystate); } } }
From source file:com.daon.identityx.controller.SimpleController.java
/*** * Generate a random salt value for each account * It would be better to use the strong instance of SecureRandom * but on many Linux systems, it may take time for the /dev/random * to contain the necessary number of bits required. As this is a * demonstration, the algorithm has been changed to SHA1PRNG which * is fast but not as secure./* w w w .j a v a2 s. c o m*/ * * @return */ protected synchronized byte[] getRandomSalt() { try { byte[] data = new byte[32]; if (random == null) { random = SecureRandom.getInstance("SHA1PRNG"); //random = SecureRandom.getInstanceStrong(); <- More secure } random.nextBytes(data); return data; } catch (Exception e) { logger.error("An excpetion occurred while attempting to generate the random salt", e); throw new RuntimeException(e); } }
From source file:org.apache.ws.security.util.WSSecurityUtil.java
/** * @param algorithm// w w w .j av a2s . c o m * * @return a SecureRandom instance initialized with the identifier * specified in algorithm */ public synchronized static SecureRandom resolveSecureRandom(final String algorithm) throws NoSuchAlgorithmException { if (random == null || !algorithm.equals(randomAlgorithm)) { random = SecureRandom.getInstance(algorithm); randomAlgorithm = algorithm; random.setSeed(System.currentTimeMillis()); } return random; }
From source file:com.servoy.j2db.util.Utils.java
/** * Hashes the given string with the PKCS/PBKDF2 algoritme see http://en.wikipedia.org/wiki/PBKDF2 for more information * * @param textString The string to hash/*from ww w . ja va 2 s.c o m*/ * @param iterations Number of hash iterations to be done (should be higher then 1000) * @return the hash of the string */ @SuppressWarnings("nls") public static String calculatePBKDF2(String textString, int iterations) { try { SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); byte[] salt = new byte[8]; sr.nextBytes(salt); PBKDF2Parameters p = new PBKDF2Parameters("HmacSHA1", "ISO-8859-1", salt, iterations); PBKDF2Engine e = new PBKDF2Engine(p); p.setDerivedKey(e.deriveKey(textString)); return new PBKDF2HexFormatter().toString(p); } catch (NoSuchAlgorithmException e) { Debug.error("No SHA1 algorime found under the name SHA1PRNG", e); } return null; }
From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java
protected void enforcementOfUniqueSubjectDN() throws Exception { log.trace(">enforcementOfUniqueSubjectDN"); final AuthenticationToken admin = new TestAlwaysAllowLocalAuthenticationToken( new UsernamePrincipal("SYSTEMTEST")); final UserDataVOWS ca1userData1 = getUserData(CA1_WSTESTUSER1); final UserDataVOWS ca1userData2 = getUserData(CA1_WSTESTUSER2); final UserDataVOWS ca2userData1 = getUserData(CA2_WSTESTUSER1); final CAInfo ca1Info = caSession.getCAInfo(admin, CA1); final int iRandom = SecureRandom.getInstance("SHA1PRNG").nextInt(); // to // make sure a new DN is used in next test final String subjectDN_A = "CN=EnforcementOfUniqueSubjectDN Test A " + iRandom; final String subjectDN_B = "CN=EnforcementOfUniqueSubjectDN Test B " + iRandom; // set same DN for all users editUser(ca1userData1, subjectDN_A); editUser(ca1userData2, subjectDN_A); editUser(ca2userData1, subjectDN_A); // make sure same DN for different users is prevented ca1Info.setDoEnforceUniqueDistinguishedName(true); caAdminSessionRemote.editCA(admin, ca1Info); // fetching first cert for a DN should be no problem assertNull(certreqInternal(ca1userData1, getP10(), CertificateHelper.CERT_REQ_TYPE_PKCS10)); // fetching another cert for the same DN for a user that does not have a // certificate with this DN should fail final ErrorCode errorCode = certreqInternal(ca1userData2, getP10(), CertificateHelper.CERT_REQ_TYPE_PKCS10); assertNotNull("error code should not be null", errorCode); assertEquals(org.cesecore.ErrorCode.CERTIFICATE_WITH_THIS_SUBJECTDN_ALREADY_EXISTS_FOR_ANOTHER_USER .getInternalErrorCode(), errorCode.getInternalErrorCode()); // test that the user that was denied a cert can get a cert with another // DN./* www . j av a 2 s .c o m*/ editUser(ca1userData2, subjectDN_B); assertNull(certreqInternal(ca1userData2, getP10(), CertificateHelper.CERT_REQ_TYPE_PKCS10)); editUser(ca1userData2, subjectDN_A); // fetching more than one cert with the same DN should be possible for // the same user assertNull(certreqInternal(ca1userData1, getP10(), CertificateHelper.CERT_REQ_TYPE_PKCS10)); // A user could get a certificate for a DN used in another certificate // from another user if another CA is issuing it. assertNull(certreqInternal(ca2userData1, getP10(), CertificateHelper.CERT_REQ_TYPE_PKCS10)); // permit same DN for different users ca1Info.setDoEnforceUniqueDistinguishedName(false); caAdminSessionRemote.editCA(admin, ca1Info); // fetching cert for existing DN for a user that does not have a // certificate with this DN is now permitted assertNull(certreqInternal(ca1userData2, getP10(), CertificateHelper.CERT_REQ_TYPE_PKCS10)); // forbid same DN for different users ca1Info.setDoEnforceUniqueDistinguishedName(true); caAdminSessionRemote.editCA(admin, ca1Info); // set back original DN for all users editUser(ca1userData1, getDN(CA1_WSTESTUSER1)); editUser(ca1userData2, getDN(CA1_WSTESTUSER2)); editUser(ca2userData1, getDN(CA2_WSTESTUSER1)); log.trace("<enforcementOfUniqueSubjectDN"); }
From source file:org.apache.usergrid.persistence.Schema.java
private static byte[] getRawKey(byte[] seed) throws Exception { KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); sr.setSeed(seed);/*from ww w. ja va2 s . c om*/ keyGenerator.init(128, sr); // 192 and 256 bits may not be available SecretKey secretKey = keyGenerator.generateKey(); return secretKey.getEncoded(); }
From source file:org.ejbca.util.CertTools.java
public static X509Certificate genSelfCertForPurpose(String dn, long validity, String policyId, PrivateKey privKey, PublicKey pubKey, String sigAlg, boolean isCA, int keyusage, String provider) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, CertificateEncodingException, IllegalStateException, NoSuchProviderException { // Create self signed certificate Date firstDate = new Date(); // Set back startdate ten minutes to avoid some problems with wrongly set clocks. firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000)); Date lastDate = new Date(); // validity in days = validity*24*60*60*1000 milliseconds lastDate.setTime(lastDate.getTime() + (validity * (24 * 60 * 60 * 1000))); X509V3CertificateGenerator certgen = new X509V3CertificateGenerator(); // Transform the PublicKey to be sure we have it in a format that the X509 certificate generator handles, it might be // a CVC public key that is passed as parameter PublicKey publicKey = null;//w w w . j ava 2s . co m if (pubKey instanceof RSAPublicKey) { RSAPublicKey rsapk = (RSAPublicKey) pubKey; RSAPublicKeySpec rSAPublicKeySpec = new RSAPublicKeySpec(rsapk.getModulus(), rsapk.getPublicExponent()); try { publicKey = KeyFactory.getInstance("RSA").generatePublic(rSAPublicKeySpec); } catch (InvalidKeySpecException e) { log.error("Error creating RSAPublicKey from spec: ", e); publicKey = pubKey; } } else if (pubKey instanceof ECPublicKey) { ECPublicKey ecpk = (ECPublicKey) pubKey; try { ECPublicKeySpec ecspec = new ECPublicKeySpec(ecpk.getW(), ecpk.getParams()); // will throw NPE if key is "implicitlyCA" publicKey = KeyFactory.getInstance("EC").generatePublic(ecspec); } catch (InvalidKeySpecException e) { log.error("Error creating ECPublicKey from spec: ", e); publicKey = pubKey; } catch (NullPointerException e) { log.debug("NullPointerException, probably it is implicitlyCA generated keys: " + e.getMessage()); publicKey = pubKey; } } else { log.debug("Not converting key of class. " + pubKey.getClass().getName()); publicKey = pubKey; } // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this // bean is created. byte[] serno = new byte[8]; SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed(new Date().getTime()); random.nextBytes(serno); certgen.setSerialNumber(new java.math.BigInteger(serno).abs()); certgen.setNotBefore(firstDate); certgen.setNotAfter(lastDate); certgen.setSignatureAlgorithm(sigAlg); certgen.setSubjectDN(CertTools.stringToBcX509Name(dn)); certgen.setIssuerDN(CertTools.stringToBcX509Name(dn)); certgen.setPublicKey(publicKey); // Basic constranits is always critical and MUST be present at-least in CA-certificates. BasicConstraints bc = new BasicConstraints(isCA); certgen.addExtension(X509Extensions.BasicConstraints.getId(), true, bc); // Put critical KeyUsage in CA-certificates if (isCA) { X509KeyUsage ku = new X509KeyUsage(keyusage); certgen.addExtension(X509Extensions.KeyUsage.getId(), true, ku); } // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Firefox. try { if (isCA) { SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(publicKey.getEncoded())) .readObject()); SubjectKeyIdentifier ski = new SubjectKeyIdentifier(spki); SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(publicKey.getEncoded())) .readObject()); AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki); certgen.addExtension(X509Extensions.SubjectKeyIdentifier.getId(), false, ski); certgen.addExtension(X509Extensions.AuthorityKeyIdentifier.getId(), false, aki); } } catch (IOException e) { // do nothing } // CertificatePolicies extension if supplied policy ID, always non-critical if (policyId != null) { PolicyInformation pi = new PolicyInformation(new DERObjectIdentifier(policyId)); DERSequence seq = new DERSequence(pi); certgen.addExtension(X509Extensions.CertificatePolicies.getId(), false, seq); } X509Certificate selfcert = certgen.generate(privKey, provider); return selfcert; }
From source file:org.cesecore.util.CertTools.java
public static X509Certificate genSelfCertForPurpose(String dn, long validity, String policyId, PrivateKey privKey, PublicKey pubKey, String sigAlg, boolean isCA, int keyusage, Date privateKeyNotBefore, Date privateKeyNotAfter, String provider, boolean ldapOrder, List<Extension> additionalExtensions) throws CertificateParsingException, IOException, OperatorCreationException { // Create self signed certificate Date firstDate = new Date(); // Set back startdate ten minutes to avoid some problems with wrongly set clocks. firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000)); Date lastDate = new Date(); // validity in days = validity*24*60*60*1000 milliseconds lastDate.setTime(lastDate.getTime() + (validity * (24 * 60 * 60 * 1000))); // Transform the PublicKey to be sure we have it in a format that the X509 certificate generator handles, it might be // a CVC public key that is passed as parameter PublicKey publicKey = null;/* w w w .j a va 2 s . c o m*/ if (pubKey instanceof RSAPublicKey) { RSAPublicKey rsapk = (RSAPublicKey) pubKey; RSAPublicKeySpec rSAPublicKeySpec = new RSAPublicKeySpec(rsapk.getModulus(), rsapk.getPublicExponent()); try { publicKey = KeyFactory.getInstance("RSA").generatePublic(rSAPublicKeySpec); } catch (InvalidKeySpecException e) { log.error("Error creating RSAPublicKey from spec: ", e); publicKey = pubKey; } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("RSA was not a known algorithm", e); } } else if (pubKey instanceof ECPublicKey) { ECPublicKey ecpk = (ECPublicKey) pubKey; try { ECPublicKeySpec ecspec = new ECPublicKeySpec(ecpk.getW(), ecpk.getParams()); // will throw NPE if key is "implicitlyCA" final String algo = ecpk.getAlgorithm(); if (algo.equals(AlgorithmConstants.KEYALGORITHM_ECGOST3410)) { try { publicKey = KeyFactory.getInstance("ECGOST3410").generatePublic(ecspec); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("ECGOST3410 was not a known algorithm", e); } } else if (algo.equals(AlgorithmConstants.KEYALGORITHM_DSTU4145)) { try { publicKey = KeyFactory.getInstance("DSTU4145").generatePublic(ecspec); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("DSTU4145 was not a known algorithm", e); } } else { try { publicKey = KeyFactory.getInstance("EC").generatePublic(ecspec); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("EC was not a known algorithm", e); } } } catch (InvalidKeySpecException e) { log.error("Error creating ECPublicKey from spec: ", e); publicKey = pubKey; } catch (NullPointerException e) { log.debug("NullPointerException, probably it is implicitlyCA generated keys: " + e.getMessage()); publicKey = pubKey; } } else { log.debug("Not converting key of class. " + pubKey.getClass().getName()); publicKey = pubKey; } // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this // bean is created. byte[] serno = new byte[8]; SecureRandom random; try { random = SecureRandom.getInstance("SHA1PRNG"); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("SHA1PRNG was not a known algorithm", e); } random.setSeed(new Date().getTime()); random.nextBytes(serno); SubjectPublicKeyInfo pkinfo; try { pkinfo = new SubjectPublicKeyInfo((ASN1Sequence) ASN1Primitive.fromByteArray(publicKey.getEncoded())); } catch (IOException e) { throw new IllegalArgumentException("Provided public key could not be read to ASN1Primitive", e); } X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder( CertTools.stringToBcX500Name(dn, ldapOrder), new BigInteger(serno).abs(), firstDate, lastDate, CertTools.stringToBcX500Name(dn, ldapOrder), pkinfo); // Basic constranits is always critical and MUST be present at-least in CA-certificates. BasicConstraints bc = new BasicConstraints(isCA); certbuilder.addExtension(Extension.basicConstraints, true, bc); // Put critical KeyUsage in CA-certificates if (isCA || keyusage != 0) { X509KeyUsage ku = new X509KeyUsage(keyusage); certbuilder.addExtension(Extension.keyUsage, true, ku); } if ((privateKeyNotBefore != null) || (privateKeyNotAfter != null)) { final ASN1EncodableVector v = new ASN1EncodableVector(); if (privateKeyNotBefore != null) { v.add(new DERTaggedObject(false, 0, new DERGeneralizedTime(privateKeyNotBefore))); } if (privateKeyNotAfter != null) { v.add(new DERTaggedObject(false, 1, new DERGeneralizedTime(privateKeyNotAfter))); } certbuilder.addExtension(Extension.privateKeyUsagePeriod, false, new DERSequence(v)); } // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Firefox. try { if (isCA) { ASN1InputStream sAsn1InputStream = new ASN1InputStream( new ByteArrayInputStream(publicKey.getEncoded())); ASN1InputStream aAsn1InputStream = new ASN1InputStream( new ByteArrayInputStream(publicKey.getEncoded())); try { SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo( (ASN1Sequence) sAsn1InputStream.readObject()); X509ExtensionUtils x509ExtensionUtils = new BcX509ExtensionUtils(); SubjectKeyIdentifier ski = x509ExtensionUtils.createSubjectKeyIdentifier(spki); SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo( (ASN1Sequence) aAsn1InputStream.readObject()); AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki); certbuilder.addExtension(Extension.subjectKeyIdentifier, false, ski); certbuilder.addExtension(Extension.authorityKeyIdentifier, false, aki); } finally { sAsn1InputStream.close(); aAsn1InputStream.close(); } } } catch (IOException e) { // do nothing } // CertificatePolicies extension if supplied policy ID, always non-critical if (policyId != null) { PolicyInformation pi = new PolicyInformation(new ASN1ObjectIdentifier(policyId)); DERSequence seq = new DERSequence(pi); certbuilder.addExtension(Extension.certificatePolicies, false, seq); } // Add any additional if (additionalExtensions != null) { for (final Extension extension : additionalExtensions) { certbuilder.addExtension(extension.getExtnId(), extension.isCritical(), extension.getParsedValue()); } } final ContentSigner signer = new BufferingContentSigner( new JcaContentSignerBuilder(sigAlg).setProvider(provider).build(privKey), 20480); final X509CertificateHolder certHolder = certbuilder.build(signer); final X509Certificate selfcert = (X509Certificate) CertTools.getCertfromByteArray(certHolder.getEncoded()); return selfcert; }
From source file:org.wso2.carbon.user.core.jdbc.JDBCUserStoreManager.java
/** * This private method returns a saltValue using SecureRandom. * * @return saltValue// w ww. j a va2 s. c om */ private String generateSaltValue() { String saltValue = null; try { SecureRandom secureRandom = SecureRandom.getInstance(UserCoreConstants.SHA_1_PRNG); byte[] bytes = new byte[16]; //secureRandom is automatically seeded by calling nextBytes secureRandom.nextBytes(bytes); saltValue = Base64.encode(bytes); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("SHA1PRNG algorithm could not be found."); } return saltValue; }