org.apache.commons.codec.digest.HmacUtils Java Examples

The following examples show how to use org.apache.commons.codec.digest.HmacUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AuthenticationInterceptor.java    From kucoin-java-sdk with MIT License 6 votes vote down vote up
/**
 * Generates signature info.
 *
 * @param request The HTTP request.
 * @param apiSecret API secret.
 * @param timestamp Timestamp.
 * @return THe signature.
 */
public static String genSignature(Request request, String apiSecret, String timestamp) {
    String endpoint = request.url().encodedPath();
    String requestUriParams = request.url().query();
    String requestBody = getRequestBody(request);

    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append(timestamp);
    stringBuilder.append(request.method());
    stringBuilder.append(endpoint);

    stringBuilder.append((StringUtils.isBlank(requestUriParams) ? "" : "?" + requestUriParams));
    stringBuilder.append((StringUtils.isBlank(requestBody) ? "" : "" + requestBody));
    String originToSign = stringBuilder.toString();

    String signature = Base64.encodeBase64String(HmacUtils.hmacSha256(apiSecret, originToSign));

    LOGGER.debug("originToSign={}", originToSign);
    LOGGER.debug("method={},endpoint={}", request.method(), endpoint);
    LOGGER.debug("signature={}", signature);

    return signature;
}
 
Example #2
Source File: BitBucketServerAuth.java    From gocd with Apache License 2.0 6 votes vote down vote up
default void validateAuth(String webhookSecret) {
    if (exemptFromAuth()) {
        return;
    }

    String signature = request().headers("X-Hub-Signature");

    if (isBlank(signature)) {
        throw die("No HMAC signature specified via 'X-Hub-Signature' header!");
    }

    String expectedSignature = "sha256=" + new HmacUtils(HmacAlgorithms.HMAC_SHA_256, webhookSecret)
            .hmacHex(request().body());

    if (!MessageDigest.isEqual(expectedSignature.getBytes(), signature.getBytes())) {
        throw die("HMAC signature specified via 'X-Hub-Signature' did not match!");
    }

    if (!"git".equals(scmType())) {
        throw die("Only 'git' repositories are currently supported!");
    }
}
 
Example #3
Source File: TestTwilioAckEventHandler.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
public void buildMocks(String anweredBy,String host, String sigHost,String callStatus) throws Exception{
   URIBuilder builder = new URIBuilder("/ivr/event/ack")
      .addParameter(TwilioBaseHandler.SCRIPT_PARAM, "alarm.smoke.triggered")
      .addParameter(TwilioHelper.NOTIFICATION_ID_PARAM_NAME, "place:"+UUID.randomUUID())
      .addParameter(TwilioHelper.PERSON_ID_PARAM_NAME, "test")
      .addParameter(TwilioHelper.NOTIFICATION_EVENT_TIME_PARAM_NAME, "12345678910")
      .addParameter(TwilioHelper.CALL_STATUS_PARAM_KEY, callStatus)
      .addParameter(TwilioHelper.ANSWEREDBY_PARAM_KEY, anweredBy);
   
   String testURI=builder.build().toString();
   FieldUtils.writeField(handler, "twilioAccountAuth", "AUTHKEY", true);
   
   String protocol =TwilioHelper.PROTOCOL_HTTPS;
   
   String sig = Base64.encodeToString(HmacUtils.hmacSha1 ("AUTHKEY", protocol + sigHost + testURI));
   
   EasyMock.expect(request.getMethod()).andReturn(HttpMethod.GET).anyTimes();
   EasyMock.expect(request.getUri()).andReturn(testURI).anyTimes();
   EasyMock.expect(request.headers()).andReturn(httpHeaders).anyTimes();
   EasyMock.expect(httpHeaders.contains(TwilioHelper.SIGNATURE_HEADER_KEY)).andReturn(true).anyTimes();
   EasyMock.expect(httpHeaders.get(TwilioHelper.SIGNATURE_HEADER_KEY)).andReturn(sig).anyTimes();
   EasyMock.expect(httpHeaders.get(TwilioHelper.HOST_HEADER_KEY)).andReturn(host).anyTimes();
   EasyMock.expect(mockPopulationCacheMgr.getPopulationByPlaceId(EasyMock.anyObject(UUID.class))).andReturn(Population.NAME_GENERAL);
}
 
