Java 类org.apache.commons.codec.digest.HmacUtils 实例源码

项目:zaoshu-java-sdk    文件:Authorize.java   
/**
 *
 * @param secret
 * @param method
 * @param contentType
 * @param date
 * @param sortedQuery
 * @param body
 * @return
 */
public static String sign(String secret,String method,String contentType,String date,String sortedQuery,String body){
    StringBuilder strToSign = new StringBuilder();

    /**
     * 构建 签名字符串
     */
    strToSign.append(method)
            .append('\n')
            .append(contentType)
            .append('\n')
            .append(date)
            .append('\n')
            .append(StringUtils.isEmpty(sortedQuery)?'\n':sortedQuery)
            .append(StringUtils.isEmpty(body)?"":body);


    log.debug("strToSign:\n{}",strToSign.toString());
    // sha256 签名
    byte[] hmacSha256 = HmacUtils.hmacSha256(secret, strToSign.toString());

    // base64 编码
    return Base64.getEncoder().encodeToString(hmacSha256);
}
项目:oauth4j    文件:AbstractAccessToken.java   
/**
 * get access token string value
 *
 * @return
 * @throws IOException
 */
public String getValue() throws IOException {
    if (StringUtils.isBlank(this.value)) {
        byte[] encodeValue = this.encode();
        byte[] hmacValue = Base64.encodeBase64(HmacUtils.hmacSha1(this.key.getBytes(), encodeValue));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (DataOutputStream dos = new DataOutputStream(baos)) {
            dos.writeInt(hmacValue.length);
            dos.write(hmacValue);
            dos.write(encodeValue);
            dos.flush();
            this.value = Base64.encodeBase64String(baos.toByteArray());
        }
    }
    return this.value;
}
项目:gh-webhook-demo    文件:GithubWebhook.java   
@RequestMapping(value = "/github-webhook", method = RequestMethod.POST)
public ResponseEntity<String> handle(@RequestHeader("X-Hub-Signature") String signature,
        @RequestBody String payload) {
    HttpHeaders headers = new HttpHeaders();
    headers.add("X-Webhook-Version", String.format("%s/%s", version, commitId));

    if (signature == null) {
        return new ResponseEntity<>("No signature given." + EOL, headers,
                HttpStatus.BAD_REQUEST);
    }

    String computed = String.format("sha1=%s", HmacUtils.hmacSha1Hex(secret, payload));
    boolean invalidLength = signature.length() != SIGNATURE_LENGTH;

    if (invalidLength || !StringUtils.constantTimeCompare(signature, computed)) {
        return new ResponseEntity<>("Invalid signature." + EOL, headers,
                HttpStatus.UNAUTHORIZED);
    }

    int bytes = payload.getBytes().length;
    StringBuilder message = new StringBuilder();
    message.append("Signature OK.").append(EOL);
    message.append(String.format("Received %d bytes.", bytes)).append(EOL);
    return new ResponseEntity<>(message.toString(), headers, HttpStatus.OK);
}
项目:cos-java-sdk-v5    文件:COSSigner.java   
public String buildAuthorizationStr(HttpMethodName methodName, String resouce_path,
        Map<String, String> headerMap, Map<String, String> paramMap, COSCredentials cred,
        Date expiredTime) {

    if (isAnonymous(cred)) {
        return null;
    }

    Map<String, String> signHeaders = buildSignHeaders(headerMap);
    // 签名中的参数和http 头部 都要进行字符串排序
    TreeMap<String, String> sortedSignHeaders = new TreeMap<>();
    TreeMap<String, String> sortedParams = new TreeMap<>();

    sortedSignHeaders.putAll(signHeaders);
    sortedParams.putAll(paramMap);

    String qHeaderListStr = buildSignMemberStr(sortedSignHeaders);
    String qUrlParamListStr = buildSignMemberStr(sortedParams);
    String qKeyTimeStr, qSignTimeStr;
    qKeyTimeStr = qSignTimeStr = buildTimeStr(expiredTime);
    String signKey = HmacUtils.hmacSha1Hex(cred.getCOSSecretKey(), qKeyTimeStr);
    String formatMethod = methodName.toString().toLowerCase();
    String formatUri = resouce_path;
    String formatParameters = formatMapToStr(sortedParams);
    String formatHeaders = formatMapToStr(sortedSignHeaders);

    String formatStr = new StringBuilder().append(formatMethod).append(LINE_SEPARATOR)
            .append(formatUri).append(LINE_SEPARATOR).append(formatParameters)
            .append(LINE_SEPARATOR).append(formatHeaders).append(LINE_SEPARATOR).toString();
    String hashFormatStr = DigestUtils.sha1Hex(formatStr);
    String stringToSign = new StringBuilder().append(Q_SIGN_ALGORITHM_VALUE)
            .append(LINE_SEPARATOR).append(qSignTimeStr).append(LINE_SEPARATOR)
            .append(hashFormatStr).append(LINE_SEPARATOR).toString();
    String signature = HmacUtils.hmacSha1Hex(signKey, stringToSign);

    String authoriationStr = new StringBuilder().append(Q_SIGN_ALGORITHM_KEY).append("=")
            .append(Q_SIGN_ALGORITHM_VALUE).append("&").append(Q_AK).append("=")
            .append(cred.getCOSAccessKeyId()).append("&").append(Q_SIGN_TIME).append("=")
            .append(qSignTimeStr).append("&").append(Q_KEY_TIME).append("=").append(qKeyTimeStr)
            .append("&").append(Q_HEADER_LIST).append("=").append(qHeaderListStr).append("&")
            .append(Q_URL_PARAM_LIST).append("=").append(qUrlParamListStr).append("&")
            .append(Q_SIGNATURE).append("=").append(signature).toString();
    return authoriationStr;
}
项目:zaoshu-java-sdk    文件:AuthorizeTest.java   
@Test
public  void testSign(){
    String str = "POST\napplication/json; charset=utf-8\nWed, 18 Mar 2016 08:04:06 GMT\na=1\nb=2\n{\"v\": \"tt\"}";
    // sha256 签名
    String secret = "1234567890-=";
    byte[] hmacSha256 = HmacUtils.hmacSha256(secret, str);

    // base64 编码
    String sign =  Base64.getEncoder().encodeToString(hmacSha256);
    log.info("strToSign:\n{}",str);
    log.info("sign:\n{}",sign);
}
项目:coinpaymentsnet-java-api    文件:CoinPaymentsAPI.java   
/**
 * Calls the API
 * 
 * @param cmd
 * @return the answer from the
 */
