public String generateRandomKey(int length) { return CryptUtil.generateRandomKey(length); }
public String encryptWithHMacSHA1(String data, String secret) { return CryptUtil.encryptWithHMacSHA1(data, secret); }
public String decryptAES(String data, String secretKey) { return CryptUtil.decryptAES(data, secretKey); } }
public String encryptAES(String data, String secretKey) { return CryptUtil.encryptAES(data, secretKey); }
public String sha1(String value) { return CryptUtil.sha1(value); }
public String encryptToHex(String data, String secret, String hashType) { return CryptUtil.encryptToHex(data, secret, hashType); }
private ProjectApiKeys transformKeys(ProjectApiKeys apiKeys) { if (projectConfig.getPassphrase() == null) { return ProjectApiKeys.create(apiKeys.masterKey(), apiKeys.readKey(), apiKeys.writeKey()); } else { return ProjectApiKeys.create( CryptUtil.encryptAES(apiKeys.masterKey(), projectConfig.getPassphrase()), CryptUtil.encryptAES(apiKeys.readKey(), projectConfig.getPassphrase()), CryptUtil.encryptAES(apiKeys.writeKey(), projectConfig.getPassphrase())); } }
public static String getCookieForUser(String secretKey, int userId) { final long expiringTimestamp = Instant.now().plus(7, ChronoUnit.DAYS).getEpochSecond(); final StringBuilder cookieData = new StringBuilder() .append(expiringTimestamp).append("|") .append(userId); final String secureKey = CryptUtil.encryptWithHMacSHA1(cookieData.toString(), secretKey); cookieData.append('|').append(secureKey); return cookieData.toString(); }
@Override public ProjectApiKeys createApiKeys(String project) { String masterKey = CryptUtil.generateRandomKey(64); String readKey = CryptUtil.generateRandomKey(64); String writeKey = CryptUtil.generateRandomKey(64); try (Connection connection = connectionPool.getConnection()) { PreparedStatement ps = connection.prepareStatement("INSERT INTO api_key " + "(master_key, read_key, write_key, project) VALUES (?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS); ps.setString(1, masterKey); ps.setString(2, readKey); ps.setString(3, writeKey); ps.setString(4, project); ps.executeUpdate(); final ResultSet generatedKeys = ps.getGeneratedKeys(); generatedKeys.next(); } catch (SQLException e) { throw Throwables.propagate(e); } return ProjectApiKeys.create(masterKey, readKey, writeKey); }
String data = CryptUtil.decryptAES(apiKey.substring(apiKeyId), projectKey.key); access = JsonHelper.read(data, Access.class); } else {
private String getRecoverUrl(String email, int hours) { long expiration = Instant.now().plus(hours, HOURS).getEpochSecond(); String key = expiration + "|" + email; String hash = CryptUtil.encryptWithHMacSHA1(key, encryptionConfig.getSecretKey()); String encoded = new String(Base64.getEncoder().encode(key.getBytes(UTF_8)), UTF_8); try { return format("key=%s&hash=%s", URLEncoder.encode(encoded, "UTF-8"), URLEncoder.encode(hash, "UTF-8")); } catch (UnsupportedEncodingException e) { throw Throwables.propagate(e); } }
@Test(invocationCount = 5) public void testIncrementalExpirationWithData() throws Exception { String tableName = CryptUtil.generateRandomKey(10); populate(tableName);
private String encodeState(ScenarioState[] states) { if (states == null) { return null; } StringBuilder builder = new StringBuilder(); for (ScenarioState scenarioState : states) { if (scenarioState != null) { builder.append(scenarioState.ruleId).append(':').append(scenarioState.state).append(':').append(scenarioState.threshold); } } String secureKey = CryptUtil.encryptWithHMacSHA1(builder.toString(), encryptionConfig.getSecretKey()); builder.append('|').append(secureKey); return builder.toString(); }
@Test(invocationCount = 5) public void testIncrementalRealtimeExpiration() throws Exception { String tableName = CryptUtil.generateRandomKey(10); populate(tableName); MaterializedView view = new MaterializedView("testview", "testview", format("select count(*) as count from %s", checkCollection(tableName)), Duration.ofSeconds(1), true, true, ImmutableMap.of()); getMaterializedViewService().create(new RequestContext(PROJECT_NAME), view).join(); QueryExecutorService queryService = getQueryService(); QueryResult result = queryService.executeQuery(PROJECT_NAME, "select * from materialized.testview", ZoneId.systemDefault()).getResult().join(); assertFalse(result.isFailed()); populate(tableName); getClock().increment(Duration.ofSeconds(2).toMillis()); result = queryService.executeQuery(PROJECT_NAME, "select * from materialized.testview", ZoneId.systemDefault()).getResult().join(); assertFalse(result.isFailed()); int total = 0; for (List<Object> objects : result.getResult()) { total += ((Number) objects.get(0)).intValue(); } assertEquals(SCALE_FACTOR * 2, total); }
public static int extractUserFromCookie(String session, String key) { if (session == null) { throw new RakamException(UNAUTHORIZED); } final String[] split = session.split("\\|"); if (split.length != 3) { throw new RakamException(UNAUTHORIZED); } final long expiringTimestamp = Long.parseLong(split[0]); final int id = Integer.parseInt(split[1]); final String hash = split[2]; final StringBuilder cookieData = new StringBuilder() .append(expiringTimestamp).append("|") .append(id); if (!CryptUtil.encryptWithHMacSHA1(cookieData.toString(), key).equals(hash)) { throw new RakamException(UNAUTHORIZED); } return id; }
private ScenarioState[] extractState(RequestParams extraProperties) throws IllegalStateException { ScenarioState[] value; String val = extraProperties.cookies().stream().filter(e -> e.name().equals(PROPERTY_KEY)) .findAny().map(e -> e.value()).orElse(null); if (val == null) { return null; } String[] cookie = val.split("\\|", 2); if (cookie.length != 2 || !CryptUtil.encryptWithHMacSHA1(cookie[0], encryptionConfig.getSecretKey()).equals(cookie[1])) { throw new IllegalStateException(); } String[] values = cookie[0].split(","); value = new ScenarioState[values.length]; for (int i = 0; i < values.length; i++) { final String[] split = values[i].split(":", 3); final ScenarioState scenarioState; try { scenarioState = new ScenarioState(Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2])); } catch (NumberFormatException e) { throw new IllegalStateException(); } value[i] = scenarioState; } return null; }
throw new RakamException("Invalid token", UNAUTHORIZED); if (!CryptUtil.encryptWithHMacSHA1(realKey, encryptionConfig.getSecretKey()).equals(hash)) { throw new RakamException("Invalid token", UNAUTHORIZED);
public Optional<WebUser> login(String email, String password) { if (config.getHashPassword()) { password = CryptUtil.encryptWithHMacSHA1(password, encryptionConfig.getSecretKey());
public void updateUserPassword(int id, String oldPassword, String newPassword) { final String scrypt = SCryptUtil.scrypt(newPassword, 2 << 14, 8, 1); if (!PASSWORD_PATTERN.matcher(newPassword).matches()) { throw new RakamException("Password is not valid. Your password must contain at least one lowercase character, uppercase character and digit and be at least 8 characters. ", BAD_REQUEST); } if (config.getHashPassword()) { oldPassword = CryptUtil.encryptWithHMacSHA1(oldPassword, encryptionConfig.getSecretKey()); } try (Handle handle = dbi.open()) { String hashedPass = handle.createQuery("SELECT password FROM web_user WHERE id = :id") .bind("id", id).map(StringMapper.FIRST).first(); if (hashedPass == null) { throw new RakamException("User does not exist", BAD_REQUEST); } if (!SCryptUtil.check(oldPassword, hashedPass)) { throw new RakamException("Password is wrong", BAD_REQUEST); } handle.createStatement("UPDATE web_user SET password = :password WHERE id = :id") .bind("id", id) .bind("password", scrypt).execute(); } }
password = CryptUtil.encryptWithHMacSHA1(password, encryptionConfig.getSecretKey());