Example #4
Source File: TestTwilioAckScriptHandler.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
   super.setUp();
   builder = buildParameters(null);
   FieldUtils.writeField(handler, "twilioAccountAuth", "AUTHKEY", true);

   sig = Base64.encodeToString(HmacUtils.hmacSha1 ("AUTHKEY", TwilioHelper.PROTOCOL_HTTPS + "somehost" + builder.toString()));
   EasyMock.expect(request.getUri()).andReturn(builder.toString()).anyTimes();
   EasyMock.expect(request.getMethod()).andReturn(HttpMethod.GET);
   EasyMock.expect(request.headers()).andReturn(httpHeaders).anyTimes();
   
   EasyMock.expect(httpHeaders.contains(TwilioHelper.SIGNATURE_HEADER_KEY)).andReturn(true).anyTimes();
   EasyMock.expect(httpHeaders.get(TwilioHelper.SIGNATURE_HEADER_KEY)).andReturn(sig).anyTimes();
   EasyMock.expect(httpHeaders.get(TwilioHelper.HOST_HEADER_KEY)).andReturn("somehost").anyTimes();
   EasyMock.expect(personDAO.findById(personID)).andReturn(person);
   EasyMock.expect(placeDAO.findById(placeId)).andReturn(place);
   EasyMock.expect(populationCacheMgr.getPopulationByPlaceId(EasyMock.anyObject(UUID.class))).andReturn(Population.NAME_GENERAL).anyTimes();
}
 
Example #5
Source File: GitEventHandler.java    From echo with Apache License 2.0 6 votes vote down vote up
private boolean hasValidGitHubSecureSignature(GitEvent gitEvent, Trigger trigger) {
  String header =
      gitEvent.getDetails().getRequestHeaders().get(GITHUB_SECURE_SIGNATURE_HEADER).get(0);
  log.debug("GitHub Signature detected. " + GITHUB_SECURE_SIGNATURE_HEADER + ": " + header);
  String signature = StringUtils.removeStart(header, "sha1=");

  String computedDigest = HmacUtils.hmacSha1Hex(trigger.getSecret(), gitEvent.getRawContent());

  // TODO: Find constant time comparison algo?
  boolean digestsMatch = signature.equalsIgnoreCase(computedDigest);
  if (!digestsMatch) {
    log.warn("Github Digest mismatch! Pipeline NOT triggered: " + trigger);
    log.debug("computedDigest: " + computedDigest + ", from GitHub: " + signature);
  }

  return digestsMatch;
}
 
Example #6
Source File: InstamojoImpl.java    From instamojo-java with MIT License 6 votes vote down vote up
@Override
public String generateWebhookSignature(Map<String, String> data, String salt) {

    ArrayList<String> keys = new ArrayList<>(data.keySet());
    Collections.sort(keys);

    StringBuilder sb = new StringBuilder();
    for (int index = 0; index < keys.size(); index++) {
        sb.append(data.get(keys.get(index)));
        if (index != keys.size() - 1) {
            sb.append('|');
        }
    }

    return new HmacUtils(HmacAlgorithms.HMAC_SHA_1, salt).hmacHex(sb.toString());
}
 
