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.mastfrog.acteur.twitter.TwitterSign.java

private static String computeSignature(String baseString, String keyString)
        throws GeneralSecurityException, UnsupportedEncodingException {
    SecretKey secretKey = null;/*from   w  ww . jav  a  2s .  c  o m*/

    byte[] keyBytes = keyString.getBytes();
    secretKey = new SecretKeySpec(keyBytes, "HmacSHA1");

    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(secretKey);

    byte[] text = baseString.getBytes();

    //        return new String(Base64.getEncoder().encode(mac.doFinal(text))).trim();
    return new String(Base64.encodeBase64(mac.doFinal(text))).trim();
}

From source file:ch.docbox.elexis.UserDocboxPreferences.java

public static String getSSOSignature(String ts) {

    String username = getDocboxLoginID(false);

    String sha1Password = getSha1DocboxPassword();
    String sha1SecretKey = getSha1DocboxSecretKey();

    String message = username + ":" + ts + ":" + sha1Password; //$NON-NLS-1$ //$NON-NLS-2$
    try {/*  www.j av a2 s  .  com*/
        // get an hmac_sha1 key from the raw key bytes
        SecretKeySpec signingKey;
        signingKey = new SecretKeySpec(sha1SecretKey.getBytes("UTF-8"), "HmacSHA1"); //$NON-NLS-1$//$NON-NLS-2$

        // get an hmac_sha1 Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance("HmacSHA1");//$NON-NLS-1$
        mac.init(signingKey);

        // compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(message.getBytes("UTF-8")); //$NON-NLS-1$

        // base64-encode the hmac
        // If desired, convert the digest into a string
        byte[] base64 = Base64.encodeBase64(rawHmac);
        return new String(base64);
    } catch (java.security.NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:lucee.commons.io.res.type.s3.S3.java

private static byte[] HMAC_SHA1(String key, String message, String charset)
        throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {

    SecretKeySpec sks = new SecretKeySpec(key.getBytes(charset), "HmacSHA1");
    Mac mac = Mac.getInstance(sks.getAlgorithm());
    mac.init(sks);
    mac.update(message.getBytes(charset));
    return mac.doFinal();

}

From source file:uk.bowdlerize.API.java

private static String createSignatureHash(String value, String key)
        throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
    String type = "HmacSHA512";
    SecretKeySpec secret = new SecretKeySpec(key.getBytes(), type);
    Mac mac = Mac.getInstance(type);
    mac.init(secret);
    byte[] bytes = mac.doFinal(value.getBytes());
    return bytesToHex(bytes);
}

From source file:org.ejbca.core.protocol.cmp.CmpMessageHelper.java

public static byte[] protectPKIMessageWithPBE(PKIMessage msg, String keyId, String raSecret, String digestAlgId,
        String macAlgId, int iterationCount)
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException {
    if (LOG.isTraceEnabled()) {
        LOG.trace(">protectPKIMessageWithPBE()");
    }// w w  w  .  j  a va 2  s  .  c  o  m
    // Create the PasswordBased protection of the message
    PKIHeaderBuilder head = getHeaderBuilder(msg.getHeader());
    byte[] keyIdBytes;
    try {
        keyIdBytes = keyId.getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        keyIdBytes = keyId.getBytes();
        LOG.info("UTF-8 not available, using platform default encoding for keyIdBytes.");
    }
    head.setSenderKID(new DEROctetString(keyIdBytes));
    // SHA1
    AlgorithmIdentifier owfAlg = new AlgorithmIdentifier(digestAlgId);
    // iterations, usually something like 1024
    ASN1Integer iteration = new ASN1Integer(iterationCount);
    // HMAC/SHA1
    AlgorithmIdentifier macAlg = new AlgorithmIdentifier(macAlgId);
    // We need some random bytes for the nonce
    byte[] saltbytes = createSenderNonce();
    DEROctetString derSalt = new DEROctetString(saltbytes);

    // Create the new protected return message
    //String objectId = "1.2.840.113533.7.66.13" = passwordBasedMac;
    String objectId = CMPObjectIdentifiers.passwordBasedMac.getId();
    PBMParameter pp = new PBMParameter(derSalt, owfAlg, iteration, macAlg);
    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(new ASN1ObjectIdentifier(objectId), pp);
    head.setProtectionAlg(pAlg);

    // Calculate the protection bits
    byte[] rasecret = raSecret.getBytes();
    byte[] basekey = new byte[rasecret.length + saltbytes.length];
    System.arraycopy(rasecret, 0, basekey, 0, rasecret.length);
    System.arraycopy(saltbytes, 0, basekey, rasecret.length, saltbytes.length);
    // Construct the base key according to rfc4210, section 5.1.3.1
    MessageDigest dig = MessageDigest.getInstance(owfAlg.getAlgorithm().getId(), "BC");
    for (int i = 0; i < iterationCount; i++) {
        basekey = dig.digest(basekey);
        dig.reset();
    }

    PKIHeader pkiHeader = head.build();
    // Do the mac
    String macOid = macAlg.getAlgorithm().getId();
    byte[] protectedBytes = CmpMessageHelper.getProtectedBytes(pkiHeader, msg.getBody()); //ret.getProtectedBytes();
    Mac mac = Mac.getInstance(macOid, "BC");
    SecretKey key = new SecretKeySpec(basekey, macOid);
    mac.init(key);
    mac.reset();
    mac.update(protectedBytes, 0, protectedBytes.length);
    byte[] out = mac.doFinal();
    DERBitString bs = new DERBitString(out);

    if (LOG.isTraceEnabled()) {
        LOG.trace("<protectPKIMessageWithPBE()");
    }
    // Return response as byte array 
    return CmpMessageHelper
            .pkiMessageToByteArray(new PKIMessage(pkiHeader, msg.getBody(), bs, msg.getExtraCerts()));
}

From source file:com.sangupta.jerry.oauth.OAuthUtils.java

/**
 * Generate the signature using the given signing method for the signable
 * using the key string. For OAuth the key string should already be
 * URI-percent-encoded if need be.//from ww  w. j a v  a  2  s  .co  m
 * 
 * @param signable
 *            the string for which the signature needs to be generated
 * 
 * @param keyString
 *            the key string to be used
 * 
 * @param signingMethod
 *            the signing method to be used
 * 
 * @return the signature generated, or <code>null</code> if some exception
 *         occurs
 * 
 * @throws NullPointerException
 *             if the signable string is <code>null</code>/empty.
 */
public static String createSignature(String signable, String keyString, OAuthSignatureMethod signingMethod) {
    if (AssertUtils.isEmpty(signable)) {
        throw new IllegalArgumentException("Signable string cannot be null/empty");
    }

    if (signingMethod == OAuthSignatureMethod.PLAIN_TEXT) {
        return keyString;
    }

    SecretKeySpec key = new SecretKeySpec((keyString).getBytes(StringUtils.CHARSET_UTF8),
            signingMethod.getAlgorithmName());
    Mac mac;
    try {
        mac = Mac.getInstance(signingMethod.getAlgorithmName());
        mac.init(key);
        byte[] bytes = mac.doFinal(signable.getBytes(StringUtils.CHARSET_UTF8));
        return Base64Encoder.encodeToString(bytes, false);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.orange.oidc.secproxy_service.KryptoUtils.java

static String encryptJWE(byte[] bytes, Key pubRsaKey, byte[] cek) {
    // Log.d("","encryptJWE");
    try {//from   w  w w.ja  v  a2  s .  co m
        // A.2.1
        // jwe header already computed as static
        // jweProtectedHeader;

        // A.2.2 Content Encryption Key (CEK)
        if (cek == null) {
            cek = generateRandomKey(256);
        }

        // Log.d("","cek: "+bytesToHex(cek));

        // A.2.3 Key Encryption
        String jweEncrypted64 = encryptRsaB64(cek, pubRsaKey);
        // Log.d("","jweEncrypted "+jweEncrypted64 );

        // A.2.4 Initialization Vector
        byte[] iv_key = generateRandomKey(128);

        // Log.d("","jweInitVector: "+bytesToHex(iv_key));
        String jweInitVector64 = encodeB64(iv_key);
        // Log.d("","jweInitVector64 "+jweInitVector64 );

        // A.2.5 Additional Authenticated Data
        byte[] aad = jweProtectedHeader.getBytes();

        // A.2.6. Content Encryption
        Cipher encrypt = Cipher.getInstance("AES/CBC/PKCS5Padding");

        // check cek result byte array
        if (cek == null || cek.length == 0 || (cek.length % 2) != 0)
            return null;
        int keySize = cek.length / 2;
        Log.d("", "Encryption AES: " + keySize * 8);

        byte aes_key[] = new byte[keySize];
        byte hmac_key[] = new byte[keySize];

        System.arraycopy(cek, 0, hmac_key, 0, keySize);
        System.arraycopy(cek, keySize, aes_key, 0, keySize);

        // Log.d("","hmac_key: "+bytesToHex(hmac_key));
        // Log.d("","aes_key: "+bytesToHex(aes_key));

        encrypt.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(aes_key, "AES"), new IvParameterSpec(iv_key));
        byte[] cryptedBytes = encrypt.doFinal(bytes);
        String cryptedBytes64 = encodeB64(cryptedBytes);

        // compute hmac
        long al = aad.length * 8;

        // concatenate aad, iv_key, cryptedBytes and al 
        byte[] hmacData = new byte[aad.length + iv_key.length + cryptedBytes.length + 8];
        int offset = 0;
        System.arraycopy(aad, offset, hmacData, 0, aad.length);
        offset += aad.length;
        System.arraycopy(iv_key, 0, hmacData, offset, iv_key.length);
        offset += iv_key.length;
        System.arraycopy(cryptedBytes, 0, hmacData, offset, cryptedBytes.length);
        offset += cryptedBytes.length;
        ByteBuffer buffer = ByteBuffer.allocate(8);
        buffer.putLong(al);
        System.arraycopy(buffer.array(), 0, hmacData, offset, 8);

        // hmac
        Mac hmac = Mac.getInstance("HmacSHA256", "SC");
        hmac.init(new SecretKeySpec(hmac_key, "HmacSHA256"));
        byte[] hmacValue = hmac.doFinal(hmacData);

        // authentication tag
        byte[] auth_tag = Arrays.copyOf(hmacValue, 16);
        String auth_tag64 = encodeB64(auth_tag);

        // A.2.7. Complete Representation
        String finalString = jweProtectedHeader + "." + jweEncrypted64 + "." + jweInitVector64 + "."
                + cryptedBytes64 + "." + auth_tag64;

        return finalString;

    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:net.sf.xfd.provider.PublicProvider.java

public static @Nullable Uri publicUri(Context context, CharSequence path, String mode) {
    // XXX suspect coversion
    final String pathString = path.toString();

    final int modeInt = ParcelFileDescriptor.parseMode(mode);

    final Key key = getSalt(context);

    if (key == null) {
        return null;
    }/*from w  w w .  ja  v a2s  .c o  m*/

    final Calendar c = Calendar.getInstance();
    c.add(Calendar.DATE, 1);
    final long l = c.getTimeInMillis();

    final byte[] encoded;
    try {
        final Mac hash = Mac.getInstance("HmacSHA1");
        hash.init(key);

        final byte[] modeBits = new byte[] { (byte) (modeInt >> 24), (byte) (modeInt >> 16),
                (byte) (modeInt >> 8), (byte) modeInt, };
        hash.update(modeBits);

        final byte[] expiryDate = new byte[] { (byte) (l >> 56), (byte) (l >> 48), (byte) (l >> 40),
                (byte) (l >> 32), (byte) (l >> 24), (byte) (l >> 16), (byte) (l >> 8), (byte) l, };
        hash.update(expiryDate);

        encoded = hash.doFinal(pathString.getBytes());
    } catch (NoSuchAlgorithmException | InvalidKeyException e) {
        throw new AssertionError("Error while creating a hash: " + e.getMessage(), e);
    }

    final String packageName = context.getPackageName();

    final Uri.Builder b = new Uri.Builder().scheme(SCHEME_CONTENT).authority(packageName + AUTHORITY_SUFFIX);

    if (!"r".equals(mode)) {
        b.appendQueryParameter(URI_ARG_MODE, mode);
    }

    return b.path(pathString).appendQueryParameter(URI_ARG_EXPIRY, String.valueOf(l))
            .appendQueryParameter(URI_ARG_COOKIE, encodeToString(encoded, URL_SAFE | NO_WRAP | NO_PADDING))
            .build();
}

From source file:org.apache.myfaces.shared_ext202patch.util.StateUtils.java

public static byte[] encrypt(byte[] insecure, ExternalContext ctx) {

    if (ctx == null)
        throw new NullPointerException("ExternalContext ctx");

    testConfiguration(ctx);/*from   w  w w .  ja  v a  2s. c om*/

    SecretKey secretKey = (SecretKey) getSecret(ctx);
    String algorithm = findAlgorithm(ctx);
    String algorithmParams = findAlgorithmParams(ctx);
    byte[] iv = findInitializationVector(ctx);

    SecretKey macSecretKey = (SecretKey) getMacSecret(ctx);
    String macAlgorithm = findMacAlgorithm(ctx);

    try {
        // keep local to avoid threading issue
        Mac mac = Mac.getInstance(macAlgorithm);
        mac.init(macSecretKey);
        Cipher cipher = Cipher.getInstance(algorithm + "/" + algorithmParams);
        if (iv != null) {
            IvParameterSpec ivSpec = new IvParameterSpec(iv);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);
        } else {
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        }
        if (log.isLoggable(Level.FINE)) {
            log.fine("encrypting w/ " + algorithm + "/" + algorithmParams);
        }

        //EtM Composition Approach
        int macLenght = mac.getMacLength();
        byte[] secure = new byte[cipher.getOutputSize(insecure.length) + macLenght];
        int secureCount = cipher.doFinal(insecure, 0, insecure.length, secure);
        mac.update(secure, 0, secureCount);
        mac.doFinal(secure, secureCount);

        return secure;
    } catch (Exception e) {
        throw new FacesException(e);
    }
}

From source file:org.apache.myfaces.shared_ext202patch.util.StateUtils.java

public static byte[] decrypt(byte[] secure, ExternalContext ctx) {
    if (ctx == null)
        throw new NullPointerException("ExternalContext ctx");

    testConfiguration(ctx);//from  www. j  av  a 2s .  c o m

    SecretKey secretKey = (SecretKey) getSecret(ctx);
    String algorithm = findAlgorithm(ctx);
    String algorithmParams = findAlgorithmParams(ctx);
    byte[] iv = findInitializationVector(ctx);

    SecretKey macSecretKey = (SecretKey) getMacSecret(ctx);
    String macAlgorithm = findMacAlgorithm(ctx);

    try {
        // keep local to avoid threading issue
        Mac mac = Mac.getInstance(macAlgorithm);
        mac.init(macSecretKey);
        Cipher cipher = Cipher.getInstance(algorithm + "/" + algorithmParams);
        if (iv != null) {
            IvParameterSpec ivSpec = new IvParameterSpec(iv);
            cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);
        } else {
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
        }
        if (log.isLoggable(Level.FINE)) {
            log.fine("decrypting w/ " + algorithm + "/" + algorithmParams);
        }

        //EtM Composition Approach
        int macLenght = mac.getMacLength();
        mac.update(secure, 0, secure.length - macLenght);
        byte[] signedDigestHash = mac.doFinal();

        boolean isMacEqual = true;
        for (int i = 0; i < signedDigestHash.length; i++) {
            if (signedDigestHash[i] != secure[secure.length - macLenght + i]) {
                isMacEqual = false;
                // MYFACES-2934 Must compare *ALL* bytes of the hash, 
                // otherwise a side-channel timing attack is theorically possible
                // but with a very very low probability, because the
                // comparison time is too small to be measured compared to
                // the overall request time and in real life applications,
                // there are too many uncertainties involved.
                //break;
            }
        }
        if (!isMacEqual) {
            throw new ViewExpiredException();
        }

        return cipher.doFinal(secure, 0, secure.length - macLenght);
    } catch (Exception e) {
        throw new FacesException(e);
    }
}