Example usage for javax.crypto Mac init

List of usage examples for javax.crypto Mac init

Introduction

In this page you can find the example usage for javax.crypto Mac init.

Prototype

public final void init(Key key) throws InvalidKeyException 

Source Link

Document

Initializes this Mac object with the given key.

Usage

From source file:com.xeiam.xchange.mtgox.v2.service.streaming.SocketMessageFactory.java

private String signedCall(String endPoint, Map<String, String> params, String reqId)
        throws JsonProcessingException, UnsupportedEncodingException {

    long nonce = MtGoxUtils.getNonce();

    HashMap<String, Object> call = new HashMap<String, Object>(6);
    call.put("id", reqId);
    call.put("call", endPoint);
    call.put("nonce", nonce);
    call.put("params", params);

    ObjectMapper mapper = new ObjectMapper();
    String callString = mapper.writeValueAsString(call);
    String signedCall = null;//from www.  j av a2s .co  m

    try {
        byte[] bsecret = Base64.decode(this.apiSecret);
        SecretKeySpec spec = new SecretKeySpec(bsecret, "HmacSHA512");
        Mac mac = Mac.getInstance("HmacSHA512");
        mac.init(spec);

        byte[] bsig = mac.doFinal(callString.getBytes());
        byte[] keyB = fromHexString(this.apiKey.replaceAll("-", ""));
        byte[] callB = callString.getBytes();

        byte[] c = new byte[bsig.length + keyB.length + callB.length];
        System.arraycopy(keyB, 0, c, 0, keyB.length);
        System.arraycopy(bsig, 0, c, keyB.length, bsig.length);
        System.arraycopy(callB, 0, c, keyB.length + bsig.length, callB.length);

        signedCall = Base64.encodeBytes(c);

    } catch (Exception e) {
        System.out.println("e!: " + e);

    }

    HashMap<String, String> msg = new HashMap<String, String>(4);
    msg.put("op", "call");
    msg.put("call", signedCall);
    msg.put("id", reqId);
    msg.put("context", "mtgox.com");

    mapper = new ObjectMapper();
    return mapper.writeValueAsString(msg);
}

From source file:be.fedict.eid.idp.protocol.openid.StatelessServerAssociationStore.java

private Association loadFromHandle(String handle)
        throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException,
        BadPaddingException, IOException, InvalidAlgorithmParameterException {
    byte[] encodedHandle = Base64.decodeBase64(handle);
    if (null != this.macSecretKeySpec) {
        byte[] signature = new byte[32];
        System.arraycopy(encodedHandle, 0, signature, 0, 32);
        byte[] toBeSigned = new byte[encodedHandle.length - 32];
        System.arraycopy(encodedHandle, 32, toBeSigned, 0, encodedHandle.length - 32);
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(this.macSecretKeySpec);
        byte[] actualSignature = mac.doFinal(toBeSigned);
        if (false == Arrays.equals(actualSignature, signature)) {
            return null;
        }//from   w  ww  . j a va  2 s  . c o  m
        encodedHandle = toBeSigned;
    }
    byte[] iv = new byte[16];
    System.arraycopy(encodedHandle, 0, iv, 0, iv.length);
    byte[] encodedData = Arrays.copyOfRange(encodedHandle, 16, encodedHandle.length);
    Cipher cipher = Cipher.getInstance(CIPHER_ALGO);
    IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
    cipher.init(Cipher.DECRYPT_MODE, this.secretKeySpec, ivParameterSpec);
    byte[] associationBytes = cipher.doFinal(encodedData);
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(associationBytes);
    int typeByte = byteArrayInputStream.read();
    if (typeByte == 1) {
        byte[] macKeyBytes = new byte[160 / 8];
        byteArrayInputStream.read(macKeyBytes);
        DataInputStream dataInputStream = new DataInputStream(byteArrayInputStream);
        long exp = dataInputStream.readLong();
        Date expDate = new Date(exp);
        return Association.createHmacSha1(handle, macKeyBytes, expDate);
    } else if (typeByte == 2) {
        byte[] macKeyBytes = new byte[256 / 8];
        byteArrayInputStream.read(macKeyBytes);
        DataInputStream dataInputStream = new DataInputStream(byteArrayInputStream);
        long exp = dataInputStream.readLong();
        Date expDate = new Date(exp);
        return Association.createHmacSha256(handle, macKeyBytes, expDate);
    } else {
        return null;
    }
}