Example #7
Source File: PatreonServiceImpl.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
@PostConstruct
private void init() {
    List<PatreonUser> activeUsers = repository.findActive();
    activeUsers.forEach(this::enableFeatures);

    String accessToken = workerProperties.getPatreon().getAccessToken();
    if (StringUtils.isNotEmpty(accessToken)) {
        creatorApi = new PatreonAPI(accessToken);
        if (workerProperties.getPatreon().isUpdateEnabled()) {
            scheduler.scheduleWithFixedDelay(this::update, workerProperties.getPatreon().getUpdateInterval());
        }
    } else {
        log.warn("No Patreon credentials specified, integration would not work");
    }
    String webhookSecret = workerProperties.getPatreon().getWebhookSecret();
    if (StringUtils.isNotEmpty(webhookSecret)) {
        webHookHmac = new HmacUtils(HmacAlgorithms.HMAC_MD5, webhookSecret);
    } else {
        log.warn("No Patreon WebHook secret specified, WebHooks would not work");
    }
}
 
Example #8
Source File: MatrixHttpClient.java    From matrix-java-sdk with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void register(MatrixPasswordCredentials credentials, String sharedSecret, boolean admin) {
    // As per synapse registration script:
    // https://github.com/matrix-org/synapse/blob/master/scripts/register_new_matrix_user#L28

    String value = credentials.getLocalPart() + "\0" + credentials.getPassword() + "\0"
            + (admin ? "admin" : "notadmin");
    String mac = new HmacUtils(HmacAlgorithms.HMAC_SHA_1, sharedSecret).hmacHex(value);
    JsonObject body = new JsonObject();
    body.addProperty("user", credentials.getLocalPart());
    body.addProperty("password", credentials.getPassword());
    body.addProperty("mac", mac);
    body.addProperty("type", "org.matrix.login.shared_secret");
    body.addProperty("admin", false);
    URL url = getPath("client", "api", "v1", "register");
    updateContext(execute(new Request.Builder().post(getJsonBody(body)).url(url)));
}
 
Example #9
Source File: GitHubAuth.java    From gocd with Apache License 2.0 5 votes vote down vote up
default void validateAuth(String secret) {
    String signature = request().headers("X-Hub-Signature");

    if (isBlank(signature)) {
        throw die("No HMAC signature specified via 'X-Hub-Signature' header!");
    }

    String expectedSignature = "sha1=" + new HmacUtils(HmacAlgorithms.HMAC_SHA_1, secret).hmacHex(request().body());

    if (!MessageDigest.isEqual(expectedSignature.getBytes(), signature.getBytes())) {
        throw die("HMAC signature specified via 'X-Hub-Signature' did not match!");
    }
}
 
Example #10
Source File: ExtensionUtils.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
public static String computeHMAC(String secret, String... parts) {
    if(parts == null || parts.length == 0) {
        return "";
    }
    var text = Arrays.stream(parts).map(StringUtils::trimToEmpty).collect(Collectors.joining(""));
    return new HmacUtils(HmacAlgorithms.HMAC_SHA_256, secret).hmacHex(text);
}
 
Example #11
Source File: AuthorizationTokenImpl.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #12
Source File: CalcSignature.java    From actor-platform with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #13
Source File: TwilioBaseHandler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private boolean verifySignature(String key, String uri, String signature) {
   byte[] generatedSig = HmacUtils.hmacSha1(key, uri);
   String encodedGeneratedSig = Base64.getEncoder().encodeToString(generatedSig);
   if (signature.equals(encodedGeneratedSig.toString())) {
      return true;
   }
   return false;
}
 
Example #14
Source File: COSSigner.java    From cos-java-sdk-v5 with MIT License 4 votes vote down vote up
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;
}
 
Example #15
Source File: COSSigner.java    From cos-java-sdk-v5 with MIT License 4 votes vote down vote up
public String buildPostObjectSignature(String secretKey, String keyTime, String policy) {
    String signKey = HmacUtils.hmacSha1Hex(secretKey, keyTime);
    String stringToSign = DigestUtils.sha1Hex(policy);
    return HmacUtils.hmacSha1Hex(signKey, stringToSign);
}
 
