List of usage examples for javax.crypto Mac init
public final void init(Key key) throws InvalidKeyException
From source file:com.terremark.handlers.CloudApiAuthenticationHandler.java
/** * Returns HMAC instance initialized with the private key. * * @return HMAC instance./*w w w . j av a 2s. c o m*/ * @throws NoSuchAlgorithmException If the HMAC algorithm is not available. * @throws InvalidKeyException If the private key is malformed. * @throws UnsupportedEncodingException If UTF-8 character encoding is not supported. */ private Mac getMac() throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException { String algo; switch (algorithm) { case HMAC_SHA1: algo = "HmacSHA1"; break; case HMAC_SHA256: algo = "HmacSHA256"; break; case HMAC_SHA512: algo = "HmacSHA512"; break; default: throw new UnsupportedOperationException("Not implemented: " + algorithm.toString()); } final Mac mac = Mac.getInstance(algo); mac.init(new SecretKeySpec(privateKey.getBytes("UTF-8"), algo)); return mac; }
From source file:org.cryptonode.jncryptor.AES256v2Cryptor.java
@Override public byte[] encryptData(byte[] plaintext, SecretKey encryptionKey, SecretKey hmacKey) throws CryptorException { Validate.notNull(plaintext, "Plaintext cannot be null."); Validate.notNull(encryptionKey, "Encryption key cannot be null."); Validate.notNull(hmacKey, "HMAC key cannot be null."); byte[] iv = getSecureRandomData(AES_BLOCK_SIZE); try {//from w ww.ja v a 2 s . co m Cipher cipher = Cipher.getInstance(AES_CIPHER_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, encryptionKey, new IvParameterSpec(iv)); byte[] ciphertext = cipher.doFinal(plaintext); AES256v2Ciphertext output = new AES256v2Ciphertext(iv, ciphertext); Mac mac = Mac.getInstance(HMAC_ALGORITHM); mac.init(hmacKey); byte[] hmac = mac.doFinal(output.getDataToHMAC()); output.setHmac(hmac); return output.getRawData(); } catch (GeneralSecurityException e) { throw new CryptorException("Failed to generate ciphertext.", e); } }
From source file:com.altcanvas.asocial.Twitter.java
private byte[] generateSignature(String data) { SecretKeySpec spec = null;/* w w w. ja v a2 s . c o m*/ if (this.tokenSecret == null) { spec = new SecretKeySpec((Http.encode(OAUTH_CONSUMER_SECRET) + "&").getBytes(), HMACSHA1); } else { spec = new SecretKeySpec( (Http.encode(OAUTH_CONSUMER_SECRET) + "&" + Http.encode(tokenSecret)).getBytes(), HMACSHA1); } try { Mac mac = Mac.getInstance(HMACSHA1); mac.init(spec); byte[] byteHMAC = mac.doFinal(data.getBytes()); return Base64.encodeBase64(byteHMAC); } catch (NoSuchAlgorithmException nsae) { } catch (InvalidKeyException ike) { } return null; }
From source file:com.ublish.service.BasicLTIService.java
private String getSignature(OAuthMessage message, String secret) throws OAuthException { try {/*w w w . j a va 2 s .com*/ String baseString = getBaseString(message); byte[] keyBytes = (secret + "&").getBytes(UTF8); SecretKey secretKey = new SecretKeySpec(keyBytes, LaunchParameters.OAUTH_SIGNATURE_METHOD_HMACSHA1); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(secretKey); return Base64Codec.encode(mac.doFinal(baseString.getBytes(UTF8))).trim(); } catch (Exception e) { throw new OAuthException("An exception occurred while creating the OAuth signature.", e); } }
From source file:angel.zhuoxiu.library.pusher.Pusher.java
private String authenticate(String channelName) { if (!isConnected()) { Log.e(LOG_TAG, "pusher not connected, can't create auth string"); return null; }/*from ww w. j a v a 2 s . c o m*/ try { String stringToSign = mSocketId + ":" + channelName; SecretKey key = new SecretKeySpec(mPusherSecret.getBytes(), PUSHER_AUTH_ALGORITHM); Mac mac = Mac.getInstance(PUSHER_AUTH_ALGORITHM); mac.init(key); byte[] signature = mac.doFinal(stringToSign.getBytes()); StringBuffer sb = new StringBuffer(); for (int i = 0; i < signature.length; ++i) { sb.append(Integer.toHexString((signature[i] >> 4) & 0xf)); sb.append(Integer.toHexString(signature[i] & 0xf)); } String authInfo = mPusherKey + ":" + sb.toString(); Log.d(LOG_TAG, "Auth Info " + authInfo); return authInfo; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } return null; }
From source file:com.leacox.pusher.Pusher.java
/** * Returns a HMAC/SHA256 representation of the given data. *//*from w ww.j a v a 2 s . co m*/ private String hmacsha256Representation(String data) { try { // Create the HMAC/SHA256 key from application secret final SecretKeySpec signingKey = new SecretKeySpec(appSecret.getBytes(), "HmacSHA256"); // Create the message authentication code (MAC) final Mac mac = Mac.getInstance("HmacSHA256"); mac.init(signingKey); // Process and return data byte[] digest; // @TODO: decide if it's UTF-8 or not... digest = mac.doFinal(data.getBytes("UTF-8")); digest = mac.doFinal(data.getBytes()); // Convert to string BigInteger bigInteger = new BigInteger(1, digest); return String.format("%0" + (digest.length << 1) + "x", bigInteger); } catch (NoSuchAlgorithmException nsae) { // We should never come here, because GAE has HMac SHA256 throw new RuntimeException("No HMac SHA256 algorithm"); //} catch (UnsupportedEncodingException e) { // We should never come here, because UTF-8 should be available //throw new RuntimeException("No UTF-8"); } catch (InvalidKeyException e) { throw new RuntimeException("Invalid key exception while converting to HMac SHA256"); } }
From source file:com.zxlim.totp.TOTP.java
private final byte[] hmac(final byte[] data) { final Mac mac; try {//from w ww . java 2 s .c om mac = Mac.getInstance(HMAC_ALGORITHM, HMAC_PROVIDER); } catch (NoSuchAlgorithmException | NoSuchProviderException e) { return null; } try { mac.init(new SecretKeySpec(secret, HMAC_ALGORITHM)); } catch (InvalidKeyException e) { return null; } return mac.doFinal(data); }
From source file:io.teak.sdk.Request.java
@Override public void run() { HttpsURLConnection connection = null; SecretKeySpec keySpec = new SecretKeySpec(this.session.appConfiguration.apiKey.getBytes(), "HmacSHA256"); String requestBody;//from www . j a v a 2 s.c o m String hostnameForEndpoint = this.hostname; if (hostnameForEndpoint == null) { hostnameForEndpoint = this.session.remoteConfiguration.getHostnameForEndpoint(this.endpoint); } try { ArrayList<String> payloadKeys = new ArrayList<>(this.payload.keySet()); Collections.sort(payloadKeys); StringBuilder builder = new StringBuilder(); for (String key : payloadKeys) { Object value = this.payload.get(key); if (value != null) { String valueString; if (value instanceof Map) { valueString = new JSONObject((Map) value).toString(); } else if (value instanceof Array) { valueString = new JSONArray(Collections.singletonList(value)).toString(); } else if (value instanceof Collection) { valueString = new JSONArray((Collection) value).toString(); } else { valueString = value.toString(); } builder.append(key).append("=").append(valueString).append("&"); } else { Log.e(LOG_TAG, "Value for key: " + key + " is null."); } } builder.deleteCharAt(builder.length() - 1); String stringToSign = "POST\n" + hostnameForEndpoint + "\n" + this.endpoint + "\n" + builder.toString(); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(keySpec); byte[] result = mac.doFinal(stringToSign.getBytes()); builder = new StringBuilder(); for (String key : payloadKeys) { Object value = this.payload.get(key); String valueString; if (value instanceof Map) { valueString = new JSONObject((Map) value).toString(); } else if (value instanceof Array) { valueString = new JSONArray(Collections.singletonList(value)).toString(); } else if (value instanceof Collection) { valueString = new JSONArray((Collection) value).toString(); } else { valueString = value.toString(); } builder.append(key).append("=").append(URLEncoder.encode(valueString, "UTF-8")).append("&"); } builder.append("sig=") .append(URLEncoder.encode(Base64.encodeToString(result, Base64.NO_WRAP), "UTF-8")); requestBody = builder.toString(); } catch (Exception e) { Log.e(LOG_TAG, "Error signing payload: " + Log.getStackTraceString(e)); return; } try { if (Teak.isDebug) { Log.d(LOG_TAG, "Submitting request to '" + this.endpoint + "': " + new JSONObject(this.payload).toString(2)); } URL url = new URL("https://" + hostnameForEndpoint + this.endpoint); connection = (HttpsURLConnection) url.openConnection(); connection.setRequestProperty("Accept-Charset", "UTF-8"); connection.setUseCaches(false); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(requestBody.getBytes().length)); // Send request DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(requestBody); wr.flush(); wr.close(); // Get Response InputStream is; if (connection.getResponseCode() < 400) { is = connection.getInputStream(); } else { is = connection.getErrorStream(); } BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuilder response = new StringBuilder(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); if (Teak.isDebug) { String responseText = response.toString(); try { responseText = new JSONObject(response.toString()).toString(2); } catch (Exception ignored) { } Log.d(LOG_TAG, "Reply from '" + this.endpoint + "': " + responseText); } // For extending classes done(connection.getResponseCode(), response.toString()); } catch (Exception e) { Log.e(LOG_TAG, Log.getStackTraceString(e)); } finally { if (connection != null) { connection.disconnect(); } } }
From source file:es.onebox.rest.utils.service.QueryService.java
/** * Signs a string with the given key.//ww w.ja v a 2 s. c o m * * @param data * @param key * @return * @throws SignatureException */ private String generate_HMAC_SHA1_Signature(String data, String key) throws SignatureException { String result; try { // get an hmac_sha1 key from the raw key bytes SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(UTF_8), HMAC_SHA1_ALGORITHM); // get an hmac_sha1 Mac instance and initialize with the signing key Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM); mac.init(signingKey); // compute the hmac on input data bytes byte[] rawHmac = mac.doFinal(data.getBytes(UTF_8)); byte[] base64 = Base64.encodeBase64(rawHmac); // base64-encode the hmac result = new String(base64); } catch (Exception e) { throw new SignatureException("Failed to generate HMAC : " + e.getMessage()); } return AUTHORIZATION_HEADER_HMAC_PREFIX + result; }