public JsonObject call(String cmd)
{

    // Copy the current map to
    Map<String, String> req = new HashMap<>();
    req.putAll(params);
    params.clear();

    // Set the API command and required fields
    req.put("version", "1");
    req.put("cmd", cmd);
    req.put("key", this.public_key);
    req.put("format", "json");

    try {
        // Generate the query string
        String post_data = urlEncodeUTF8(req);

        // Calculate the HMAC
        String hmac = HmacUtils.hmacSha512Hex(this.private_key, post_data);
        URL obj = new URL("https://www.coinpayments.net/api.php");
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        // Set the request headers
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", "Mozilla/5.0");
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
        con.setRequestProperty("HMAC", hmac);

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(post_data);
        wr.flush();
        wr.close();

        // Wait for the resüonse code
        int responseCode = con.getResponseCode();
        logger.debug("Sending 'POST' request to URL : https://www.coinpayments.net/api.php");
        logger.debug("Post parameters : " + post_data);
        logger.debug("Response Code : " + responseCode);

        // Read the full response
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        // Parse the JSON response with GSON
        JsonParser jsonParser = new JsonParser();
        JsonElement jsonTree = jsonParser.parse(response.toString());
        JsonObject jsonObject = jsonTree.getAsJsonObject();

        // If there is an error - throw an Exception
        if (jsonObject.get("error").getAsString().equals("ok") == false) {
            throw new IllegalStateException(jsonObject.get("error").getAsString());
        }

        // Otherwise return the result object
        Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
        String prettyJson = gson.toJson(jsonObject);
        logger.debug(prettyJson);

        return jsonObject.getAsJsonObject("result");
    }
    catch (Exception e) {
        logger.error("Exception occured: " + e.getMessage());
        throw new CoinpaymentsApiCallException(e.getMessage());
    }
}
项目:s3srv    文件:SignatureUtils.java   
/**
 * Computes RFC 2104-compliant HMAC signature.
 *
 * @param data The data to be signed.
 * @param key  The signing key.
 * @return The Base64-encoded RFC 2104-compliant HMAC signature.
 * @throws SignatureException if signing fails
 */
