List of usage examples for javax.crypto Mac doFinal
public final byte[] doFinal(byte[] input) throws IllegalStateException
From source file:com.zegoggles.smssync.auth.XOAuthConsumer.java
private String generateSig(HttpRequest request, HttpParameters requestParameters) throws Exception { String keyString = percentEncode(getConsumerSecret()) + '&' + percentEncode(getTokenSecret()); SecretKey key = new SecretKeySpec(keyString.getBytes(ENCODING), MAC_NAME); Mac mac = Mac.getInstance(MAC_NAME); mac.init(key);/* w ww. ja v a 2 s.c o m*/ String sbs = new SignatureBaseString(request, requestParameters).generate(); return base64(mac.doFinal(sbs.getBytes(ENCODING))); }
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; }/* www . j a va2 s . c om*/ 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:be.fedict.eid.idp.protocol.openid.StatelessServerAssociationStore.java
private Association setHandle(Association association) throws AssociationException, IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, NoSuchProviderException { ByteArrayOutputStream encodedAssociation = new ByteArrayOutputStream(); String type = association.getType(); if (type == Association.TYPE_HMAC_SHA1) { encodedAssociation.write(1);//from w ww .ja v a2 s .c o m } else if (type == Association.TYPE_HMAC_SHA256) { encodedAssociation.write(2); } else { throw new AssociationException("unknown type: " + type); } SecretKey macKey = association.getMacKey(); byte[] macKeyBytes = macKey.getEncoded(); encodedAssociation.write(macKeyBytes); Date expiry = association.getExpiry(); Long time = expiry.getTime(); DataOutputStream dos = new DataOutputStream(encodedAssociation); dos.writeLong(time); dos.flush(); Cipher cipher = Cipher.getInstance(CIPHER_ALGO); byte[] iv = new byte[16]; this.secureRandom.nextBytes(iv); IvParameterSpec ivParameterSpec = new IvParameterSpec(iv); cipher.init(Cipher.ENCRYPT_MODE, this.secretKeySpec, ivParameterSpec); byte[] handleValue = cipher.doFinal(encodedAssociation.toByteArray()); ByteArrayOutputStream result = new ByteArrayOutputStream(); result.write(iv); result.write(handleValue); if (null != this.macSecretKeySpec) { Mac mac = Mac.getInstance("HmacSHA256"); mac.init(this.macSecretKeySpec); byte[] toBeSigned = result.toByteArray(); byte[] signature = mac.doFinal(toBeSigned); result = new ByteArrayOutputStream(); result.write(signature); result.write(iv); result.write(handleValue); } String handle = Base64.encodeBase64URLSafeString(result.toByteArray()); this.secureRandom.setSeed(result.toByteArray()); if (handle.getBytes().length > 255) { throw new AssociationException("handle size > 255"); } if (type == Association.TYPE_HMAC_SHA1) { return Association.createHmacSha1(handle, macKeyBytes, expiry); } else if (type == Association.TYPE_HMAC_SHA256) { return Association.createHmacSha256(handle, macKeyBytes, expiry); } throw new AssociationException("unknown type: " + type); }
From source file:com.ublish.service.BasicLTIService.java
private String getSignature(OAuthMessage message, String secret) throws OAuthException { try {/*from w w w. j av a 2 s. co m*/ 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:co.edu.uniandes.csw.Arquidalgos.usuario.service._UsuarioService.java
@POST @Path("/crearUsuario") public UsuarioDTO crearUsuario(UsuarioDTO usuario) throws Exception { Mac sha256_HMAC = Mac.getInstance("HmacSHA256"); String key = "123"; SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(), "HmacSHA256"); sha256_HMAC.init(secret_key);//from w w w .ja va 2s . co m System.out.println("TO String: " + usuario.toString()); String hash = Hex.encodeHexString(sha256_HMAC.doFinal(usuario.toString().getBytes())); System.out.println("CODIGO HASH: " + hash); System.out.println("CODIGO HASH JSON " + usuario.getHash()); boolean alterado = !(hash.equalsIgnoreCase(usuario.getHash())); System.out.println("Alterado: " + alterado); if (alterado) { throw new Exception("Se han alterado los datos"); } return createUsuario(usuario); }
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 w w w . j a v a2 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:com.quantil.http.HttpProcessor.java
private String createKey() throws Exception { SimpleDateFormat formatter;/*from www . j av a2s . c o m*/ formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z"); currentDate = formatter.format(new Date()); SecretKeySpec signingKey = new SecretKeySpec(pass.getBytes(), "HmacSHA1"); // get an hmac_sha1 Mac instance and initialize with the signing key Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signingKey); // compute the hmac on input data bytes byte[] rawHmac = mac.doFinal(currentDate.getBytes()); Base64 b64 = new Base64(); String pas = user + ":" + new String(b64.encode(rawHmac), "UTF-8"); return new String(b64.encode(pas.getBytes()), "UTF-8"); }
From source file:org.hk.jt.client.core.Request.java
private String getSignature() throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException { String keyString = String.format(SIGN_FORMAT, config.getConsumerSercret(), config.getAccessTokenSercret()); String signatureBaseString = getSignatureBaseString(); Mac mac = Mac.getInstance(this.config.getAlgolithm()); Key key = new SecretKeySpec(keyString.getBytes(), this.config.getAlgolithm()); mac.init(key);//from ww w .ja v a2 s .c o m byte[] digest = mac.doFinal(signatureBaseString.getBytes()); return encodeURL(Base64.encodeBytes(digest)); }
From source file:co.edu.uniandes.csw.Arquidalgos.usuario.service.UsuarioService.java
@POST @Path("/darAmigos") public List<UsuarioDTO> darAmigos(UsuarioDTO usuario) throws Exception { System.out.println("Dar amigos service de: " + usuario.getFacebookId()); Mac sha256_HMAC = Mac.getInstance("HmacSHA256"); String key = "123"; SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(), "HmacSHA256"); sha256_HMAC.init(secret_key);//from w ww .j ava 2 s. c o m System.out.println("TO String: " + usuario.toString()); String hash = Hex.encodeHexString(sha256_HMAC.doFinal(usuario.toString().getBytes())); System.out.println("CODIGO HASH: " + hash); System.out.println("CODIGO HASH JSON " + usuario.getHash()); boolean alterado = !(hash.equalsIgnoreCase(usuario.getHash())); System.out.println("Alterado: " + alterado); if (alterado) { throw new Exception("Se han alterado los datos"); } return this.usuarioLogicService.darAmigosUsuario(usuario.getFacebookId()); }
From source file:nl.esciencecenter.octopus.webservice.mac.MacScheme.java
/** * Computes RFC 2104-compliant HMAC signature. * * @param data//from w w w . j a v a 2 s.c o m * The data to be signed. * @param key * The signing key. * @param algorithm * MAC algorithm implemented by javax.crypto.MAC * @return The Base64-encoded RFC 2104-compliant HMAC signature. * @throws AuthenticationException * when signature generation fails */ private String calculateRFC2104HMAC(String data, String key, String algorithm) throws AuthenticationException { try { Mac mac = Mac.getInstance(algorithm); SecretKeySpec macKey = new SecretKeySpec(key.getBytes(), "RAW"); mac.init(macKey); byte[] signature = mac.doFinal(data.getBytes()); return Base64.encodeBase64String(signature); } catch (InvalidKeyException e) { throw new AuthenticationException("Failed to generate HMAC: " + e.getMessage(), e); } catch (NoSuchAlgorithmException e) { throw new AuthenticationException("Algorithm is not supported", e); } }