List of usage examples for java.security SecureRandom getInstance
public static SecureRandom getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:org.artifactory.security.crypto.CryptoHelper.java
public static KeyPair generateKeyPair() { try {//from w ww .ja v a 2s. c o m KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ASYM_ALGORITHM); SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); keyGen.initialize(512, random); return keyGen.generateKeyPair(); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException("No such algorithm:" + e.getMessage()); } }
From source file:de.widone.services.UserService.java
private byte[] getSalt() { try {//from w ww. j a v a2 s . co m SecureRandom rnd = SecureRandom.getInstance("SHA1PRNG"); byte[] salt = new byte[8]; rnd.nextBytes(salt); return salt; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.xwiki.csrf.internal.DefaultCSRFToken.java
/** * Initializes the storage and random number generator. * /*from w w w. java2 s . c o m*/ * {@inheritDoc} */ @Override public void initialize() throws InitializationException { this.tokens = new ConcurrentHashMap<String, String>(); try { this.random = SecureRandom.getInstance("SHA1PRNG"); } catch (NoSuchAlgorithmException e) { // use the default implementation then this.random = new SecureRandom(); this.logger.warn("CSRFToken: Using default implementation of SecureRandom"); } byte[] seed = this.random.generateSeed(TOKEN_LENGTH); this.random.setSeed(seed); this.logger.debug("CSRFToken: Anti-CSRF secret token component has been initialized"); }
From source file:net.firejack.platform.core.utils.SecurityHelper.java
/** * generate random sequence//from ww w . ja va2 s . c o m * * @param length lengh of sequence to generate * @return Generated random sequence */ public static String generateRandomSequence(int length) { String password = ""; try { SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); for (int i = 0; i < length; i++) { char ch = 0; int j = random.nextInt(3); switch (j) { case 0: ch = (char) (97 + random.nextInt(26)); break; case 1: ch = (char) (65 + random.nextInt(26)); break; case 2: ch = (char) (48 + random.nextInt(10)); break; } password += ch; } } catch (NoSuchAlgorithmException e) { LOGGER.info("Couldn't create new instance of SecureRandom class", e); throw new RuntimeException(e); } return password; }
From source file:com.mastercard.mcbp.utils.crypto.CryptoServiceImpl.java
/** * {@inheritDoc}//from ww w.ja va 2 s.c o m */ @Override public final byte[] getRandom(final int size) { byte[] randomVector = new byte[size]; try { SecureRandom s = SecureRandom.getInstance("SHA1PRNG"); s.nextBytes(new byte[1]); // force seed s.nextBytes(randomVector); } catch (NoSuchAlgorithmException e) { new Random().nextBytes(randomVector); } return randomVector; }
From source file:com.sonicle.webtop.core.util.IdentifierUtils.java
/** * @deprecated use com.sonicle.commons.IdentifierUtils.generateSecretKey instead * @return/*from ww w. ja va 2 s . c o m*/ */ @Deprecated public static synchronized String generateSecretKey() { try { byte[] buffer = new byte[80 / 8]; SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); sr.nextBytes(buffer); byte[] secretKey = Arrays.copyOf(buffer, 80 / 8); byte[] encodedKey = new Base32().encode(secretKey); return new String(encodedKey).toLowerCase(); } catch (NoSuchAlgorithmException ex) { return null; } }
From source file:org.owasp.benchmark.score.BenchmarkScore.java
public static void main(String[] args) { if (args == null || args.length < 2) { System.out.println(usageNotice); System.exit(-1);//from w w w .j a v a2 s . c o m } if (args.length > 2) { focus = args[2].replace(' ', '_'); } if (args.length > 3) { if ("anonymous".equalsIgnoreCase(args[3])) { anonymousMode = true; } else if ("show_ave_only".equalsIgnoreCase(args[3])) { showAveOnlyMode = true; } else { System.out.println(usageNotice); System.exit(-1); } } // Prepare the scorecard results directory for the newly generated scorecards // Step 1: Create the dir if it doesn't exist, or delete everything in it if it does File scoreCardDir = new File(scoreCardDirName); try { if (!scoreCardDir.exists()) { Files.createDirectories(Paths.get(scoreCardDirName)); } else { System.out.println( "Deleting previously generated scorecard files in: " + scoreCardDir.getAbsolutePath()); FileUtils.cleanDirectory(scoreCardDir); } // Step 2: Now copy the entire /content directory, that either didn't exist, or was just deleted with everything else File dest1 = new File(scoreCardDirName + File.separator + "content"); FileUtils.copyDirectory(new File(pathToScorecardResources + "content"), dest1); } catch (IOException e) { System.out.println("Error dealing with scorecard directory: '" + scoreCardDir.getAbsolutePath() + "' for some reason!"); e.printStackTrace(); } // Step 3: Copy over the Homepage and Guide templates try { Files.copy(Paths.get(pathToScorecardResources + HOMEFILENAME), Paths.get(scoreCardDirName + "/" + HOMEFILENAME), StandardCopyOption.REPLACE_EXISTING); Files.copy(Paths.get(pathToScorecardResources + GUIDEFILENAME), Paths.get(scoreCardDirName + "/" + GUIDEFILENAME), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { System.out.println("Problem copying home and guide files"); e.printStackTrace(); } // Step 4: Read the expected results so we know what each tool 'should do' try { if ("mixed".equalsIgnoreCase(args[0])) { mixedMode = true; // Tells anyone that cares that we aren't processing a single version of Benchmark results File f = new File(args[1]); if (!f.exists()) { System.out.println("Error! - results directory: '" + f.getAbsolutePath() + "' doesn't exist."); System.exit(-1); } if (!f.isDirectory()) { System.out.println("Error! - results parameter is a file: '" + f.getAbsolutePath() + "' but must be a directory when processing results in 'mixed' mode."); System.exit(-1); } // Go through each file in the root directory. // -- 1st find each directory. And then within each of those directories: // -- 1st find the expected results file in that directory // -- and then each of the actual results files in that directory for (File rootDirFile : f.listFiles()) { if (rootDirFile.isDirectory()) { // Process this directory TestResults expectedResults = null; String expectedResultsFilename = null; // Step 4a: Find and process the expected results file so we know what each tool in this directory 'should do' for (File resultsDirFile : rootDirFile.listFiles()) { if (resultsDirFile.getName().startsWith("expectedresults-")) { if (expectedResults != null) { System.out.println("Found 2nd expected results file " + resultsDirFile.getAbsolutePath() + " in same directory. Can only have 1 in each results directory"); System.exit(-1); } // read in the expected results for this directory of results expectedResults = readExpectedResults(resultsDirFile); if (expectedResults == null) { System.out.println("Couldn't read expected results file: " + resultsDirFile.getAbsolutePath()); System.exit(-1); } // end if expectedResultsFilename = resultsDirFile.getName(); if (benchmarkVersion == null) { benchmarkVersion = expectedResults.getBenchmarkVersion(); } else benchmarkVersion += "," + expectedResults.getBenchmarkVersion(); System.out.println( "\nFound expected results file: " + resultsDirFile.getAbsolutePath()); } // end if } // end for loop going through each file looking for expected results file // Make sure we found an expected results file, before processing the results if (expectedResults == null) { System.out.println("Couldn't find expected results file in results directory: " + rootDirFile.getAbsolutePath()); System.out.println( "Expected results file has to be a .csv file that starts with: 'expectedresults-'"); System.exit(-1); } // Step 5a: Go through each result file and generate a scorecard for that tool. if (!anonymousMode) { for (File actual : rootDirFile.listFiles()) { // Don't confuse the expected results file as an actual results file if its in the same directory if (!actual.isDirectory() && !expectedResultsFilename.equals(actual.getName())) process(actual, expectedResults, toolResults); } } else { // To handle anonymous mode, we are going to randomly grab files out of this directory // and process them. By doing it this way, multiple runs should randomly order the commercial // tools each time. List<File> files = new ArrayList(); for (File file : rootDirFile.listFiles()) { files.add(file); } SecureRandom generator = SecureRandom.getInstance("SHA1PRNG"); while (files.size() > 0) { // Get a random, positive integer int fileToGet = Math.abs(generator.nextInt(files.size())); File actual = files.remove(fileToGet); // Don't confuse the expected results file as an actual results file if its in the same directory if (!actual.isDirectory() && !expectedResultsFilename.equals(actual.getName())) process(actual, expectedResults, toolResults); } } } // end if a directory } // end for loop through all files in the directory // process the results the normal way with a single results directory } else { // Step 4b: Read the expected results so we know what each tool 'should do' File expected = new File(args[0]); TestResults expectedResults = readExpectedResults(expected); if (expectedResults == null) { System.out.println("Couldn't read expected results file: " + expected); System.exit(-1); } else { System.out.println("Read expected results from file: " + expected.getAbsolutePath()); int totalResults = expectedResults.totalResults(); if (totalResults != 0) { System.out.println(totalResults + " results found."); benchmarkVersion = expectedResults.getBenchmarkVersion(); } else { System.out.println("Error! - zero expected results found in results file."); System.exit(-1); } } // Step 5b: Go through each result file and generate a scorecard for that tool. File f = new File(args[1]); if (!f.exists()) { System.out.println("Error! - results file: '" + f.getAbsolutePath() + "' doesn't exist."); System.exit(-1); } if (f.isDirectory()) { if (!anonymousMode) { for (File actual : f.listFiles()) { // Don't confuse the expected results file as an actual results file if its in the same directory if (!actual.isDirectory() && !expected.getName().equals(actual.getName())) process(actual, expectedResults, toolResults); } } else { // To handle anonymous mode, we are going to randomly grab files out of this directory // and process them. By doing it this way, multiple runs should randomly order the commercial // tools each time. List<File> files = new ArrayList(); for (File file : f.listFiles()) { files.add(file); } SecureRandom generator = SecureRandom.getInstance("SHA1PRNG"); while (files.size() > 0) { int randomNum = generator.nextInt(); // FIXME: Get Absolute Value better if (randomNum < 0) randomNum *= -1; int fileToGet = randomNum % files.size(); File actual = files.remove(fileToGet); // Don't confuse the expected results file as an actual results file if its in the same directory if (!actual.isDirectory() && !expected.getName().equals(actual.getName())) process(actual, expectedResults, toolResults); } } } else { // This will process a single results file, if that is what the 2nd parameter points to. // This has never been used. process(f, expectedResults, toolResults); } } // end else System.out.println("Tool scorecards computed."); } catch (Exception e) { System.out.println("Error during processing: " + e.getMessage()); e.printStackTrace(); } // Step 6: Now generate scorecards for each type of vulnerability across all the tools // First, we have to figure out the list of vulnerabilities // A set is used here to eliminate duplicate categories across all the results Set<String> catSet = new TreeSet<String>(); for (Report toolReport : toolResults) { catSet.addAll(toolReport.getOverallResults().getCategories()); } // Then we generate each vulnerability scorecard BenchmarkScore.generateVulnerabilityScorecards(toolResults, catSet); System.out.println("Vulnerability scorecards computed."); // Step 7: Update all the menus for all the generated pages to reflect the tools and vulnerability categories updateMenus(toolResults, catSet); // Step 8: Generate the overall comparison chart for all the tools in this test ScatterHome.generateComparisonChart(toolResults, focus); // Step 9: Generate the results table across all the tools in this test String table = generateOverallStatsTable(toolResults); File f = Paths.get(scoreCardDirName + "/" + HOMEFILENAME).toFile(); try { String html = new String(Files.readAllBytes(f.toPath())); html = html.replace("${table}", table); Files.write(f.toPath(), html.getBytes()); } catch (IOException e) { System.out.println("Error updating results table in: " + f.getName()); e.printStackTrace(); } System.out.println("Benchmark scorecards complete."); System.exit(0); }
From source file:org.opencms.security.CmsDefaultPasswordHandler.java
/** * @see org.opencms.security.I_CmsPasswordHandler#digest(java.lang.String, java.lang.String, java.lang.String) *//*from w ww. ja v a 2 s . c o m*/ public String digest(String password, String digestType, String inputEncoding) throws CmsPasswordEncryptionException { MessageDigest md; String result; try { if (DIGEST_TYPE_PLAIN.equals(digestType.toLowerCase())) { result = password; } else if (DIGEST_TYPE_SSHA.equals(digestType.toLowerCase())) { byte[] salt = new byte[4]; byte[] digest; byte[] total; if (m_secureRandom == null) { m_secureRandom = SecureRandom.getInstance("SHA1PRNG"); } m_secureRandom.nextBytes(salt); md = MessageDigest.getInstance(DIGEST_TYPE_SHA); md.reset(); md.update(password.getBytes(inputEncoding)); md.update(salt); digest = md.digest(); total = new byte[digest.length + salt.length]; System.arraycopy(digest, 0, total, 0, digest.length); System.arraycopy(salt, 0, total, digest.length, salt.length); result = new String(Base64.encodeBase64(total)); } else { md = MessageDigest.getInstance(digestType); md.reset(); md.update(password.getBytes(inputEncoding)); result = new String(Base64.encodeBase64(md.digest())); } } catch (NoSuchAlgorithmException e) { CmsMessageContainer message = Messages.get().container(Messages.ERR_UNSUPPORTED_ALGORITHM_1, digestType); if (LOG.isErrorEnabled()) { LOG.error(message.key(), e); } throw new CmsPasswordEncryptionException(message, e); } catch (UnsupportedEncodingException e) { CmsMessageContainer message = Messages.get().container(Messages.ERR_UNSUPPORTED_PASSWORD_ENCODING_1, inputEncoding); if (LOG.isErrorEnabled()) { LOG.error(message.key(), e); } throw new CmsPasswordEncryptionException(message, e); } return result; }
From source file:org.wso2.carbon.identity.sso.saml.builders.ArtifactMessageBuilder.java
/** * Build the SAML V2.0 Artifact type of Type Code 0x0004 * Artifact length : 44 bytes/*from w ww .j av a2 s. c o m*/ * * SAML V2.0 defines an artifact type of type code 0x0004 * Identification:urn:oasis:names:tc:SAML:2.0:artifact-04 * * SAML_artifact := B64(TypeCode EndpointIndex RemainingArtifact) * TypeCode := Byte1Byte2 * EndpointIndex := Byte1Byte2 * * TypeCode := 0x0004 * RemainingArtifact := SourceID MessageHandle * SourceID := 20-byte_sequence * MessageHandle := 20-byte_sequence * * @return SAML V2.0 Artifact type of Type Code 0x0004 */ // TODO use Interface type as the return type public SAML2ArtifactType0004 buildArtifact() throws IdentityException { try { String issuerID = SAMLSSOUtil.getIssuer().getValue(); int assertionConsumerServiceIndex = 0x0000; byte[] endpointIndex = DatatypeHelper.intToByteArray(assertionConsumerServiceIndex); byte[] trimmedIndex = new byte[2]; trimmedIndex[0] = endpointIndex[2]; trimmedIndex[1] = endpointIndex[3]; MessageDigest sha1Digester = MessageDigest.getInstance("SHA-1"); byte[] sourceID = sha1Digester.digest(issuerID.getBytes()); // TODO trim/pad as necessary to make sourceID 20 bytes SecureRandom handleGenerator = SecureRandom.getInstance("SHA1PRNG"); byte[] messageHandle; messageHandle = new byte[20]; handleGenerator.nextBytes(messageHandle); return new SAML2ArtifactType0004(trimmedIndex, sourceID, messageHandle); } catch (NoSuchAlgorithmException e) { log.error("JVM does not support required cryptography algorithms: SHA-1/SHA1PRNG.", e); throw new InternalError("JVM does not support required cryptography algorithms: SHA-1/SHA1PRNG."); } }
From source file:net.sf.gazpachoquest.rest.auth.TokenStore.java
/** * @throws NoSuchAlgorithmException/*w ww. j ava 2s . co m*/ * @throws InvalidKeyException * @throws UnsupportedEncodingException * @throws IllegalStateException * @throws NullPointerException if <code>tokenFile</code> is * <code>null</code>. */ TokenStore(final File tokenFile, final long sessionTimeout, final boolean fastSeed) throws NoSuchAlgorithmException, InvalidKeyException, IllegalStateException, UnsupportedEncodingException { if (tokenFile == null) { throw new NullPointerException("tokenfile"); } this.random = SecureRandom.getInstance(SHA1PRNG); this.ttl = sessionTimeout; this.tokenFile = tokenFile; this.tmpTokenFile = new File(tokenFile + ".tmp"); // prime the secret keys from persistence loadTokens(); // warm up the crypto API if (fastSeed) { random.setSeed(getFastEntropy()); } else { log.info("Seeding the secure random number generator can take " + "up to several minutes on some operating systems depending " + "upon environment factors. If this is a problem for you, " + "set the system property 'java.security.egd' to " + "'file:/dev/./urandom' or enable the Fast Seed Generator " + "in the Web Console"); } byte[] b = new byte[20]; random.nextBytes(b); final SecretKey secretKey = new SecretKeySpec(b, HMAC_SHA1); final Mac m = Mac.getInstance(HMAC_SHA1); m.init(secretKey); m.update(UTF_8.getBytes(UTF_8)); m.doFinal(); }