Ejemplo n.º 1
0
 public String createTokenForUser(User user) {
   logger.debug("create token for user : {}", user.toString());
   byte[] userBytes = toJSON(user).getBytes();
   byte[] hash = createHmac(userBytes);
   final StringBuilder sb = new StringBuilder(170);
   sb.append(toBase64(userBytes));
   sb.append(SEPARATOR);
   sb.append(toBase64(hash));
   logger.debug("generated token : {}", sb.toString());
   return sb.toString();
 }
Ejemplo n.º 2
0
  public User parseUserFromToken(String token) {
    logger.debug("parseToken from : {}", token);
    final String[] parts = token.split(SEPARATOR_SPLITTER);
    if (parts.length == 2 && parts[0].length() > 0 && parts[1].length() > 0) {
      logger.debug("split token : {}", parts.toString());
      try {
        final byte[] userBytes = fromBase64(parts[0]);
        final byte[] hash = fromBase64(parts[1]);
        logger.debug("retrieve userBytes={} and hash={}", new String(userBytes), new String(hash));

        boolean validHash = Arrays.equals(createHmac(userBytes), hash);
        logger.debug("is valid hash : {}", validHash);
        if (validHash) {
          final User user = fromJSON(userBytes);
          logger.debug("return user : {}", user.toString());
          return user;
        }
      } catch (IllegalArgumentException e) {
        // log tempering attempt here
      }
    }
    return null;
  }