Example usage for org.springframework.security.crypto.codec Hex encode

List of usage examples for org.springframework.security.crypto.codec Hex encode

Introduction

In this page you can find the example usage for org.springframework.security.crypto.codec Hex encode.

Prototype

public static char[] encode(byte[] bytes) 

Source Link

Usage

From source file:fi.okm.mpass.idp.authn.impl.AbstractSpringSocialOAuth2Identity.java

/**
 * Returns redirect url for authentication.
 * //from  ww w.  j  a  v  a 2  s . c o m
 * @param httpRequest
 *            the request
 * 
 * @return redirect url
 */
public String getRedirectUrl(HttpServletRequest httpRequest) {
    log.trace("Entering");
    if (httpRequest == null) {
        log.trace("Leaving");
        return null;
    }
    OAuth2Parameters params = new OAuth2Parameters();
    if (scope != null) {
        params.setScope(scope);
    }
    try {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.reset();
        md.update(httpRequest.getSession().getId().getBytes());
        String digest = new String(Hex.encode(md.digest()));
        params.setState(digest);
    } catch (NoSuchAlgorithmException e) {
        log.error("Unable to generate state");
        log.error("Something bad happened " + e.getMessage());
        log.trace("Leaving");
        return null;
    }
    params.setRedirectUri(httpRequest.getRequestURL().toString());
    String authorizeUrl = oauthOperations.buildAuthorizeUrl(GrantType.AUTHORIZATION_CODE, params);
    log.trace("Leaving");
    return authorizeUrl;

}

From source file:fi.vm.kapa.identification.service.PhaseIdService.java

private String generateHmacString(String tokenId, String stepCounter, int time) {
    return String.valueOf(Hex
            .encode(hmacCalc.doFinal(("tid=" + tokenId + ";pid=" + stepCounter + ";time=" + time).getBytes())));
}

From source file:org.springframework.social.facebook.web.RealTimeUpdateController.java

private boolean verifySignature(String payload, String signature) throws Exception {
    if (!signature.startsWith("sha1=")) {
        return false;
    }//from   www  .  jav  a2  s  .  c  o m
    String expected = signature.substring(5);
    Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
    SecretKeySpec signingKey = new SecretKeySpec(applicationSecret.getBytes(), HMAC_SHA1_ALGORITHM);
    mac.init(signingKey);
    byte[] rawHmac = mac.doFinal(payload.getBytes());
    String actual = new String(Hex.encode(rawHmac));
    return expected.equals(actual);
}

From source file:fr.gael.dhus.service.SystemService.java

@PreAuthorize("hasRole('ROLE_SYSTEM_MANAGER')")
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
public void changeRootPassword(String new_pwd, String old_pwd) {
    User root = userDao.getByName(cfgManager.getAdministratorConfiguration().getName());
    PasswordEncryption encryption = root.getPasswordEncryption();
    if (encryption != PasswordEncryption.NONE) {
        try {//from   ww  w  . ja v  a  2s  . co  m
            MessageDigest md = MessageDigest.getInstance(encryption.getAlgorithmKey());
            old_pwd = new String(Hex.encode(md.digest(old_pwd.getBytes("UTF-8"))));
        } catch (Exception e) {
            throw new UserBadEncryptionException("There was an error while encrypting password of root user",
                    e);
        }
    }
    if ((old_pwd == null) || ("".equals(old_pwd)) || (!root.getPassword().equals(old_pwd)))
        throw new SecurityException("Wrong password.");

    if ((new_pwd == null) || "".equals(new_pwd.trim()))
        throw new SecurityException("New password cannot be empty.");

    String password = new_pwd.trim();
    root.setPassword(password);
    userDao.update(root);
}

From source file:fi.okm.mpass.idp.authn.impl.AbstractSpringSocialOAuth2Identity.java

/**
 * Throws an error if state parameter is not the expected one.
 * //from   w w w. j  a  va  2s  .c o  m
 * @param httpRequest
 *            is the httpRequest we check for state.
 * @throws SocialUserAuthenticationException
 *             if the parameter is missing or mismatches.
 * */
