List of usage examples for java.security SecureRandom SecureRandom
public SecureRandom()
From source file:edu.vt.middleware.crypt.signature.SignatureAlgorithmTest.java
/** * @param signature A crypto signature algorithm to test. * @param keys Public/private key pair used for signing. * @param converter Converter used to convert sig bytes to String. * * @throws Exception On test failure./*from ww w .java 2s . c om*/ */ @Test(groups = { "functest", "signature" }, dataProvider = "testdata") public void testRandomizedSignVerify(final SignatureAlgorithm signature, final KeyPair keys, final Converter converter) throws Exception { logger.info("Testing randomized signature algorithm " + signature + " with converter " + converter); signature.setRandomProvider(new SecureRandom()); signature.setSignKey(keys.getPrivate()); signature.initSign(); if (converter == null) { final byte[] signedBytes = signature.sign(CLEARTEXT.getBytes()); signature.setVerifyKey(keys.getPublic()); signature.initVerify(); AssertJUnit.assertTrue(signature.verify(CLEARTEXT.getBytes(), signedBytes)); } else { final String sig = signature.sign(CLEARTEXT.getBytes(), converter); signature.setVerifyKey(keys.getPublic()); signature.initVerify(); AssertJUnit.assertTrue(signature.verify(CLEARTEXT.getBytes(), sig, converter)); } }
From source file:com.mmj.app.common.security.EncryptBuilder.java
private byte[] doCrypt(String source, String secretKey, ICrypt iCrypt) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { byte[] cryptedData = iCrypt.getCryptedData(source); Security.addProvider(new com.sun.crypto.provider.SunJCE()); SecureRandom sr = new SecureRandom(); byte[] rawKeyData = (new String(secretKey)).getBytes(); DESKeySpec dks = new DESKeySpec(rawKeyData); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey key = keyFactory.generateSecret(dks); Cipher cipher = Cipher.getInstance("DES"); iCrypt.initCipher(key, sr, cipher);//from w w w .java 2 s . c o m return cipher.doFinal(cryptedData); }
From source file:ch.cyberduck.core.sftp.openssh.OpenSSHHostKeyVerifier.java
/** * Generate the hashed representation of the given hostname. Useful for adding entries * with hashed hostnames to a known_hosts file. (see -H option of OpenSSH key-gen). * * @return the hashed representation, e.g., "|1|cDhrv7zwEUV3k71CEPHnhHZezhA=|Xo+2y6rUXo2OIWRAYhBOIijbJMA=" *///from w ww .j a v a 2s .com private static String hash(String hostname) throws IOException { MessageDigest sha1; try { sha1 = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new IOException(e); } byte[] salt = new byte[sha1.getDigestLength()]; new SecureRandom().nextBytes(salt); byte[] hash; try { hash = hmacSha1Hash(salt, hostname); } catch (IOException e) { throw new IOException(e); } String base64_salt = new String(Base64.encodeBase64(salt)); String base64_hash = new String(Base64.encodeBase64(hash)); return String.format("|1|%s|%s", base64_salt, base64_hash); }
From source file:com.intel.chimera.CryptoCodecTest.java
private void cryptoCodecTestForInputStream(int count, String encCodecClass, String decCodecClass, byte[] iv) throws IOException { CryptoCodec encCodec = null;//www.j a v a 2 s . c o m try { encCodec = (CryptoCodec) ReflectionUtils.newInstance(ReflectionUtils.getClassByName(encCodecClass), props); } 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), props); } 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); // Decrypt data byte-at-a-time in = new CryptoInputStream(new ByteArrayInputStream(encryptedData.toByteArray()), decCodec, bufferSize, key, iv); // Check DataInputStream originalIn = new DataInputStream( new BufferedInputStream(new ByteArrayInputStream(originalData))); int expected; do { expected = originalIn.read(); Assert.assertEquals("Decrypted stream read by byte does not match", expected, in.read()); } while (expected != -1); LOG.info("SUCCESS! Completed checking " + count + " records"); }
From source file:org.kegbot.api.KegbotApiImpl.java
private static String getBoundary() { return String.format("-------MultiPart%s", new SecureRandom().nextLong()); }
From source file:com.fengduo.bee.commons.security.EncryptBuilder.java
@SuppressWarnings("restriction") private byte[] doCrypt(String source, String secretKey, ICrypt iCrypt) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { byte[] cryptedData = iCrypt.getCryptedData(source); Security.addProvider(new com.sun.crypto.provider.SunJCE()); SecureRandom sr = new SecureRandom(); byte[] rawKeyData = (new String(secretKey)).getBytes(); DESKeySpec dks = new DESKeySpec(rawKeyData); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey key = keyFactory.generateSecret(dks); Cipher cipher = Cipher.getInstance("DES"); iCrypt.initCipher(key, sr, cipher);/*w ww. jav a 2 s.c om*/ return cipher.doFinal(cryptedData); }
From source file:net.atos.aeon.AEONSDK.java
private void Init(String subscribeUrl, String id, String desc) { this.messages = new AEONSDKMessages(); try {//from ww w.j av a2 s . com if (subscribeUrl.indexOf("/subscribe") != -1) { if (subscribeUrl.startsWith("https")) { this.webClient = ClientHelper.createClient(); SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, ClientHelper.trustAllCerts, new SecureRandom()); SocketIO.setDefaultSSLSocketFactory(sc); HttpsURLConnection.setDefaultHostnameVerifier(new RelaxedHostNameVerifier()); } else this.webClient = Client.create(); this.subscribeUrl = subscribeUrl; this.socketServer = getSocketServerEndpoint(getServerEndpoint(subscribeUrl)); this.socket = new SocketIO(socketServer); this.socket.addHeader("force_new_connection", "true"); // this.socket.addHeader("transports", "xhr-polling"); // this.socket.addHeader("polling duration", "20"); this.id = id; this.desc = desc; this.mode = "subscribe"; sioLogger.setLevel(Level.OFF); } else this.mode = "error"; } catch (MalformedURLException e) { e.printStackTrace(); this.mode = "error"; } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); this.mode = "error"; } catch (KeyManagementException e) { // TODO Auto-generated catch block e.printStackTrace(); this.mode = "error"; } }
From source file:io.kodokojo.endpoint.UserSparkEndpoint.java
@Override public void configure() { post(BASE_API + "/user/:id", JSON_CONTENT_TYPE, ((request, response) -> { String identifier = request.params(":id"); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Try to create user with id {}", identifier); }/*from w w w .j a v a 2 s . com*/ if (userStore.identifierExpectedNewUser(identifier)) { JsonParser parser = new JsonParser(); JsonObject json = (JsonObject) parser.parse(request.body()); String email = json.getAsJsonPrimitive("email").getAsString(); String username = email.substring(0, email.lastIndexOf("@")); User userByUsername = userStore.getUserByUsername(username); if (userByUsername != null) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Trying to create user {} from email '{}' who already exist.", username, email); } halt(409); return ""; } String entityName = email; if (json.has("entity") && StringUtils.isNotBlank(json.getAsJsonPrimitive("entity").getAsString())) { entityName = json.getAsJsonPrimitive("entity").getAsString(); } String password = new BigInteger(130, new SecureRandom()).toString(32); KeyPair keyPair = RSAUtils.generateRsaKeyPair(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); User user = new User(identifier, username, username, email, password, RSAUtils.encodePublicKey((RSAPublicKey) keyPair.getPublic(), email)); String entityId = null; SimpleCredential credential = extractCredential(request); if (credential != null) { User userRequester = userAuthenticator.authenticate(credential); if (userRequester != null) { entityId = entityStore.getEntityIdOfUserId(userRequester.getIdentifier()); } } if (entityId == null) { Entity entity = new Entity(entityName, user); entityId = entityStore.addEntity(entity); } entityStore.addUserToEntity(identifier, entityId); user = new User(identifier, entityId, username, username, email, password, user.getSshPublicKey()); if (userStore.addUser(user)) { response.status(201); StringWriter sw = new StringWriter(); RSAUtils.writeRsaPrivateKey(privateKey, sw); response.header("Location", "/user/" + user.getIdentifier()); UserCreationDto userCreationDto = new UserCreationDto(user, sw.toString()); if (emailSender != null) { List<String> cc = null; if (credential != null) { User userRequester = userAuthenticator.authenticate(credential); if (userRequester != null) { cc = Collections.singletonList(userRequester.getEmail()); } } String content = "<h1>Welcome on Kodo Kojo</h1>\n" + "<p>You will find all information which is bind to your account '" + userCreationDto.getUsername() + "'.</p>\n" + "\n" + "<p>Password : <b>" + userCreationDto.getPassword() + "</b></p>\n" + "<p>Your SSH private key generated:\n" + "<br />\n" + userCreationDto.getPrivateKey() + "\n" + "</p>\n" + "<p>Your SSH public key generated:\n" + "<br />\n" + userCreationDto.getSshPublicKey() + "\n" + "</p>"; emailSender.send(Collections.singletonList(userCreationDto.getEmail()), null, cc, "User creation on Kodo Kojo " + userCreationDto.getName(), content, true); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Mail with user data send to {}.", userCreationDto.getEmail()); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Email to {} content : \n {}", userCreationDto.getEmail(), content); } } } return userCreationDto; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("The UserStore not abel to add following user {}.", user.toString()); } halt(428); return ""; } else { halt(412); return ""; } }), jsonResponseTransformer); post(BASE_API + "/user", JSON_CONTENT_TYPE, (request, response) -> { String res = userStore.generateId(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Generate id : {}", res); } return res; }); get(BASE_API + "/user", JSON_CONTENT_TYPE, (request, response) -> { SimpleCredential credential = extractCredential(request); if (credential != null) { User user = userStore.getUserByUsername(credential.getUsername()); if (user == null) { halt(404); return ""; } return getUserDto(user); } halt(401); return ""; }, jsonResponseTransformer); get(BASE_API + "/user/:id", JSON_CONTENT_TYPE, (request, response) -> { SimpleCredential credential = extractCredential(request); String identifier = request.params(":id"); User requestUser = userStore.getUserByUsername(credential.getUsername()); User user = userStore.getUserByIdentifier(identifier); if (user != null) { if (user.getEntityIdentifier().equals(requestUser.getEntityIdentifier())) { if (!user.getUsername().equals(credential.getUsername())) { user = new User(user.getIdentifier(), user.getName(), user.getUsername(), user.getEmail(), "", user.getSshPublicKey()); } return getUserDto(user); } halt(403, "You aren't in same entity."); return ""; } halt(404); return ""; }, jsonResponseTransformer); }
From source file:com.sudoku.data.model.User.java
private String randomSalt() { SecureRandom random = new SecureRandom(); return new BigInteger(130, random).toString(32); }
From source file:com.gtp.tradeapp.rest.UserController.java
private String generateRandomPassword() { final SecureRandom secureRandom = new SecureRandom(); return new BigInteger(130, secureRandom).toString(32).substring(0, 10); }