public static String calculateHmacSha1(String data, String key) throws SignatureException {
    try {
        final Mac mac = HmacUtils.getHmacSha1(key.getBytes());
        return Base64.getEncoder().encodeToString(mac.doFinal(data.getBytes()));

    } catch (Exception e) {
        throw new SignatureException("Failed to generate HMAC: " + e.getMessage());
    }
}
项目:tiramisu    文件:UserController.java   
public TiramisuResponse register() throws NotFoundException {
    log.info("User Controller Register Method");

    if (this.request.getMethod().equals("POST")) {

        UserModel user = new UserModel();
        user.setUsername(this.getRequest().getParameter("user_username"));
        user.setEmail(this.getRequest().getParameter("user_email"));
        user.setActive(false);

        // Use the salt and pepper, plus hash, to save the password.
        String salt = BCrypt.gensalt();

        // Using the apache commons codec library, convert the password and pepper to a hashed password.
        // Have to use 256 here, because 512 exceeds the max length of BCrypt
        String hmacPassword = HmacUtils.hmacSha256Hex(TiramisuConfiguration.pepper, this.getRequest().getParameter("user_password"));

        // Hash the password.
        String hash = BCrypt.hashpw(hmacPassword, salt);

        // Store the hash.
        user.setPassword(hash);

        // Finally save the user.
        this.save(user);

        // Add a flash message.
        this.getResponse().addFlashMessage("New user created");

        // Redirect to the users index.
        return this.redirect("/tiramisu/users", 303);
    }

    // Render the create form.
    this.getResponse().setTemplate("/users/create.vm");
    this.getResponse().setPageTitle("Create new user");

    return this.getResponse();
}
项目:facebook-messenger    文件:FacebookMessengerClient.java   
/**
 * Validates the provided signature by comparing it to a HmacSHA1 encoded string generated using the
 * provided request body and app secret key.
 *
 * https://developers.facebook.com/docs/messenger-platform/webhook-reference#security
 */
public boolean isValidRequest(@NonNull String appSecretKey, @NonNull String signature, @NonNull String requestBody) {
    checkArgument(StringUtils.isNotBlank(appSecretKey), "appSecretKey cannot be blank");
    checkArgument(StringUtils.isNotBlank(signature), "signature cannot be blank");

    try {
        byte[] sha1 = HmacUtils.hmacSha1(appSecretKey.getBytes(StandardCharsets.UTF_8), requestBody.getBytes(StandardCharsets.UTF_8));
        return StringUtils.equals("sha1=" + Hex.encodeHexString(sha1), signature);
    } catch (Exception e) {
        log.error("Failed to generate hex encoded HmacSHA1 for requestBody {}", requestBody, e);
        return false;
    }
}
项目:pay-publicauth    文件:TokenService.java   
private boolean tokenMatchesHmac(String token, String currentHmac) {
    final String hmacCalculatedFromToken = BaseEncoding.base32Hex()
            .lowerCase().omitPadding()
            .encode(HmacUtils.hmacSha1(apiKeyHmacSecret, token));

    return hmacCalculatedFromToken.equals(currentHmac);
}
项目:pay-publicauth    文件:TokenServiceTest.java   
@Test
public void extractEncryptedTokenFromApiKey_shouldNotBePresent_whenTokenDoesNotMatchHmac() {

    String token = "thisismvplaintoken";
    String hmac = BaseEncoding.base32Hex().omitPadding().lowerCase().encode(HmacUtils.hmacSha1(EXPECTED_SECRET_KEY, token));

    Optional<Token> expectedValidTokenOptional = tokenService.extractEncryptedTokenFrom(token + hmac);
    assertThat(expectedValidTokenOptional.isPresent(), is(true));

    String tokenInvalid = token + "1";

    Optional<Token> expectedInvalidTokenOptional = tokenService.extractEncryptedTokenFrom(tokenInvalid + hmac);
    assertThat(expectedInvalidTokenOptional.isPresent(), is(false));
}
项目:pay-publicauth    文件:TokenServiceTest.java   
@Test
public void extractEncryptedTokenFromApiKey_shouldNotBePresent_whenLengthIsGreaterThanExpected() {

    String tokenGreaterThan26Characters = "morethan26chartokenisnotval";
    String hmac = BaseEncoding.base32Hex().omitPadding().lowerCase().encode(HmacUtils.hmacSha1(EXPECTED_SECRET_KEY, tokenGreaterThan26Characters));

    Optional<Token> expectedValidTokenOptional = tokenService.extractEncryptedTokenFrom(tokenGreaterThan26Characters + hmac);
    assertThat(expectedValidTokenOptional.isPresent(), is(false));
}
项目:pay-publicauth    文件:TokenServiceTest.java   
@Test
public void extractEncryptedTokenFromApiKey_shouldBePresent_evenWhenCharacterSetIsNotExpectedBase32HexLowercase_asLongTheHmacIsValid() {

    // Is more computationally expensive checking for character set validation than validating against the Hmac.
    // Enough to be a lightweight mechanism to check the token is genuine.

    String tokenLowercaseButNoInBase32Hex = "x";
    String hmac = BaseEncoding.base32Hex().omitPadding().lowerCase().encode(HmacUtils.hmacSha1(EXPECTED_SECRET_KEY, tokenLowercaseButNoInBase32Hex));

    Optional<Token> expectedValidTokenOptional = tokenService.extractEncryptedTokenFrom(tokenLowercaseButNoInBase32Hex + hmac);
    assertThat(expectedValidTokenOptional.isPresent(), is(true));
}
项目:pay-publicauth    文件:TokenServiceTest.java   
@Test
public void extractEncryptedTokenFromApiKey_shouldBePresent_evenWhenCharacterSetIsInBase32HexButUppercase_asLongTheHmacIsValid() {

    // Is more computationally expensive checking for character set validation than validating against the Hmac.
    // Enough to be a lightweight mechanism to check the token is genuine.

    String tokenUppercaseBase32Hex = "A";
    String hmac = BaseEncoding.base32Hex().omitPadding().lowerCase().encode(HmacUtils.hmacSha1(EXPECTED_SECRET_KEY, tokenUppercaseBase32Hex));

    Optional<Token> expectedValidTokenOptional = tokenService.extractEncryptedTokenFrom(tokenUppercaseBase32Hex + hmac);
    assertThat(expectedValidTokenOptional.isPresent(), is(true));
}
项目:actor-platform    文件:CalcSignature.java   
/**
 * Returns url with calculated signature for specific file with specific file builder parameters
 * @param baseUri base uri from file url builder
 * @param seed seed provided by file url builder. Must be included in url
 * @param signatureSecret secret used to sign request
 * @param fileId id of file to download
 * @param fileAccessHash access hash of file to download
 * @return file url
 */
