List of usage examples for javax.crypto Mac doFinal
public final byte[] doFinal(byte[] input) throws IllegalStateException
From source file:com.ai.smart.bottom.helper.MacUtils.java
public static String hmacsha256(String secret, String data) { Mac mac = null; byte[] doFinal = null; try {// www .j a v a2 s. c o m mac = Mac.getInstance(HMAC_ALGORITHM); //??MD5 byte[] dataBytes = DigestUtils.md5(data); //sourcekeyMD5, SecretKey secretkey = new SecretKeySpec(DigestUtils.md5(secret), HMAC_ALGORITHM); mac.init(secretkey); //HmacSHA256 doFinal = mac.doFinal(dataBytes); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (InvalidKeyException e) { } String checksum = Hex.encodeHexString(doFinal).toLowerCase(); return checksum; }
From source file:br.com.vpsa.oauth2android.token.MacTokenTypeDefinition.java
private static String calculateMAC(String key, String normalizedString, String algorithm) { String macString = ""; try {//from w w w.j a v a 2s . com System.out.println("algorithm=" + algorithm); Mac mac = Mac.getInstance(algorithm); mac.init(new SecretKeySpec(key.getBytes(), algorithm)); macString = Base64.encodeToString(mac.doFinal(normalizedString.getBytes()), Base64.DEFAULT); } catch (InvalidKeyException ex) { Logger.getLogger(MacTokenTypeDefinition.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(MacTokenTypeDefinition.class.getName()).log(Level.SEVERE, null, ex); } return macString; }
From source file:ch.threema.apitool.CryptTool.java
/** * Hashes an email address for identity lookup. * * @param email the email address// w w w . j av a 2 s. c om * @return the raw hash */ public static byte[] hashEmail(String email) { try { Mac emailMac = Mac.getInstance("HmacSHA256"); emailMac.init(new SecretKeySpec(EMAIL_HMAC_KEY, "HmacSHA256")); String normalizedEmail = email.toLowerCase().trim(); return emailMac.doFinal(normalizedEmail.getBytes("US-ASCII")); } catch (Exception e) { e.printStackTrace(); return null; } }
From source file:air.com.snagfilms.cast.chromecast.utils.Utils.java
public static String getfilmriseParameters(Context ctx) { StringBuilder strBlr = null;/*from w w w. j a v a 2 s . c o m*/ try { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); long longs = System.currentTimeMillis(); String timestamp = dateFormat.format(longs); ; String stringToSign = timestamp; // Query uses this string // Compute the signature and base64 encode it. String algorithm = "HmacSHA1"; SecretKeySpec key = new SecretKeySpec(SECRET_KEY.getBytes(), algorithm); Mac mac = Mac.getInstance(algorithm); mac.init(key); String signature = new String(Base64.encodeBase64(mac.doFinal(stringToSign.getBytes()))); System.out.println(signature);// required for Query signature = URLEncoder.encode(signature, "UTF-8"); strBlr = new StringBuilder(); strBlr.append(Constants.ACCESS_KEY); strBlr.append("="); strBlr.append(ACCESS_KEY); strBlr.append("&"); strBlr.append(Constants.TIME_STAMP); strBlr.append("="); strBlr.append(timestamp); strBlr.append("&"); strBlr.append(Constants.SIGNATURE); strBlr.append("="); strBlr.append(signature); strBlr.append("&"); strBlr.append(Constants.SITE); strBlr.append("="); strBlr.append(Constants.filmrise); strBlr.append("&"); strBlr.append(Constants.DEVICE); strBlr.append("="); strBlr.append("android"); return strBlr.toString(); } catch (Exception e) { } return null; }
From source file:ch.threema.apitool.CryptTool.java
/** * Hashes a phone number for identity lookup. * * @param phoneNo the phone number/* w w w. j a v a 2s . co m*/ * @return the raw hash */ public static byte[] hashPhoneNo(String phoneNo) { try { Mac phoneMac = Mac.getInstance("HmacSHA256"); phoneMac.init(new SecretKeySpec(PHONENO_HMAC_KEY, "HmacSHA256")); String normalizedPhoneNo = phoneNo.replaceAll("[^0-9]", ""); return phoneMac.doFinal(normalizedPhoneNo.getBytes("US-ASCII")); } catch (Exception e) { e.printStackTrace(); return null; } }
From source file:crow.weibo.util.WeiboUtil.java
/** * Sina tencent HmacSHA1 ???//w w w . j av a2 s . c o m * * @param base * ??? * @param consumerSecret * ??API Secret * @param accessTokenSecret * ?? Access Secret * @return */ public static String hmacSHA1Signature(String base, String consumerSecret, String accessTokenSecret) { String HMAC_SHA1 = "HmacSHA1"; try { Mac mac = Mac.getInstance(HMAC_SHA1); String oauthSignature = encode(consumerSecret) + "&" + ((accessTokenSecret == null) ? "" : encode(accessTokenSecret)); SecretKeySpec spec = new SecretKeySpec(oauthSignature.getBytes(), HMAC_SHA1); mac.init(spec); byte[] bytes = mac.doFinal(base.getBytes()); return new String(BASE64Encoder.encode(bytes)); } catch (Exception e) { } return null; }
From source file:io.syndesis.rest.v1.state.ClientSideState.java
static byte[] mac(final String authenticationAlgorithm, final CharSequence base, final SecretKey authenticationKey) { try {//from www. j ava 2s.c o m final String baseString = base.toString(); final Mac mac = Mac.getInstance(authenticationAlgorithm); mac.init(authenticationKey); // base contains only BASE64 characters and '|', so we use ASCII final byte[] raw = baseString.getBytes(StandardCharsets.US_ASCII); return mac.doFinal(raw); } catch (final GeneralSecurityException e) { throw new IllegalStateException("Unable to compute MAC of the given value", e); } }
From source file:com.profesorfalken.payzen.webservices.sdk.handler.soap.HeaderHandler.java
private static byte[] encode256(byte[] keyBytes, byte[] text) throws NoSuchAlgorithmException, InvalidKeyException { Mac hmacSha1; try {/*from ww w . ja va 2 s.c o m*/ hmacSha1 = Mac.getInstance("HmacSHA256"); } catch (NoSuchAlgorithmException nsae) { hmacSha1 = Mac.getInstance("HMAC-SHA-256"); } SecretKeySpec macKey = new SecretKeySpec(keyBytes, "RAW"); try { hmacSha1.init(macKey); } catch (java.security.InvalidKeyException ex) { logger.error("Error encoding auth hash", ex); } return hmacSha1.doFinal(text); }
From source file:be.cytomine.client.HttpClient.java
public static Header[] authorizeFromRETRIEVAL(String action, String urlFullStr, String contentType, String accept, String publicKey, String privateKey, String host) throws IOException { log.debug("authorize: action=" + action + ", url=" + urlFullStr + ", contentType=" + contentType + ",accept=" + accept); String url = urlFullStr.replace(host, ""); log.debug("authorize: url short=" + url); Header[] headers = new Header[3]; headers[0] = new BasicHeader("accept", accept); headers[1] = new BasicHeader("date", getActualDateStr()); String canonicalHeaders = action + "\n\n" + contentType + "\n" + headers[1].getValue() + "\n"; String messageToSign = canonicalHeaders + url; SecretKeySpec privateKeySign = new SecretKeySpec(privateKey.getBytes(), "HmacSHA1"); try {// w ww . ja va2s. c om Mac mac = Mac.getInstance("HmacSHA1"); mac.init(privateKeySign); byte[] rawHmac = mac.doFinal(new String(messageToSign.getBytes(), "UTF-8").getBytes()); //byte[] signatureBytes = Base64.encodeToByte(rawHmac,false); byte[] signatureBytes = org.apache.commons.codec.binary.Base64.encodeBase64(rawHmac, false); String authorization = "CYTOMINE " + publicKey + ":" + new String(signatureBytes); headers[2] = new BasicHeader("authorization", authorization); } catch (GeneralSecurityException e) { throw new IOException(e); } return headers; }
From source file:com.ibm.sbt.security.encryption.HMACEncryptionUtility.java
public static String generateHMACSignature(String apiUrl, String method, String consumerSecret, String tokenSecret, Map<String, String> paramsSortedMap) throws OAuthException { try {//from w w w. j a v a 2s . c o m String parameterString = generateParameterString(paramsSortedMap); String signature_base_string = generateSignatureBaseString(method, apiUrl, parameterString); String signingKey = null; if (StringUtil.isEmpty(tokenSecret)) { // No token secret is available when call is made from getRequestToken, tokensecret is fetched // later in OADance signingKey = consumerSecret + "&"; } else { signingKey = consumerSecret + "&" + tokenSecret; } byte[] keyBytes = null; try { keyBytes = signingKey.getBytes(Configuration.ENCODING); } catch (UnsupportedEncodingException e) { throw new OAuthException(e, "HMACEncryptionUtility : generateHMACSignature caused UnsupportedEncodingException exception"); } SecretKey secretKey = new SecretKeySpec(keyBytes, "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(secretKey); byte[] text = null; try { text = signature_base_string.getBytes(Configuration.ENCODING); } catch (UnsupportedEncodingException e) { throw new OAuthException(e, "HMACEncryptionUtility : generateHMACSignature caused UnsupportedEncodingException exception"); } String signature = new String(Base64.encodeBase64(mac.doFinal(text))).trim(); return signature; } catch (NoSuchAlgorithmException e) { throw new OAuthException(e, "HMACEncryptionUtility : generateHMACSignature caused NoSuchAlgorithmException exception"); } catch (InvalidKeyException e) { throw new OAuthException(e, "HMACEncryptionUtility : generateHMACSignature caused InvalidKeyException exception"); } }