List of usage examples for javax.crypto Mac getInstance
public static final Mac getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:flpitu88.web.backend.psicoweb.config.Jwt.java
/** * Private method to generate a signature from a key * * @param input Data to sign/*from ww w.j a va 2s. c om*/ * @param key Key used for the signature * @param method Algorithm * * @return Signature * * @throws NoSuchAlgorithmException * @throws UnsupportedEncodingException * @throws InvalidKeyException */ private static byte[] sign(String input, String key, String method) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException { Mac hmac = Mac.getInstance(method); SecretKey secretKey = new SecretKeySpec(key.getBytes(), method); hmac.init(secretKey); return hmac.doFinal(input.getBytes()); }
From source file:com.flozano.socialauth.util.OAuthConsumer.java
private String getHMACSHA1(final String method, final String url, final Map<String, String> args, final AccessGrant token) throws Exception { if (config.get_consumerSecret().length() == 0) { throw new SignatureException("Please check consumer secret"); }//from w w w.ja va 2 s . c om boolean valid = MethodType.GET.toString().equals(method) || MethodType.PUT.toString().equals(method) || MethodType.POST.toString().equals(method); if (!valid) { throw new SignatureException("Invalid method type :" + method); } if (url.length() == 0) { throw new SignatureException("Please check URL"); } String key = HttpUtil.encodeURIComponent(config.get_consumerSecret()) + "&"; if (token != null && token.getSecret() != null) { key += HttpUtil.encodeURIComponent(token.getSecret()); } try { // get an hmac_sha1 key from the raw key bytes SecretKeySpec signingKey = new SecretKeySpec(key.getBytes("UTF-8"), "HMAC-SHA1"); // get an hmac_sha1 Mac instance and initialize with the signing key Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signingKey); String data = HttpUtil.encodeURIComponent(method) + "&" + HttpUtil.encodeURIComponent(url) + "&" + HttpUtil.encodeURIComponent(HttpUtil.buildParams(args)); LOG.debug("Signature data : " + data); // compute the hmac on input data bytes byte[] rawHmac = mac.doFinal(data.getBytes("UTF-8")); // base64-encode the hmac LOG.debug("Encoding raw HMAC to Base64"); String sig = Base64.encodeBytes(rawHmac); return sig; } catch (Exception e) { throw new SignatureException("Unable to generate HMAC-SHA1", e); } }
From source file:org.apache.jcp.xml.dsig.internal.dom.DOMHMACSignatureMethod.java
boolean verify(Key key, SignedInfo si, byte[] sig, XMLValidateContext context) throws InvalidKeyException, SignatureException, XMLSignatureException { if (key == null || si == null || sig == null) { throw new NullPointerException(); }/*from www . j a v a 2 s. c o m*/ if (!(key instanceof SecretKey)) { throw new InvalidKeyException("key must be SecretKey"); } if (hmac == null) { try { hmac = Mac.getInstance(getJCAAlgorithm()); } catch (NoSuchAlgorithmException nsae) { throw new XMLSignatureException(nsae); } } if (outputLengthSet && outputLength < getDigestLength()) { throw new XMLSignatureException("HMACOutputLength must not be less than " + getDigestLength()); } hmac.init((SecretKey) key); ((DOMSignedInfo) si).canonicalize(context, new MacOutputStream(hmac)); byte[] result = hmac.doFinal(); return MessageDigest.isEqual(sig, result); }
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. j ava 2 s . co 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:org.dasein.cloud.qingcloud.util.requester.QingCloudRequestBuilder.java
private String doMac(byte[] accessKeySecret, String stringToSign) throws InternalException { String signature;//from w ww . j av a2s . c om 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:no.digipost.android.authentication.OAuth.java
private static String encryptHmacSHA256(final String data) { SecretKeySpec secretKey = new SecretKeySpec(Secret.CLIENT_SECRET.getBytes(), ApplicationConstants.HMACSHA256); Mac mac = null;/*ww w .jav a 2 s. c o m*/ try { mac = Mac.getInstance(ApplicationConstants.HMACSHA256); mac.init(secretKey); } catch (Exception e) { // Ignore } byte[] hmacData = mac.doFinal(data.getBytes()); return new String(hmacData); }
From source file:com.ibm.og.s3.v4.AwsChunkedEncodingInputStream.java
/** * A wrapper of InputStream that implements pseudo-chunked-encoding. Each chunk will be buffered * for the calculation of the chunk signature which is added at the head of each chunk.<br> * The default chunk size cannot be customized, since we need to calculate the expected encoded * stream length before reading the wrapped stream.<br> * This class will use the mark() & reset() of the wrapped InputStream if they are supported, * otherwise it will create a buffer for bytes read from the wrapped stream. * /* w ww . jav a 2 s .c om*/ * @param in The original InputStream. * @param maxBufferSize Maximum number of bytes buffered by this class. * @param kSigning Signing key. * @param datetime Datetime, as used in SigV4. * @param keyPath Keypath/Scope, as used in SigV4. * @param headerSignature The signature of the signed headers. This will be used for calculating * the signature of the first chunk. * @param aws4Signer The AWS4Signer used for hashing and signing. */ public AwsChunkedEncodingInputStream(final InputStream in, int maxBufferSize, final byte[] kSigning, final String datetime, final String keyPath, final String headerSignature, final AWS4Signer aws4Signer, final LoadingCache<Long, byte[]> digestCache) { if (in instanceof AwsChunkedEncodingInputStream) { // This could happen when the request is retried, and we need to re-calculate the signatures. final AwsChunkedEncodingInputStream originalChunkedStream = (AwsChunkedEncodingInputStream) in; maxBufferSize = Math.max(originalChunkedStream.maxBufferSize, maxBufferSize); this.is = originalChunkedStream.is; this.decodedStreamBuffer = originalChunkedStream.decodedStreamBuffer; } else { this.is = in; this.decodedStreamBuffer = null; } if (maxBufferSize < DEFAULT_CHUNK_SIZE) { throw new IllegalArgumentException("Max buffer size should not be less than chunk size"); } try { this.sha256 = MessageDigest.getInstance("SHA-256"); final String signingAlgo = SigningAlgorithm.HmacSHA256.toString(); this.hmacSha256 = Mac.getInstance(signingAlgo); this.hmacSha256.init(new SecretKeySpec(kSigning, signingAlgo)); } catch (final NoSuchAlgorithmException e) { throw new IllegalStateException(e); } catch (final InvalidKeyException e) { throw new IllegalArgumentException(e); } this.maxBufferSize = maxBufferSize; this.dateTime = datetime; this.keyPath = keyPath; this.headerSignature = headerSignature; this.priorChunkSignature = headerSignature; this.aws4Signer = aws4Signer; this.digestCache = digestCache; }
From source file:com.cloud.sample.UserCloudAPIExecutor.java
/** * 1. Signs a string with a secret key using SHA-1 2. Base64 encode the result 3. URL encode the final result * /* ww w . j av a 2s.c om*/ * @param request * @param key * @return */ public static String signRequest(String request, String key) { try { Mac mac = Mac.getInstance("HmacSHA1"); SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "HmacSHA1"); mac.init(keySpec); mac.update(request.getBytes()); byte[] encryptedBytes = mac.doFinal(); return URLEncoder.encode(Base64.encodeBase64String(encryptedBytes), "UTF-8"); } catch (Exception ex) { System.out.println(ex); } return null; }
From source file:org.akvo.flow.api.FlowApi.java
private String getAuthorization(String query) { String authorization = null;/*from w w w . java2 s. co m*/ try { SecretKeySpec signingKey = new SecretKeySpec(API_KEY.getBytes(), "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signingKey); byte[] rawHmac = mac.doFinal(query.getBytes()); authorization = Base64.encodeToString(rawHmac, Base64.DEFAULT); } catch (NoSuchAlgorithmException e) { Log.e(TAG, e.getMessage()); } catch (InvalidKeyException e) { Log.e(TAG, e.getMessage()); } return authorization; }