List of usage examples for javax.crypto Mac init
public final void init(Key key) throws InvalidKeyException
From source file:org.glite.slcs.caclient.impl.CMPRequest.java
private static byte[] makeProtection(String secret, int iterCount, String owfAlgId, String macAlgId, DEROctetString salt, PKIMessage message) { byte[] saltBytes = salt.getOctets(); byte[] sharedSecret = secret.getBytes(); byte[] firstKey = new byte[sharedSecret.length + saltBytes.length]; for (int i = 0; i < sharedSecret.length; i++) { firstKey[i] = sharedSecret[i];//from w w w . j av a 2 s . c om } for (int i = 0; i < saltBytes.length; i++) { firstKey[sharedSecret.length + i] = saltBytes[i]; } // Construct the base key according to rfc4210, section 5.1.3.1 MessageDigest dig = null; Mac mac = null; try { dig = MessageDigest.getInstance(owfAlgId, "BC"); for (int i = 0; i < iterCount; i++) { firstKey = dig.digest(firstKey); dig.reset(); } mac = Mac.getInstance(macAlgId, "BC"); SecretKey key = new SecretKeySpec(firstKey, macAlgId); mac.init(key); } catch (Exception e) { log.error("Error while calculating PKIMessage protection", e); } mac.reset(); byte[] protectedBytes = message.getProtectedBytes(); mac.update(protectedBytes, 0, protectedBytes.length); return mac.doFinal(); }
From source file:org.apache.nifi.processors.standard.util.crypto.scrypt.Scrypt.java
/** * Implementation of the <a href="http://www.tarsnap.com/scrypt/scrypt.pdf">scrypt KDF</a>. * * @param password password/*from www.ja v a2 s.c o m*/ * @param salt salt * @param n CPU cost parameter * @param r memory cost parameter * @param p parallelization parameter * @param dkLen intended length of the derived key in bits * @return the derived key * @throws GeneralSecurityException when HMAC_SHA256 is not available */ protected static byte[] deriveScryptKey(byte[] password, byte[] salt, int n, int r, int p, int dkLen) throws GeneralSecurityException { if (n < 2 || (n & (n - 1)) != 0) { throw new IllegalArgumentException("N must be a power of 2 greater than 1"); } if (r < 1) { throw new IllegalArgumentException("Parameter r must be 1 or greater"); } if (p < 1) { throw new IllegalArgumentException("Parameter p must be 1 or greater"); } if (n > MAX_VALUE / 128 / r) { throw new IllegalArgumentException("Parameter N is too large"); } // Must be enforced before r check if (p > MAX_VALUE / 128) { throw new IllegalArgumentException("Parameter p is too large"); } if (r > MAX_VALUE / 128 / p) { throw new IllegalArgumentException("Parameter r is too large"); } if (password == null || password.length == 0) { throw new IllegalArgumentException("Password cannot be empty"); } int saltLength = salt == null ? 0 : salt.length; if (salt == null || saltLength == 0) { // Do not enforce this check here. According to the scrypt spec, the salt can be empty. However, in the user-facing ScryptCipherProvider, enforce an arbitrary check to avoid empty salts logger.warn("An empty salt was used for scrypt key derivation"); // throw new IllegalArgumentException("Salt cannot be empty"); // as the Exception is not being thrown, prevent NPE if salt is null by setting it to empty array if (salt == null) salt = new byte[] {}; } if (saltLength < 8 || saltLength > 32) { // Do not enforce this check here. According to the scrypt spec, the salt can be empty. However, in the user-facing ScryptCipherProvider, enforce an arbitrary check of [8..32] bytes logger.warn("A salt of length {} was used for scrypt key derivation", saltLength); // throw new IllegalArgumentException("Salt must be between 8 and 32 bytes"); } Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(password, "HmacSHA256")); byte[] b = new byte[128 * r * p]; byte[] xy = new byte[256 * r]; byte[] v = new byte[128 * r * n]; int i; pbkdf2(mac, salt, 1, b, p * 128 * r); for (i = 0; i < p; i++) { smix(b, i * 128 * r, r, n, v, xy); } byte[] dk = new byte[dkLen / 8]; pbkdf2(mac, b, 1, dk, dkLen / 8); return dk; }
From source file:com.akamai.edgegrid.auth.EdgeGridV1Signer.java
/** * Helper method to calculate the HMAC signature of a given string. * /*from w ww . j a v a2 s . co m*/ * @param s the string to sign. * @param key the key for the signature. * @param algorithm the signing algorithm. * @return the HMac signature. * @throws RequestSigningException */ private static byte[] sign(String s, byte[] key, String algorithm) throws RequestSigningException { try { SecretKeySpec signingKey = new SecretKeySpec(key, algorithm); Mac mac = Mac.getInstance(algorithm); mac.init(signingKey); byte[] valueBytes = s.getBytes(CHARSET); return mac.doFinal(valueBytes); } catch (NoSuchAlgorithmException nsae) { throw new RequestSigningException("Failed to sign: algorithm not found", nsae); } catch (InvalidKeyException ike) { throw new RequestSigningException("Failed to sign: invalid key", ike); } catch (UnsupportedEncodingException uee) { throw new RequestSigningException("Failed to sign: invalid string encoding", uee); } }
From source file:eap.util.EDcodeUtil.java
private static byte[] hmac(byte[] data, byte[] key, String algorithm) { try {/*from ww w .j av a 2 s.co m*/ SecretKey secretKey = new SecretKeySpec(key, algorithm); Mac mac = Mac.getInstance(secretKey.getAlgorithm(), provider); mac.init(secretKey); return mac.doFinal(data); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException("No such algorithm [" + algorithm + "]"); } catch (InvalidKeyException e) { throw new IllegalArgumentException(e.getMessage(), e); } }
From source file:at.alladin.rmbt.shared.Helperfunctions.java
public static String calculateHMAC(final String secret, final String data) { try {// w w w . ja v a 2 s. c om final SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(), "HmacSHA1"); final Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signingKey); final byte[] rawHmac = mac.doFinal(data.getBytes()); final String result = new String(Base64.encodeBytes(rawHmac)); return result; } catch (final GeneralSecurityException e) { System.out.println("Unexpected error while creating hash: " + e.getMessage()); return ""; } }
From source file:com.imaginary.home.controller.CloudService.java
static public String sign(byte[] key, String stringToSign) throws Exception { Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(key, "HmacSHA256")); return new String(Base64.encodeBase64(mac.doFinal(stringToSign.getBytes("utf-8")))); }
From source file:org.dasein.cloud.terremark.Terremark.java
private static String sign(byte[] key, String authString, String algorithm) throws InternalException { try {//from www . j a v a 2s.c om Mac mac = Mac.getInstance(algorithm); mac.init(new SecretKeySpec(key, algorithm)); return new String(Base64.encodeBase64(mac.doFinal(authString.getBytes("utf-8")))); } catch (NoSuchAlgorithmException e) { logger.error(e); e.printStackTrace(); throw new InternalException(e); } catch (InvalidKeyException e) { logger.error(e); e.printStackTrace(); throw new InternalException(e); } catch (IllegalStateException e) { logger.error(e); e.printStackTrace(); throw new InternalException(e); } catch (UnsupportedEncodingException e) { logger.error(e); e.printStackTrace(); throw new InternalException(e); } }
From source file:com.petercho.Encoder.java
public static byte[] getHmac(String secretKey, String payload, String hmacType) { final Mac mac; byte[] hmac;/* ww w . j a v a2 s .c o m*/ try { final byte[] secretKeyBytes; if (secretKey == null) { secretKeyBytes = new byte[] { 0 }; } else { secretKeyBytes = secretKey.getBytes(DEFAULT_ENCODING); } if (payload == null) { payload = ""; } SecretKeySpec keySpec = new SecretKeySpec(secretKeyBytes, hmacType); mac = Mac.getInstance(hmacType); mac.init(keySpec); hmac = mac.doFinal(payload.getBytes(DEFAULT_ENCODING)); } catch (NoSuchAlgorithmException e) { String msg = "An error occurred initializing algorithm '" + hmacType + "', e: " + e; throw new IllegalStateException(msg, e); } catch (InvalidKeyException e) { String msg = "An error occurred initializing key, e: " + e; throw new IllegalStateException(msg, e); } catch (UnsupportedEncodingException e) { String msg = "Invalid encoding, e: " + e; throw new IllegalStateException(msg, e); } return hmac; }
From source file:ac.elements.io.Signature.java
/** * Computes RFC 2104-compliant HMAC signature. * //w w w.j a v a2 s .c om * @param data * the data * @param key * the key * @param algorithm * the algorithm * * @return the string * @throws SignatureException */ private static String sign(String data, String key, String algorithm) throws SignatureException { if (key == null) throw new SignatureException("Encoding key is null."); byte[] signature = null; try { Mac mac = Mac.getInstance(algorithm); mac.init(new SecretKeySpec(key.getBytes(), algorithm)); signature = Base64.encodeBase64(mac.doFinal(data.getBytes(DEFAULT_ENCODING))); } catch (Exception e) { log.error("Failed to generate signature: " + e.getMessage(), e); } return new String(signature); }
From source file:com.eucalyptus.ws.util.HmacUtils.java
public static String getSignature(final String queryKey, final String subject, final Hmac mac) throws AuthenticationException { SecretKeySpec signingKey = new SecretKeySpec(queryKey.getBytes(), mac.toString()); try {/*from ww w.java2s .co m*/ Mac digest = mac.getInstance(); digest.init(signingKey); byte[] rawHmac = digest.doFinal(subject.getBytes()); return Base64.encode(rawHmac).replaceAll("=", ""); } catch (Exception e) { LOG.error(e, e); throw new AuthenticationException("Failed to compute signature"); } }