From source file:com.tapcentive.minimalist.JWTHelper.java

/***
 * Generates a JSON Web Token. This token uses the supplied application key to sign the token
 * content which should uniquely identify the client's customer (e.g. a loyalty number, email
 * etc.) and contain any Tapcentive audience IDs assigned to this customer. This example does
 * not require that either parameter be present.
 * @param originalBody/*from  w w w  .j a  v a2s  .com*/
 * @param audiences
 * @param customerId
 * @return
 */
public String createJWT(JSONObject originalBody, List<String> audiences, String customerId) {

    try {
        JSONObject header = new JSONObject();
        JSONObject body = new JSONObject(originalBody.toString());
        header.put("typ", "JWT");
        header.put("alg", "HS256");
        body.put("iss", _keyid);

        if ((audiences != null) && (audiences.size() > 0)) {
            JSONArray attrArray = new JSONArray(audiences);
            body.put("audiences", attrArray);
        }

        if (customerId != null) {
            body.put("customer_xid", customerId);
        }

        String signedContent = Base64.encodeToString(header.toString().getBytes("UTF-8"), Base64.NO_WRAP) + "."
                + Base64.encodeToString(body.toString().getBytes("UTF-8"), Base64.NO_WRAP);
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(_key.getBytes("UTF-8"), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        String signature = Base64.encodeToString(sha256_HMAC.doFinal(signedContent.getBytes("UTF-8")),
                Base64.NO_WRAP);
        return signedContent + "." + signature;
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.google.gwtjsonrpc.server.SignedToken.java

private Mac newMac() throws XsrfException {
    try {//from w w  w  .j a va 2  s  . c  o  m
        final Mac m = Mac.getInstance(MAC_ALG);
        m.init(key);
        return m;
    } catch (NoSuchAlgorithmException e) {
        throw new XsrfException(MAC_ALG + " not supported", e);
    } catch (InvalidKeyException e) {
        throw new XsrfException("Invalid private key", e);
    }
}

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);// w  ww  . j  a  v a2s .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:co.edu.uniandes.csw.Arquidalgos.usuario.service.UsuarioService.java

@POST
@Path("/agregarAmigos")
public List<UsuarioDTO> agregarAmigos(UsuarioAmigosDTO usuarioAmigos) throws Exception {

    Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
    String key = "123";
    SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(), "HmacSHA256");
    sha256_HMAC.init(secret_key);

    String x = usuarioAmigos.toString();
    System.out.println("TO String: " + x);

    String hash = Hex.encodeHexString(sha256_HMAC.doFinal(x.getBytes()));
    System.out.println("CODIGO HASH: " + hash);
    System.out.println("CODIGO HASH JSON " + usuarioAmigos.getHash());

    boolean alterado = !(hash.equalsIgnoreCase(usuarioAmigos.getHash()));
    System.out.println("Alterado: " + alterado);

    if (alterado) {
        System.out.println("Alterado el sistema");
    }//ww  w .  ja v  a 2  s. co  m
    return this.usuarioLogicService.agregarAmigos(usuarioAmigos);
}

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);

    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");
    }// w  w  w .j  av  a2s  .  co  m

    return this.usuarioLogicService.darAmigosUsuario(usuario.getFacebookId());
}

From source file:com.microsoft.valda.oms.OmsAppender.java

