List of usage examples for java.security SecureRandom nextBytes
@Override public void nextBytes(byte[] bytes)
From source file:com.azaptree.services.security.domain.config.impl.HashServiceConfig.java
@Override public HashService getHashService() { if (hashService != null) { return hashService; }//from w w w . jav a2 s . c om final DefaultHashService service = new DefaultHashService(); service.setGeneratePublicSalt(true); service.setPrivateSalt(ByteSource.Util.bytes(privateSalt)); service.setHashAlgorithmName(hashAlgorithmName); service.setHashIterations(hashIterations); final SecureRandomNumberGenerator rng = new SecureRandomNumberGenerator(); rng.setDefaultNextBytesSize(secureRandomNumberGeneratorNextBytesSize); final SecureRandom random = new SecureRandom(); final byte rngSeed[] = new byte[20]; random.nextBytes(rngSeed); rng.setSeed(rngSeed); service.setRandomNumberGenerator(rng); hashService = service; return service; }
From source file:plbtw.klmpk.barang.hilang.controller.DeveloperController.java
@RequestMapping(method = RequestMethod.PUT, produces = "application/json") public CustomResponseMessage updateDeveloper(@RequestBody DeveloperRequest developerRequest) { try {//w w w . ja v a2 s . c o m Developer developerUpdate = developerService.getDeveloper(developerRequest.getIdDeveloper()); SecureRandom random = new SecureRandom(); byte bytes[] = new byte[20]; random.nextBytes(bytes); String token = bytes.toString(); developerUpdate.setToken(token); developerUpdate.setEmail(developerRequest.getEmail()); developerUpdate.setPassword(developerRequest.getPassword()); developerService.updateDeveloper(developerUpdate); return new CustomResponseMessage(HttpStatus.CREATED, "Update Developer successfuly"); } catch (Exception ex) { return new CustomResponseMessage(HttpStatus.BAD_REQUEST, ex.toString()); } }
From source file:com.cfs.util.AESCriptografia.java
public String gerarSalt() { /* Tamanho do buffer do Salt */ final int SALT_LENGTH = 16; /* Criao do buffer do Salt */ byte[] salt = new byte[SALT_LENGTH]; /* Criao do gerador de Salt */ SecureRandom aleatorio = new SecureRandom(); /* Gerao de um Salt aleatrio */ aleatorio.nextBytes(salt); /* Encoda o salt gerado */ String retorno = Base64.encodeBase64String(salt); /* Retorna o salt gerado */ return retorno; }
From source file:org.gluu.com.ox_push2.u2f.v2.cert.KeyPairGeneratorImpl.java
@Override public byte[] generateKeyHandle() { SecureRandom random = new SecureRandom(); byte[] keyHandle = new byte[64]; random.nextBytes(keyHandle); return keyHandle; }
From source file:ubicrypt.core.UtilsTest.java
@Test public void readIs() throws Exception { final SecureRandom rnd = new SecureRandom(); rnd.setSeed(System.currentTimeMillis()); final byte[] key = new byte[3 * (1 << 16)]; rnd.nextBytes(key); final Path path = Files.createTempFile(TestUtils.tmp, "a", "b"); Utils.write(path, new ByteArrayInputStream(key)).toBlocking().last(); final byte[] bytes = IOUtils.toByteArray(Utils.readIs(path)); final byte[] bytes2 = IOUtils.toByteArray(Files.newInputStream(path)); assertThat(bytes.length).isEqualTo(bytes2.length); for (int i = 0; i < bytes.length; i++) { assertThat(bytes[i]).isEqualTo(bytes2[i]); }//w ww .j av a 2 s . co m }
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// w w w .ja v a 2s . 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:com.github.mrstampy.gameboot.security.SecurityConfiguration.java
/** * Secure random./*from w w w . ja v a2s . c om*/ * * @return the secure random * @throws Exception * the exception */ @Bean(name = GAME_BOOT_SECURE_RANDOM) public SecureRandom secureRandom() throws Exception { SecureRandom random = isEmpty(algorithm) ? SecureRandom.getInstanceStrong() : SecureRandom.getInstance(algorithm); byte[] seed = new byte[seedSize]; random.nextBytes(seed); return random; }
From source file:com.fegor.alfresco.security.crypto.Crypto.java
/** * Encryption configuration// w w w.j ava 2 s. c o m * * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException * @throws NoSuchPaddingException * @throws InvalidParameterSpecException * @throws IllegalBlockSizeException * @throws BadPaddingException * @throws UnsupportedEncodingException * @throws InvalidKeyException */ public void configEncrypt() throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, InvalidKeyException { SecretKeyFactory factory = null; SecretKey tmp = null; salt_pos = new byte[SALT_LEN]; SecureRandom rnd = new SecureRandom(); rnd.nextBytes(salt_pos); if (logger.isDebugEnabled()) logger.debug(this.getClass().getName() + ": [salt: " + (new String(Hex.encodeHex(salt_pos))) + "]"); factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); /* * http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files * .shtml */ KeySpec spec = new PBEKeySpec(password.toCharArray(), salt_pos, ITERATIONS, KEYLEN_BITS); tmp = factory.generateSecret(spec); SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES"); eCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); eCipher.init(Cipher.ENCRYPT_MODE, secret); AlgorithmParameters params = eCipher.getParameters(); vector_init = params.getParameterSpec(IvParameterSpec.class).getIV(); if (logger.isDebugEnabled()) logger.debug( this.getClass().getName() + ": [vector ini: " + (new String(Hex.encodeHex(vector_init))) + "]"); }
From source file:org.apache.geronimo.crypto.ConfiguredEncryption.java
public ConfiguredEncryption(String location) throws IOException { File keyFile = new File(location); ObjectInputStream oin = null; if (keyFile != null) { if (keyFile.exists()) { FileInputStream fi = new FileInputStream(keyFile); try { oin = new ObjectInputStream(fi); spec = (SecretKeySpec) oin.readObject(); } catch (ClassNotFoundException e) { log.error("Unable to read object or class not found: ", e); } finally { if (oin != null) oin.close();//from w ww . j a v a 2s .c om if (fi != null) fi.close(); } } else { SecureRandom random = new SecureRandom(); random.setSeed(System.currentTimeMillis()); byte[] bytes = new byte[16]; random.nextBytes(bytes); spec = new SecretKeySpec(bytes, "AES"); File dir = keyFile.getParentFile(); if (!dir.exists()) { dir.mkdirs(); } if (!dir.exists() || !dir.isDirectory()) { throw new IllegalStateException("Could not create directory for secret key spec: " + dir); } FileOutputStream out = new FileOutputStream(keyFile); try { ObjectOutputStream oout = new ObjectOutputStream(out); try { oout.writeObject(spec); oout.flush(); } finally { oout.close(); } } finally { out.close(); } log.info("Generate a new configured encryption password: " + spec.getEncoded().toString()); } } }
From source file:plbtw.klmpk.barang.hilang.controller.DeveloperController.java
@RequestMapping(method = RequestMethod.POST, produces = "application/json") public CustomResponseMessage addDeveloper(@RequestBody DeveloperRequest developerRequest) { try {//from ww w. j a va2 s . co m if (developerService.checkDeveloperExist(developerRequest.getEmail()) != null) { return new CustomResponseMessage(HttpStatus.METHOD_NOT_ALLOWED, "Email Already Used"); } Developer developer = new Developer(); developer.setRole(roleService.getRole(developerRequest.getIdrole())); SecureRandom random = new SecureRandom(); byte bytes[] = new byte[20]; random.nextBytes(bytes); String token = bytes.toString(); developer.setToken(token); developer.setSecretKey(token); developer.setEmail(developerRequest.getEmail()); developer.setPassword(developerRequest.getPassword()); developerService.addDeveloper(developer); List<Developer> result = new ArrayList<>(); result.add(developer); return new CustomResponseMessage(HttpStatus.CREATED, "Developer Has Been Created", result); } catch (Exception ex) { return new CustomResponseMessage(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage()); } }