private void validateState(HttpServletRequest httpRequest) throws SocialUserAuthenticationException {
    log.trace("Entering");
    String state = httpRequest.getParameter("state");
    if (state == null) {
        log.trace("Leaving");
        throw new SocialUserAuthenticationException("State parameter missing", SocialUserErrorIds.EXCEPTION);
    }
    MessageDigest md;
    try {
        md = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
        log.error("Unable to generate state");
        log.error("Something bad happened " + e.getMessage());
        log.trace("Leaving");
        throw new SocialUserAuthenticationException("Unable to hash, use some other method",
                SocialUserErrorIds.EXCEPTION);
    }
    md.reset();
    md.update(httpRequest.getSession().getId().getBytes());
    String cmpState = new String(Hex.encode(md.digest()));
    if (!state.equalsIgnoreCase(cmpState)) {
        log.error("state parameter mismatch");
        log.trace("Leaving");
        throw new SocialUserAuthenticationException("State parameter mismatch", SocialUserErrorIds.EXCEPTION);
    }
}

From source file:sk.lazyman.gizmo.util.GizmoUtils.java

public static String toSha1(String value) {
    if (value == null) {
        return null;
    }//from  w w  w. ja  va 2 s. c  o  m

    try {
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        md.reset();
        md.update(value.getBytes(StandardCharsets.UTF_8));

        char[] array = Hex.encode(md.digest());
        return new String(array);
    } catch (NoSuchAlgorithmException e) {
        new RuntimeException(e);
    }

    return null;
}

From source file:org.apache.syncope.core.util.ImportExport.java

private String getValues(final ResultSet rs, final String columnName, final Integer columnType)
        throws SQLException {

    String res = null;/*from   w  ww .  jav a2 s.c o m*/

    try {
        switch (columnType) {
        case Types.BINARY:
        case Types.VARBINARY:
        case Types.LONGVARBINARY:
            final InputStream is = rs.getBinaryStream(columnName);
            if (is != null) {
                res = new String(Hex.encode(IOUtils.toByteArray(is)));
            }
            break;

        case Types.BLOB:
            final Blob blob = rs.getBlob(columnName);
            if (blob != null) {
                res = new String(Hex.encode(IOUtils.toByteArray(blob.getBinaryStream())));
            }
            break;

        case Types.BIT:
        case Types.BOOLEAN:
            if (rs.getBoolean(columnName)) {
                res = "1";
            } else {
                res = "0";
            }
            break;

        case Types.DATE:
        case Types.TIME:
        case Types.TIMESTAMP:
            final Timestamp timestamp = rs.getTimestamp(columnName);
            if (timestamp != null) {
                res = DATE_FORMAT.get().format(new Date(timestamp.getTime()));
            }
            break;

        default:
            res = rs.getString(columnName);
        }
    } catch (IOException e) {
        LOG.error("Error retrieving hexadecimal string", e);
    }

    return res;
}

From source file:alfio.manager.NotificationManager.java

private static String calculateChecksum(String recipient, String attachments, String subject, String text) {
    try {//from   ww w .  j  a  v a  2s  .  c  o m
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        digest.update(recipient.getBytes(StandardCharsets.UTF_8));
        digest.update(subject.getBytes(StandardCharsets.UTF_8));
        Optional.ofNullable(attachments).ifPresent(v -> digest.update(v.getBytes(StandardCharsets.UTF_8)));
        digest.update(text.getBytes(StandardCharsets.UTF_8));
        return new String(Hex.encode(digest.digest()));
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(e);
    }
}

From source file:fr.gael.dhus.service.UserService.java

@PreAuthorize("isAuthenticated ()")
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
@CacheEvict(value = "user", allEntries = true)
public void selfChangePassword(Long id, String old_password, String new_password)
        throws RootNotModifiableException, RequiredFieldMissingException, EmailNotSentException,
        UserBadOldPasswordException {//w ww. j  a v  a2  s .  c  om
    User u = userDao.read(id);
    checkRoot(u);

    //encrypt old password to compare
    PasswordEncryption encryption = u.getPasswordEncryption();
    if (encryption != PasswordEncryption.NONE) // when configurable
    {
        try {
            MessageDigest md = MessageDigest.getInstance(encryption.getAlgorithmKey());
            old_password = new String(Hex.encode(md.digest(old_password.getBytes("UTF-8"))));
        } catch (Exception e) {
            throw new UserBadEncryptionException(
                    "There was an error while encrypting password of user " + u.getUsername(), e);
        }
    }

    if (!u.getPassword().equals(old_password)) {
        throw new UserBadOldPasswordException("Old password is not correct.");
    }

    u.setPassword(new_password);

    checkRequiredFields(u);
    userDao.update(u);
}