private void sendLog(LoggingEvent event)
        throws NoSuchAlgorithmException, InvalidKeyException, IOException, HTTPException {
    //create JSON message
    JSONObject obj = new JSONObject();
    obj.put("LOGBACKLoggerName", event.getLoggerName());
    obj.put("LOGBACKLogLevel", event.getLevel().toString());
    obj.put("LOGBACKMessage", event.getFormattedMessage());
    obj.put("LOGBACKThread", event.getThreadName());
    if (event.getCallerData() != null && event.getCallerData().length > 0) {
        obj.put("LOGBACKCallerData", event.getCallerData()[0].toString());
    } else {/*from   ww w. j a  v a2  s  . com*/
        obj.put("LOGBACKCallerData", "");
    }
    if (event.getThrowableProxy() != null) {
        obj.put("LOGBACKStackTrace", ThrowableProxyUtil.asString(event.getThrowableProxy()));
    } else {
        obj.put("LOGBACKStackTrace", "");
    }
    if (inetAddress != null) {
        obj.put("LOGBACKIPAddress", inetAddress.getHostAddress());
    } else {
        obj.put("LOGBACKIPAddress", "0.0.0.0");
    }
    String json = obj.toJSONString();

    String Signature = "";
    String encodedHash = "";
    String url = "";

    // Todays date input for OMS Log Analytics
    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    String timeNow = dateFormat.format(calendar.getTime());

    // String for signing the key
    String stringToSign = "POST\n" + json.length() + "\napplication/json\nx-ms-date:" + timeNow + "\n/api/logs";
    byte[] decodedBytes = Base64.decodeBase64(sharedKey);
    Mac hasher = Mac.getInstance("HmacSHA256");
    hasher.init(new SecretKeySpec(decodedBytes, "HmacSHA256"));
    byte[] hash = hasher.doFinal(stringToSign.getBytes());

    encodedHash = DatatypeConverter.printBase64Binary(hash);
    Signature = "SharedKey " + customerId + ":" + encodedHash;

    url = "https://" + customerId + ".ods.opinsights.azure.com/api/logs?api-version=2016-04-01";
    URL objUrl = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) objUrl.openConnection();
    con.setDoOutput(true);
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/json");
    con.setRequestProperty("Log-Type", logType);
    con.setRequestProperty("x-ms-date", timeNow);
    con.setRequestProperty("Authorization", Signature);

    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(json);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    if (responseCode != 200) {
        throw new HTTPException(responseCode);
    }
}

From source file:com.weibo.api.OAuth2.java

private String parseSignedRequest(String signedRequest, String appSecret) {
    String tokenInfoValue = null;
    String[] tokens = StringUtils.split(signedRequest, "\\.", 2);
    // base64Token
    String base64Token = tokens[0];
    //  url encode/decode ??base64url ??
    // '+''/'??'-''_''=' ???base64?'='?
    int padding = (4 - base64Token.length() % 4);
    for (int i = 0; i < padding; i++) {
        base64Token += "=";
    }//  w w  w .  j  av a  2s .c om
    base64Token = StringUtils.replace(base64Token, "-", "+");
    base64Token = StringUtils.replace(base64Token, "_", "/");
    // base64Token1
    String token1 = tokens[1];
    SecretKey key = new SecretKeySpec(appSecret.getBytes(), ALGORITHM_HMACSHA256);
    try {
        Mac mac = Mac.getInstance(ALGORITHM_HMACSHA256);
        mac.init(key);
        mac.update(token1.getBytes());
        byte[] macResult = mac.doFinal();
        String base64Token1 = Base64.encodeBase64String(macResult);
        // access token
        if (StringUtils.equals(base64Token, base64Token1)) {
            tokenInfoValue = new String(Base64.decodeBase64(token1));
            log.info(tokenInfoValue);
        }
    } catch (NoSuchAlgorithmException e) {
        log.error(ExceptionUtils.getFullStackTrace(e));
    } catch (InvalidKeyException e) {
        log.error(ExceptionUtils.getFullStackTrace(e));
    }
    return tokenInfoValue;
}

From source file:com.here.account.auth.OAuth1SignerTest.java

protected String HmacSHAN(String keyString, String algorithm, String baseString)
        throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
    /*/*from  ww  w.  j  av a2s . c o m*/
             byte[] keyBytes = (urlEncode(consumerSecret) + "&").getBytes(OAuthConstants.UTF_8_CHARSET);
    SecretKeySpec signingKey = new SecretKeySpec(keyBytes, signatureMethod);
            
    //generate signature based on the requested signature method
    Mac mac = Mac.getInstance(signatureMethod);
    mac.init(signingKey);
    byte[] signedBytes = mac.doFinal(bytesToSign);
    return Base64.encodeBase64String(signedBytes);
            
     */
    byte[] keyBytes = keyString.getBytes("UTF-8");
    Key signingKey = new SecretKeySpec(keyBytes, algorithm);
    Mac mac = Mac.getInstance(algorithm);
    mac.init(signingKey);

    //generate signature bytes
    byte[] signatureBytes = mac.doFinal(baseString.getBytes("UTF-8"));

    // base64-encode the hmac
    //return new Base64().encodeAsString(signatureBytes);
    return Base64.encodeBase64String(signatureBytes);
}