List of usage examples for java.security SecureRandom nextBytes
@Override public void nextBytes(byte[] bytes)
From source file:com.github.tojo.session.cookies.SessionInACookieDefaultImpl.java
@Override public CookieValue encode(SessionData sessionData) throws CipherStrategyException { try {/*from w w w . java 2s . c o m*/ // 1. create session id SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG", "SUN"); byte[] sessionId = new byte[SESSION_ID_LENGTH]; secureRandom.nextBytes(sessionId); // 2. prefix session data with the session id byte[] dataWithSessionId = ArrayUtils.addAll(sessionId, sessionData.asBytes()); // 3. calculate the cookie value CookieValue cookieValue = encryptSignAndEncode(dataWithSessionId); // 4. hit timeout strategy timeoutStrategy.issue(sessionData, cookieValue); return cookieValue; } catch (NoSuchAlgorithmException | NoSuchProviderException e) { throw new RuntimeException(e); } }
From source file:org.apache.ws.security.util.WSSecurityUtil.java
/** * Generate a nonce of the given length//from w w w .j av a 2s . c o m * * @return a nonce of the given length * @throws Exception */ public static byte[] generateNonce(int length) throws WSSecurityException { try { final SecureRandom r = resolveSecureRandom(); if (r == null) { throw new WSSecurityException("Random generator is not initialized."); } byte[] temp = new byte[length]; r.nextBytes(temp); return temp; } catch (Exception e) { throw new WSSecurityException("Error in generating nonce of length " + length, e); } }
From source file:org.noroomattheinn.utils.PWUtils.java
public byte[] generateSalt() { // VERY important to use SecureRandom instead of just Random try {/* w ww. jav a2 s .c o m*/ SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); // Generate a 8 byte (64 bit) salt as recommended by RSA PKCS5 byte[] salt = new byte[8]; random.nextBytes(salt); return salt; } catch (NoSuchAlgorithmException ex) { Logger.getLogger(PWUtils.class.getName()).log(Level.SEVERE, null, ex); return null; } }
From source file:com.cloud.server.auth.SHA256SaltedUserAuthenticator.java
@Override public String encode(String password) { // 1. Generate the salt SecureRandom randomGen; try {/*from w ww . j a v a 2s . c o m*/ randomGen = SecureRandom.getInstance("SHA1PRNG"); byte salt[] = new byte[s_saltlen]; randomGen.nextBytes(salt); String saltString = new String(Base64.encode(salt)); String hashString = encode(password, salt); // 3. concatenate the two and return return saltString + ":" + hashString; } catch (NoSuchAlgorithmException e) { throw new CloudRuntimeException("Unable to hash password", e); } catch (UnsupportedEncodingException e) { throw new CloudRuntimeException("Unable to hash password", e); } }
From source file:org.apache.nifi.web.security.otp.OtpService.java
/** * Hashes the specified authentication token. The resulting value will be used as the one time use token. * * @param authenticationToken the authentication token * @return the one time use token *///from w ww .j a v a 2s . c om private String hash(final OtpAuthenticationToken authenticationToken) { try { // input is the user identity and timestamp final String input = authenticationToken.getName() + "-" + System.nanoTime(); // create the secret using secure random final SecureRandom secureRandom = new SecureRandom(); final byte[] randomBytes = new byte[32]; secureRandom.nextBytes(randomBytes); final SecretKeySpec secret = new SecretKeySpec(randomBytes, HMAC_SHA256); // 256 bit // hash the input final Mac hmacSha256 = Mac.getInstance(HMAC_SHA256); hmacSha256.init(secret); final byte[] output = hmacSha256.doFinal(input.getBytes(StandardCharsets.UTF_8)); // return the result as a base 64 string return Base64.encodeBase64URLSafeString(output); } catch (final NoSuchAlgorithmException | InvalidKeyException e) { final String errorMessage = "There was an error generating the OTP"; logger.error(errorMessage, e); throw new IllegalStateException("Unable to generate single use token."); } }
From source file:org.apache.abdera.ext.oauth.OAuthScheme.java
private String generateNonce() throws AuthenticationException { try {//from ww w.ja v a2 s . co m SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); byte[] temp = new byte[NONCE_LENGTH]; sr.nextBytes(temp); String n = new String(Hex.encodeHex(temp)); return n; } catch (Exception e) { throw new AuthenticationException(e.getMessage(), e); } }
From source file:com.romeikat.datamessie.core.base.service.AuthenticationService.java
public byte[] createSalt() { SecureRandom sr; try {//from w ww . j a v a2 s. c o m sr = SecureRandom.getInstance("SHA1PRNG"); final byte[] salt = new byte[512 / 8]; sr.nextBytes(salt); return salt; } catch (final NoSuchAlgorithmException e) { LOG.error("Could not create salt", e); return null; } }
From source file:com.intel.cryptostream.CryptoCodecTest.java
private void cryptoCodecTest(int count, String encCodecClass, String decCodecClass, byte[] iv) throws IOException, GeneralSecurityException { CryptoCodec encCodec = null;/*w w w . java 2 s .c om*/ try { encCodec = (CryptoCodec) ReflectionUtils.newInstance(ReflectionUtils.getClassByName(encCodecClass)); } catch (ClassNotFoundException cnfe) { throw new IOException("Illegal crypto codec!"); } LOG.info("Created a Codec object of type: " + encCodecClass); // Generate data SecureRandom random = new SecureRandom(); byte[] originalData = new byte[count]; byte[] decryptedData = new byte[count]; random.nextBytes(originalData); LOG.info("Generated " + count + " records"); // Encrypt data ByteArrayOutputStream encryptedData = new ByteArrayOutputStream(); CryptoOutputStream out = new CryptoOutputStream(encryptedData, encCodec, bufferSize, key, iv); out.write(originalData, 0, originalData.length); out.flush(); out.close(); LOG.info("Finished encrypting data"); CryptoCodec decCodec = null; try { decCodec = (CryptoCodec) ReflectionUtils.newInstance(ReflectionUtils.getClassByName(decCodecClass)); } catch (ClassNotFoundException cnfe) { throw new IOException("Illegal crypto codec!"); } LOG.info("Created a Codec object of type: " + decCodecClass); // Decrypt data CryptoInputStream in = new CryptoInputStream(new ByteArrayInputStream(encryptedData.toByteArray()), decCodec, bufferSize, key, iv); // Check int remainingToRead = count; int offset = 0; while (remainingToRead > 0) { int n = in.read(decryptedData, offset, decryptedData.length - offset); if (n >= 0) { remainingToRead -= n; offset += n; } } Assert.assertArrayEquals("originalData and decryptedData not equal", originalData, decryptedData); LOG.info("SUCCESS! Completed checking " + count + " records"); }
From source file:org.zuinnote.hadoop.office.format.common.writer.msexcel.internal.EncryptedZipEntrySource.java
public EncryptedZipEntrySource(CipherAlgorithm ca, ChainingMode cm) throws IOException { // generate random key for temporary files if (ca != null) { // encrypted files SecureRandom sr = new SecureRandom(); byte[] iv = new byte[ca.blockSize]; byte[] key = new byte[ca.defaultKeySize / 8]; sr.nextBytes(iv); sr.nextBytes(key);//ww w . j a va 2 s . com SecretKeySpec skeySpec = new SecretKeySpec(key, ca.jceId); this.ca = ca; this.cm = cm; this.ciEncoder = CryptoFunctions.getCipher(skeySpec, ca, cm, iv, Cipher.ENCRYPT_MODE, "PKCS5Padding"); this.ciDecoder = CryptoFunctions.getCipher(skeySpec, ca, cm, iv, Cipher.DECRYPT_MODE, "PKCS5Padding"); } this.closed = false; }
From source file:org.apache.nifi.processors.standard.util.PasswordBasedEncryptor.java
@Override public StreamCallback getEncryptionCallback() throws ProcessException { try {/* w ww .ja v a 2s .c o m*/ byte[] salt = new byte[saltSize]; SecureRandom secureRandom = new SecureRandom(); secureRandom.nextBytes(salt); return new EncryptCallback(salt); } catch (Exception e) { throw new ProcessException(e); } }