Example #16
Source File: FacebookBidder.java    From prebid-server-java with Apache License 2.0 4 votes vote down vote up
private String makeAuthId(String requestId) {
    final Mac mac = HmacUtils.getInitializedMac(HmacAlgorithms.HMAC_SHA_256, appSecret.getBytes());
    return Hex.encodeHexString(mac.doFinal(requestId != null ? requestId.getBytes() : null));
}
 
Example #17
Source File: ApacheCloudStackClient.java    From apache-cloudstack-java-client with Apache License 2.0 4 votes vote down vote up
/**
 * 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);
}
 
Example #18
Source File: AuthorizationValidationFilter.java    From pay-publicapi with MIT License 4 votes vote down vote up
private boolean tokenMatchesHmac(String token, String currentHmac) {
    final String hmacCalculatedFromToken = BaseEncoding.base32Hex()
            .lowerCase().omitPadding()
            .encode(new HmacUtils(HmacAlgorithms.HMAC_SHA_1, apiKeyHmacSecret).hmac(token));
    return hmacCalculatedFromToken.equals(currentHmac);
}
 
Example #19
Source File: ApiKeyGenerator.java    From pay-publicapi with MIT License 4 votes vote down vote up
public static String apiKeyValueOf(String token, String secret) {
    byte[] hmacBytes = new HmacUtils(HmacAlgorithms.HMAC_SHA_1, secret).hmac(token);
    String encodedHmac = BaseEncoding.base32Hex().lowerCase().omitPadding().encode(hmacBytes);
    return token + encodedHmac;
}
 
Example #20
Source File: SimpleTokenManager.java    From littleca with Apache License 2.0 4 votes vote down vote up
public  String createToken(String hmacKey,Map<String,String> data) {
	String signData=mapToString(data);
	String sign = Base64.encodeBase64URLSafeString(new HmacUtils(HmacAlgorithms.HMAC_MD5, hmacKey).hmac(signData));
	String token=Base64.encodeBase64URLSafeString(signData.getBytes())+"."+sign;
	return token;
}
 
Example #21
Source File: SimpleTokenManager.java    From littleca with Apache License 2.0 4 votes vote down vote up
public SimpleTokenManager(String hmacKey) {
	this.hmac=new HmacUtils(HmacAlgorithms.HMAC_MD5, hmacKey);
}
 
Example #22
Source File: SimpleTokenManager.java    From littleca with Apache License 2.0 4 votes vote down vote up
public  String createToken(String hmacKey,Map<String,String> data) {
	String signData=mapToString(data);
	String sign = Base64.encodeBase64URLSafeString(new HmacUtils(HmacAlgorithms.HMAC_MD5, hmacKey).hmac(signData));
	String token=Base64.encodeBase64URLSafeString(signData.getBytes())+"."+sign;
	return token;
}
 
Example #23
Source File: SimpleTokenManager.java    From littleca with Apache License 2.0 4 votes vote down vote up
public SimpleTokenManager(String hmacKey) {
	this.hmac=new HmacUtils(HmacAlgorithms.HMAC_MD5, hmacKey);
}
 
Example #24
Source File: PayPalManager.java    From alf.io with GNU General Public License v3.0 4 votes vote down vote up
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));
}
 
Example #25
Source File: Ticket.java    From alf.io with GNU General Public License v3.0 4 votes vote down vote up
public static String hmacSHA256Base64(String key, String code) {
    return Base64.getEncoder().encodeToString(new HmacUtils(HmacAlgorithms.HMAC_SHA_256, key).hmac(code));
}
 
Example #26
Source File: COSSigner.java    From markdown-image-kit with MIT License 4 votes vote down vote up
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;
}
 
Example #27
Source File: MyHmacUtils.java    From spring-boot with Apache License 2.0 2 votes vote down vote up
/**
 * 使用指定的密码对内容生成消息摘要(散列值)
 *
 * @param key
 * @param content
 * @return
 */

public static String hmacSha256Hex(String key, String content) {
    return HmacUtils.hmacSha256Hex(key, content);
}