List of usage examples for javax.crypto Mac doFinal
public final byte[] doFinal(byte[] input) throws IllegalStateException
From source file:org.apache.abdera.ext.oauth.OAuthScheme.java
private String sign(String method, String baseString, Certificate cert) throws AuthenticationException { if (method.equalsIgnoreCase("HMAC-MD5") || method.equalsIgnoreCase("HMAC-SHA1")) { try {//w w w . j a v a 2 s. c o m String[] tokens = method.split("-"); String methodName = tokens[0].substring(0, 1).toUpperCase() + tokens[0].substring(1).toLowerCase() + tokens[1]; KeyGenerator kg = KeyGenerator.getInstance(methodName); Mac mac = Mac.getInstance(kg.getAlgorithm()); mac.init(kg.generateKey()); byte[] result = mac.doFinal(baseString.getBytes()); return new String(Base64.encodeBase64(result)); } catch (Exception e) { throw new AuthenticationException(e.getMessage(), e); } } else if (method.equalsIgnoreCase("md5")) { return new String(Base64.encodeBase64(DigestUtils.md5(baseString))); } else if (method.equalsIgnoreCase("sha1")) { return new String(Base64.encodeBase64(DigestUtils.sha(baseString))); } else if (method.equalsIgnoreCase("RSA-SHA1")) { if (cert == null) { throw new AuthenticationException("a cert is mandatory to use SHA1 with RSA"); } try { Cipher cipher = Cipher.getInstance("SHA1withRSA"); cipher.init(Cipher.ENCRYPT_MODE, cert); byte[] result = cipher.doFinal(baseString.getBytes()); return new String(Base64.encodeBase64(result)); } catch (Exception e) { throw new AuthenticationException(e.getMessage(), e); } } else { throw new AuthenticationException("unsupported algorithm method: " + method); } }
From source file:org.onebusaway.geocoder.enterprise.impl.EnterpriseGoogleGeocoderImpl.java
/** * PRIVATE METHODS/* w w w . j ava 2s. co m*/ */ private String signRequest(String key, String resource) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, URISyntaxException { key = key.replace('-', '+'); key = key.replace('_', '/'); byte[] base64edKey = Base64.decodeBase64(key.getBytes()); // Get an HMAC-SHA1 signing key from the raw key bytes SecretKeySpec sha1Key = new SecretKeySpec(base64edKey, "HmacSHA1"); // Get an HMAC-SHA1 Mac instance and initialize it with the HMAC-SHA1 key Mac mac = Mac.getInstance("HmacSHA1"); mac.init(sha1Key); // compute the binary signature for the request byte[] sigBytes = mac.doFinal(resource.getBytes()); // base 64 encode the binary signature String signature = new String(Base64.encodeBase64(sigBytes)); // convert the signature to 'web safe' base 64 signature = signature.replace('+', '-'); signature = signature.replace('/', '_'); return resource + "&signature=" + signature; }
From source file:org.dasein.cloud.qingcloud.util.requester.QingCloudRequestBuilder.java
private String doMac(byte[] accessKeySecret, String stringToSign) throws InternalException { String signature;//ww w. jav a2 s. com try { Mac mac = Mac.getInstance(SIGNATURE_ALGORITHM); mac.init(new SecretKeySpec(accessKeySecret, SIGNATURE_ALGORITHM)); byte[] signedData = mac.doFinal(stringToSign.getBytes(ENCODING)); signature = new String(Base64.encodeBase64(signedData)); } catch (NoSuchAlgorithmException noSuchAlgorithmException) { logger.error("AliyunRequestBuilderStrategy.sign() failed due to algorithm not supported: " + noSuchAlgorithmException.getMessage()); throw new InternalException(noSuchAlgorithmException); } catch (InvalidKeyException invalidKeyException) { logger.error("AliyunRequestBuilderStrategy.sign() failed due to key invalid: " + invalidKeyException.getMessage()); throw new InternalException(invalidKeyException); } catch (UnsupportedEncodingException unsupportedEncodingException) { logger.error("AliyunMethod.sign() failed due to encoding not supported: " + unsupportedEncodingException.getMessage()); throw new InternalException(unsupportedEncodingException); } return signature; }
From source file:mitm.common.security.otp.HMACOTPGenerator.java
@Override public String generate(byte[] secret, byte[] counter, int byteLength) throws OTPException { Mac mac = createMAC(secret); /*//from w w w.ja va2 s . c o m * Convert the password to base32 to make it easier for end users to read and * limit the number of bytes to make the password not too long */ return Base32.encode(ArrayUtils.subarray(mac.doFinal(counter), 0, byteLength)); }
From source file:com.monarchapis.client.authentication.HawkV1RequestProcessor.java
private String getHawkHeader(BaseClient<?> client, String accessToken, String payloadHash, String extData) { try {/* w w w. j a va 2s .co m*/ StringBuilder sb = new StringBuilder(); long ts = System.currentTimeMillis() / 1000; String nonce = RandomStringUtils.randomAlphanumeric(6); URI uri = URI.create(client.getUrl()); sb.append("hawk.1.header\n"); sb.append(ts); sb.append("\n"); sb.append(nonce); sb.append("\n"); sb.append(client.getMethod()); sb.append("\n"); sb.append(uri.getRawPath()); sb.append("\n"); sb.append(uri.getHost()); sb.append("\n"); sb.append(uri.getPort()); sb.append("\n"); if (payloadHash != null) { sb.append(payloadHash); } sb.append("\n"); if (extData != null) { sb.append(extData); } sb.append("\n"); if (accessToken != null) { sb.append(apiKey); sb.append("\n"); } String stringData = sb.toString(); String algo = HmacUtils.getHMacAlgorithm(algorithm); byte[] key = sharedSecret.getBytes(); SecretKeySpec signingKey = new SecretKeySpec(key, algo); Mac mac256 = Mac.getInstance(algo); mac256.init(signingKey); // compute the hmac on input data bytes byte[] hash = mac256.doFinal(stringData.getBytes("UTF-8")); String mac = Base64.encodeBase64String(hash); return "Hawk id=\"" + (accessToken != null ? accessToken : apiKey) + "\", ts=\"" + ts + "\", nonce=\"" + nonce + "\"" + (payloadHash != null ? ", hash=\"" + payloadHash + "\"" : "") + (extData != null ? ", ext=\"" + extData + "\"," : "") + ", mac=\"" + mac + "\"" + (accessToken != null ? ", app=\"" + apiKey + "\"" : ""); } catch (Exception e) { throw new RuntimeException("Could not create hawk header", e); } }
From source file:net.fenyo.mail4hotspot.web.GMailOAuthStep1Servlet.java
private String hmac(final String key, final String message) throws InvalidKeyException, NoSuchAlgorithmException, UnsupportedEncodingException { final Mac mac = Mac.getInstance("HmacSHA1"); mac.init(new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA1")); return org.apache.commons.codec.binary.Base64.encodeBase64String(mac.doFinal(message.getBytes("UTF-8"))); }
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 w w . ja v a 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.zegoggles.smssync.XOAuthConsumer.java
private String generateSig(HttpRequest request, HttpParameters requestParameters) throws Exception { String keyString = OAuth.percentEncode(getConsumerSecret()) + '&' + OAuth.percentEncode(getTokenSecret()); byte[] keyBytes = keyString.getBytes(OAuth.ENCODING); SecretKey key = new SecretKeySpec(keyBytes, MAC_NAME); Mac mac = Mac.getInstance(MAC_NAME); mac.init(key);//from w w w .j a v a 2 s . c om String sbs = new SignatureBaseString(request, requestParameters).generate(); return base64(mac.doFinal(sbs.getBytes(OAuth.ENCODING))); }
From source file:org.midonet.api.auth.cloudstack.CloudStackClient.java
private String generateBase64Sha1Digest(String command) throws CloudStackClientException { try {// w w w .j ava 2s.co m Mac mac = Mac.getInstance("HmacSHA1"); SecretKeySpec secret_key = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1"); mac.init(secret_key); byte[] digest = mac.doFinal(command.getBytes()); return new String(Base64.encodeBase64(digest)); } catch (NoSuchAlgorithmException e) { throw new CloudStackClientException("No algorithm found to do SHA-1: " + command, e); } catch (InvalidKeyException e) { throw new CloudStackClientException("Invalid secret key: " + secretKey, e); } }
From source file:com.baidubce.auth.BceV1Signer.java
private String sha256Hex(String signingKey, String stringToSign) { try {//from w ww . j ava 2s. co m Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(signingKey.getBytes(UTF8), "HmacSHA256")); return new String(Hex.encodeHex(mac.doFinal(stringToSign.getBytes(UTF8)))); } catch (Exception e) { throw new BceClientException("Fail to generate the signature", e); } }