public static String fileBuilderUrl(String baseUri, String seed, byte[] signatureSecret, long fileId, long fileAccessHash) {
    byte[] seedBytes = decodeHex(seed.toCharArray());
    byte[] fileIdBytes = getBytes(fileId);
    byte[] accessHashBytes = getBytes(fileAccessHash);

    byte[] bytesToSign = ArrayUtils.addAll(ArrayUtils.addAll(seedBytes, fileIdBytes), accessHashBytes);

    String signPart = HmacUtils.hmacSha256Hex(signatureSecret, bytesToSign);

    String signature = seed + "_" + signPart;

    return baseUri + "/" + fileId + "?signature=" + signature;
}
项目:upsource-bot    文件:GitHubHMACFilter.java   
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
  String hubSignature = requestContext.getHeaderString("X-Hub-Signature");
  if (hubSignature == null) {
    requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
    return;
  }

  byte[] requestBody = ByteStreams.toByteArray(requestContext.getEntityStream());
  String hmac = "sha1=" + HmacUtils.hmacSha1Hex(secret, requestBody);
  if (!MessageDigest.isEqual(hmac.getBytes(), hubSignature.getBytes())) {
    requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
  }
  requestContext.setEntityStream(new ByteArrayInputStream(requestBody));
}
项目:cs-actions    文件:AuthorizationTokenImpl.java   
@NotNull
public static String getToken(@NotNull final String identifier, @NotNull final String primaryOrSecondaryKey, @NotNull final Date expiryDate) {
    final Mac sha512Hmac = HmacUtils.getHmacSha512(primaryOrSecondaryKey.getBytes(UTF_8));
    final String dataToSign = String.format("%s\n%s", identifier, DateUtilities.formatDate(expiryDate));
    final byte[] encodedBytes = Base64.encodeBase64(sha512Hmac.doFinal(dataToSign.getBytes(UTF_8)));
    final String encodedString = new String(encodedBytes, UTF_8);
    return String.format(SHARED_ACCESS_SIGNATURE, identifier, DateUtilities.formatDate(expiryDate), encodedString);
}
项目:FTBCurseBot    文件:GithubWebhook.java   
private static boolean ghSignatureMatches (@Nonnull String signature, @Nonnull String body, @Nonnull String key) {
    return HmacUtils.hmacSha1Hex(key, body).equals(signature);
}
项目:tiramisu    文件:BaseAuthenicate.java   
private String hashPassword(String password) {
    return HmacUtils.hmacSha256Hex(TiramisuConfiguration.pepper, password);
}
项目:apache-cloudstack-java-client    文件:ApacheCloudStackClient.java   
/**
 * Creates a signature (HMAC-sha1) with the {@link #ApacheCloudStackUser#getSecretKey()} and the given queryString
 * The returner signature is encoded in Base64.
 */
