List of usage examples for java.security SecureRandom getInstance
public static SecureRandom getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:org.cesecore.certificates.ca.internal.SernoGeneratorRandom.java
private void init() { // Init random number generator for random serial numbers. // SecureRandom provides a cryptographically strong random number generator (RNG). try {/*from w w w .jav a 2 s.c om*/ // Use a specified algorithm if ca.rngalgorithm is provided and it's not set to default if (!StringUtils.isEmpty(algorithm) && !StringUtils.containsIgnoreCase(algorithm, "default")) { random = SecureRandom.getInstance(algorithm); log.info("Using " + algorithm + " serialNumber RNG algorithm."); } else if (!StringUtils.isEmpty(algorithm) && StringUtils.equalsIgnoreCase(algorithm, "defaultstrong")) { // If defaultstrong is specified and we use >=JDK8 try the getInstanceStrong to get a guaranteed strong random number generator. // Note that this may give you a generator that takes >30 seconds to create a single random number. // On JDK8/Linux this gives you a NativePRNGBlocking, while SecureRandom.getInstance() gives a NativePRNG. try { final Method methodGetInstanceStrong = SecureRandom.class .getDeclaredMethod("getInstanceStrong"); random = (SecureRandom) methodGetInstanceStrong.invoke(null); log.info("Using SecureRandom.getInstanceStrong() with " + random.getAlgorithm() + " for serialNumber RNG algorithm."); } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new IllegalStateException( "SecureRandom.getInstanceStrong() is not available or failed invocation. (This method was added in Java 8.)"); } } else if (!StringUtils.isEmpty(algorithm) && StringUtils.equalsIgnoreCase(algorithm, "default")) { // We entered "default" so let's use a good default SecureRandom this should be good enough for just about everyone (on Linux at least) // On Linux the default Java implementation uses the (secure) /dev/(u)random, but on windows something else // On JDK8/Linux this gives you a NativePRNG, while SecureRandom.getInstanceStrong() gives a NativePRNGBlocking. random = new SecureRandom(); log.info("Using default " + random.getAlgorithm() + " serialNumber RNG algorithm."); } } catch (NoSuchAlgorithmException e) { //This state is unrecoverable, and since algorithm is set in configuration requires a redeploy to handle throw new IllegalStateException("Algorithm " + algorithm + " was not a valid algorithm.", e); } if (random == null) { //This state is unrecoverable, and since algorithm is set in configuration requires a redeploy to handle throw new IllegalStateException("Algorithm " + algorithm + " was not a valid algorithm."); } // Call nextBytes directly after in order to force seeding if not already done. SecureRandom typically seeds on first call. random.nextBytes(new byte[20]); }
From source file:org.ejbca.extra.ra.ScepRAServlet.java
/** * Inits the SCEP Servlet/*www .j av a2 s. c o m*/ * * @param config Servlet configuration * * @throws ServletException on error during initialization */ public void init(ServletConfig config) throws ServletException { super.init(config); try { // Initialize configuration, not really needed but it prints some debug info that might // be interesting. ExtraConfiguration.instance(); // Install BouncyCastle provider log.debug("Re-installing BC-provider"); CryptoProviderTools.removeBCProvider(); CryptoProviderTools.installBCProvider(); cryptProvider = getInitParameter("cryptProvider"); keyStoreNumber = "." + getInitParameter("keyStoreNumber"); String kspath = ExtraConfiguration.instance() .getString(ExtraConfiguration.SCEPKEYSTOREPATH + keyStoreNumber); String kspwd = ExtraConfiguration.instance() .getString(ExtraConfiguration.SCEPKEYSTOREPWD + keyStoreNumber); scepraks = new RAKeyStore(kspath, kspwd); String randomAlgorithm = "SHA1PRNG"; randomSource = SecureRandom.getInstance(randomAlgorithm); msgHome = new MessageHome(Persistence.createEntityManagerFactory("ScepRAMessageDS"), MessageHome.MESSAGETYPE_SCEPRA, true); //false); } catch (Exception e) { throw new ServletException(e); } }
From source file:wssec.TestWSSecurityNewSCT.java
/** * Test encryption using a derived key which is based on a secret associated * with a security context token// w w w .j a v a2 s . c o m */ public void testSCTDKTEncrypt() { try { SOAPEnvelope unsignedEnvelope = message.getSOAPEnvelope(); Document doc = unsignedEnvelope.getAsDocument(); WSSecHeader secHeader = new WSSecHeader(); secHeader.insertSecurityHeader(doc); WSSecSecurityContextToken sctBuilder = new WSSecSecurityContextToken(); sctBuilder.prepare(doc, crypto); SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); byte[] tempSecret = new byte[16]; random.nextBytes(tempSecret); // Store the secret this.secrets.put(sctBuilder.getIdentifier(), tempSecret); String tokenId = sctBuilder.getSctId(); // Derived key encryption WSSecDKEncrypt encrBuilder = new WSSecDKEncrypt(); encrBuilder.setSymmetricEncAlgorithm(WSConstants.AES_128); encrBuilder.setExternalKey(tempSecret, tokenId); encrBuilder.build(doc, secHeader); sctBuilder.prependSCTElementToHeader(doc, secHeader); if (LOG.isDebugEnabled()) { String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(doc); LOG.debug(outputString); } verify(doc); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } }
From source file:org.opensafety.hishare.util.implementation.EncryptionImpl.java
public byte[] createSalt() throws CryptographyException { SecureRandom random;/*from w ww . java 2s. c o m*/ try { random = SecureRandom.getInstance(randomAlgorithm); } catch (NoSuchAlgorithmException e) { throw new CryptographyException(e.getMessage()); } byte[] salt = new byte[saltLength]; random.nextBytes(salt); return salt; }
From source file:com.qut.middleware.crypto.impl.CryptoProcessorImpl.java
public String generatePassphrase() { SecureRandom random;//ww w . j a va2s.co m String passphrase; byte[] buf; try { /* Attempt to get the specified RNG instance */ random = SecureRandom.getInstance("SHA1PRNG"); } catch (NoSuchAlgorithmException nsae) { random = new SecureRandom(); } buf = new byte[10]; random.nextBytes(buf); passphrase = new String(Hex.encodeHex(buf)); return passphrase; }
From source file:org.everit.password.encryptor.pbkdf2.PBKDF2PasswordEncryptorImpl.java
private byte[] generateSalt() throws NoSuchAlgorithmException { // VERY important to use SecureRandom instead of just Random SecureRandom random;// w ww . j a v a2 s .com random = SecureRandom.getInstance(SALT_ALGORITHM); // Generate a 8 byte (64 bit) salt as recommended by RSA PKCS5 byte[] salt = new byte[SALT_BYTE]; random.nextBytes(salt); return salt; }
From source file:edu.internet2.middleware.shibboleth.idp.system.conf1.SAML2ArtifactResolutionTest.java
@SuppressWarnings("unchecked") protected SAMLArtifactMapEntry stageArtifact(String relyingPartyId) throws Exception { SAMLObjectBuilder<Assertion> assetionBuilder = (SAMLObjectBuilder<Assertion>) builderFactory .getBuilder(Assertion.DEFAULT_ELEMENT_NAME); Assertion assertion = assetionBuilder.buildObject(); SAMLObjectBuilder<Response> responseBuilder = (SAMLObjectBuilder<Response>) builderFactory .getBuilder(Response.DEFAULT_ELEMENT_NAME); Response response = responseBuilder.buildObject(); response.getAssertions().add(assertion); SecureRandom handleGenerator = SecureRandom.getInstance("SHA1PRNG"); byte[] endpointIndex = { 0, 1 }; MessageDigest sha1Digester = MessageDigest.getInstance("SHA-1"); byte[] source = sha1Digester.digest(relyingPartyId.getBytes()); byte[] assertionHandle = new byte[20]; handleGenerator.nextBytes(assertionHandle); SAML2ArtifactType0004 artifact = new SAML2ArtifactType0004(endpointIndex, source, assertionHandle); SAMLArtifactMap artifactMap = (SAMLArtifactMap) getApplicationContext().getBean("shibboleth.ArtifactMap"); artifactMap.put(artifact.base64Encode(), relyingPartyId, "urn:example.org:idp1", response); return artifactMap.get(artifact.base64Encode()); }
From source file:com.floragunn.searchguard.service.SearchGuardService.java
@Inject public SearchGuardService(final Settings settings, final RestController restController, final Client client, final Authorizator authorizator, final AuthenticationBackend authenticationBackend, final HTTPAuthenticator httpAuthenticator, final SessionStore sessionStore, final AuditListener auditListener, final SearchService searchService) { super(settings); this.restController = restController; this.client = client; this.settings = settings; //securityConfigurationIndex = settings // .get(ConfigConstants.SEARCHGUARD_CONFIG_INDEX_NAME, ConfigConstants.DEFAULT_SECURITY_CONFIG_INDEX); this.authenticationBackend = authenticationBackend; this.authorizator = authorizator; this.httpAuthenticator = httpAuthenticator; this.sessionStore = sessionStore; try {/*w ww . ja v a 2s . c o m*/ method = RestController.class.getDeclaredMethod("getHandler", RestRequest.class); method.setAccessible(true); } catch (final Exception e) { log.error(e.toString(), e); throw new ElasticsearchException(e.toString()); } try { searchServiceSetCallbackMethod = SearchService.class.getDeclaredMethod("setCallback", SearchContextCallback.class); searchServiceSetCallbackMethod.invoke(searchService, new ConfigurableSearchContextCallback(settings, auditListener)); } catch (final Exception e) { log.error(e.toString(), e); //throw new ElasticsearchException(e.toString()); } this.auditListener = auditListener; //TODO FUTURE index change audit trail final String keyPath = settings.get(ConfigConstants.SEARCHGUARD_KEY_PATH, "."); SecretKey sc = null; try { final File keyFile = new File(keyPath, "searchguard_node_key.key"); if (keyFile.exists()) { log.debug("Loaded key from {}", keyFile.getAbsolutePath()); sc = new SecretKeySpec(FileUtils.readFileToByteArray(keyFile), "AES"); } else { final SecureRandom secRandom = SecureRandom.getInstance("SHA1PRNG"); final KeyGenerator kg = KeyGenerator.getInstance("AES"); kg.init(128, secRandom); final SecretKey secretKey = kg.generateKey(); final byte[] enckey = secretKey.getEncoded(); if (enckey == null || enckey.length != 16) { throw new Exception("invalid key " + (enckey == null ? -1 : enckey.length)); } FileUtils.writeByteArrayToFile(keyFile, enckey); sc = secretKey; log.info("New key written to {}, make sure all nodes have this key", keyFile.getAbsolutePath()); } } catch (final Exception e) { log.error("Cannot generate or read secrety key", e); throw new ElasticsearchException(e.toString()); } final boolean checkForRoot = settings.getAsBoolean(ConfigConstants.SEARCHGUARD_CHECK_FOR_ROOT, true); if (SecurityUtil.isRootUser()) { if (checkForRoot) { throw new ElasticsearchException( "You're trying to run elasticsearch as root or Windows Administrator and thats forbidden."); } else { log.warn( "You're trying to run elasticsearch as root or Windows Administrator! Thats a potential security issue."); } } /*final String scriptingStatus = settings.get(ScriptService.DISABLE_DYNAMIC_SCRIPTING_SETTING, ScriptService.DISABLE_DYNAMIC_SCRIPTING_DEFAULT); if (scriptingStatus.equalsIgnoreCase(ScriptService.DISABLE_DYNAMIC_SCRIPTING_DEFAULT)) { log.warn("{} has the default value {}, consider setting it to false if not needed", ScriptService.DISABLE_DYNAMIC_SCRIPTING_SETTING, scriptingStatus); } if (scriptingStatus.equalsIgnoreCase("true")) { log.error("{} is configured insecure, consider setting it to false or " + ScriptService.DISABLE_DYNAMIC_SCRIPTING_DEFAULT, ScriptService.DISABLE_DYNAMIC_SCRIPTING_SETTING); }*/ if (searchService == null) { throw new RuntimeException("ssnull"); } SearchGuardService.secretKey = sc; }
From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.transport.TransportUtils.java
/** * Attempts to find a free port between the MIN_PORT_NUMBER(9000) and MAX_PORT_NUMBER(11000). * Tries 'RANDOMLY picked' port numbers between this range up-until "randomAttempts" number of * times. If still fails, then tries each port in descending order from the MAX_PORT_NUMBER * whilst skipping already attempted ones via random selection. * * @param randomAttempts no of times to TEST port numbers picked randomly over the given range * @return an available/free port//from ww w .j ava 2 s . c o m */ public static synchronized int getAvailablePort(int randomAttempts) { ArrayList<Integer> failedPorts = new ArrayList<Integer>(randomAttempts); try { SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); int randomPort = MAX_PORT_NUMBER; while (randomAttempts > 0) { randomPort = secureRandom.nextInt(MAX_PORT_NUMBER - MIN_PORT_NUMBER) + MIN_PORT_NUMBER; if (checkIfPortAvailable(randomPort)) { return randomPort; } failedPorts.add(randomPort); randomAttempts--; } randomPort = MAX_PORT_NUMBER; while (true) { if (!failedPorts.contains(randomPort) && checkIfPortAvailable(randomPort)) { return randomPort; } randomPort--; } } catch (NoSuchAlgorithmException e) { throw new RuntimeException("SHA1PRNG algorithm could not be found."); } }
From source file:com.petalmd.armor.service.ArmorService.java
@Inject public ArmorService(final Settings settings, final RestController restController, final Client client, final Authorizator authorizator, final AuthenticationBackend authenticationBackend, final HTTPAuthenticator httpAuthenticator, final SessionStore sessionStore, final AuditListener auditListener, final SearchService searchService) { super(settings); this.restController = restController; this.client = client; this.settings = settings; //securityConfigurationIndex = settings // .get(ConfigConstants.ARMOR_CONFIG_INDEX_NAME, ConfigConstants.DEFAULT_SECURITY_CONFIG_INDEX); this.authenticationBackend = authenticationBackend; this.authorizator = authorizator; this.httpAuthenticator = httpAuthenticator; this.sessionStore = sessionStore; SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new SpecialPermission()); }//from ww w .j ava 2 s . com try { AccessController.doPrivileged(new PrivilegedExceptionAction<Boolean>() { @Override public Boolean run() throws Exception { method = RestController.class.getDeclaredMethod("getHandler", RestRequest.class); method.setAccessible(true); return true; } }); } catch (final Exception e) { log.error(e.toString(), e); throw new ElasticsearchException(e.toString()); } final String keyPath = settings.get(ConfigConstants.ARMOR_KEY_PATH, "."); // AccessController.checkPermission(new FilePermission(keyPath+File.separator+"armor_node_key.key", "write")); SecretKey sc = null; try { sc = AccessController.doPrivileged(new PrivilegedExceptionAction<SecretKey>() { @Override public SecretKey run() throws Exception { final File keyFile = new File(keyPath, "armor_node_key.key"); SecretKey sc = null; if (keyFile.exists()) { log.debug("Loaded key from {}", keyFile.getAbsolutePath()); sc = new SecretKeySpec(FileUtils.readFileToByteArray(keyFile), "AES"); } else { final SecureRandom secRandom = SecureRandom.getInstance("SHA1PRNG"); final KeyGenerator kg = KeyGenerator.getInstance("AES"); kg.init(128, secRandom); final SecretKey secretKey = kg.generateKey(); final byte[] enckey = secretKey.getEncoded(); if (enckey == null || enckey.length != 16) { throw new Exception("invalid key " + (enckey == null ? -1 : enckey.length)); } FileUtils.writeByteArrayToFile(keyFile, enckey); sc = secretKey; log.info("New key written to {}, make sure all nodes have this key", keyFile.getAbsolutePath()); } return sc; } }); } catch (final Exception e) { log.error("Cannot generate or read secrety key", e); throw new ElasticsearchException(e.toString()); } this.auditListener = auditListener; //TODO FUTURE index change audit trail final boolean checkForRoot = settings.getAsBoolean(ConfigConstants.ARMOR_CHECK_FOR_ROOT, true); if (SecurityUtil.isRootUser()) { if (checkForRoot) { throw new ElasticsearchException( "You're trying to run elasticsearch as root or Windows Administrator and thats forbidden."); } else { log.warn( "You're trying to run elasticsearch as root or Windows Administrator! Thats a potential security issue."); } } /*final String scriptingStatus = settings.get(ScriptService.DISABLE_DYNAMIC_SCRIPTING_SETTING, ScriptService.DISABLE_DYNAMIC_SCRIPTING_DEFAULT); if (scriptingStatus.equalsIgnoreCase(ScriptService.DISABLE_DYNAMIC_SCRIPTING_DEFAULT)) { log.warn("{} has the default value {}, consider setting it to false if not needed", ScriptService.DISABLE_DYNAMIC_SCRIPTING_SETTING, scriptingStatus); } if (scriptingStatus.equalsIgnoreCase("true")) { log.error("{} is configured insecure, consider setting it to false or " + ScriptService.DISABLE_DYNAMIC_SCRIPTING_DEFAULT, ScriptService.DISABLE_DYNAMIC_SCRIPTING_SETTING); }*/ if (searchService == null) { throw new RuntimeException("ssnull"); } ArmorService.secretKey = sc; }