protected String createSignature(String queryString) {
    byte[] signatureBytes = HmacUtils.hmacSha1(apacheCloudStackUser.getSecretKey(), queryString.toLowerCase());
    return Base64.encodeBase64String(signatureBytes);
}
项目:pay-publicauth    文件:TokenService.java   
private String createApiKey(String token) {
    byte[] hmacBytes = HmacUtils.hmacSha1(apiKeyHmacSecret, token);
    String encodedHmac = BaseEncoding.base32Hex().lowerCase().omitPadding().encode(hmacBytes);
    return token + encodedHmac;
}
项目:pay-publicauth    文件:TokenServiceTest.java   
@Test
public void issueTokens_shouldIssueApiKeyTokenWithHmacThatMatches() {

    Tokens tokens = tokenService.issueTokens();

    String apiKey = tokens.getApiKey();
    int hmacLength = 32;

    int tokenEnd = apiKey.length() - hmacLength;

    String plainToken = apiKey.substring(0, tokenEnd);
    String hmacApiKey = apiKey.substring(tokenEnd);

    String hmacFromExtractedPlainToken = BaseEncoding.base32Hex().omitPadding().lowerCase().encode(HmacUtils.hmacSha1(EXPECTED_SECRET_KEY, plainToken));

    assertThat(hmacFromExtractedPlainToken, is(hmacApiKey));
}
项目:pay-publicauth    文件:PublicAuthResourceITest.java   
private String encodedHmacValueOf(String input) {
    return BaseEncoding.base32Hex().lowerCase().omitPadding().encode(HmacUtils.hmacSha1("qwer9yuhgf", input));
}
项目:pay-publicapi    文件:AuthorizationValidationFilter.java   
private boolean tokenMatchesHmac(String token, String currentHmac) {
    final String hmacCalculatedFromToken = BaseEncoding.base32Hex()
            .lowerCase().omitPadding()
            .encode(HmacUtils.hmacSha1(apiKeyHmacSecret, token));
    return hmacCalculatedFromToken.equals(currentHmac);
}
项目:pay-publicapi    文件:ApiKeyGenerator.java   
public static String apiKeyValueOf(String token, String secret) {
    byte[] hmacBytes = HmacUtils.hmacSha1(secret, token);
    String encodedHmac = BaseEncoding.base32Hex().lowerCase().omitPadding().encode(hmacBytes);
    return token + encodedHmac;
}
项目:alf.io    文件:PaypalManager.java   
private static String computeHMAC(CustomerName customerName, String email, String billingAddress, Event event) {
    return new HmacUtils(HmacAlgorithms.HMAC_SHA_256, event.getPrivateKey()).hmacHex(StringUtils.trimToEmpty(customerName.getFullName()) + StringUtils.trimToEmpty(email) + StringUtils.trimToEmpty(billingAddress));
}
项目:alf.io    文件:Ticket.java   
private static String hmacSHA256Base64(String key, String code) {
    return Base64.getEncoder().encodeToString(new HmacUtils(HmacAlgorithms.HMAC_SHA_256, key).hmac(code));
}
项目:plugin-prov-aws    文件:AWS4SignerBase.java   
/**
 * do a HMac sha256 sign
 * 
 * @param stringData
 *            data as string
 * @param key
 *            key
 * @return signature
 */
protected byte[] sign(final String stringData, final byte[] key) {
    return new HmacUtils(HmacAlgorithms.HMAC_SHA_256, key).hmac(stringData);
}
项目:spring-boot    文件:MyHmacUtils.java   
/**
 * 使用指定的密码对内容生成消息摘要(散列值)
 *
 * @param key
 * @param content
 * @return
 */

public static String hmacSha256Hex(String key, String content) {
    return HmacUtils.hmacSha256Hex(key, content);
}
项目:security-stateless-samples    文件:Crypto.java   
/**
 * Hmac with sha256 hex
 * @param key key
 * @param value value
 * @return hmac String
 */
public static String hmacSha256Hex(String key,String value){
    checkArguments(key, value);
    return HmacUtils.hmacSha1Hex(key, value);

}
项目:security-stateless-samples    文件:Crypto.java   
/**
 * Hmac with sha1 hex
 * @param key key
 * @param value value
 * @return hmac String
 */
public static String hmacSha1Hex(String key,String value){
    checkArguments(key, value);
    return HmacUtils.hmacSha1Hex(key, value);

}