List of usage examples for javax.crypto Mac doFinal
public final byte[] doFinal(byte[] input) throws IllegalStateException
From source file:org.broadleafcommerce.vendor.authorizenet.service.payment.AuthorizeNetCheckoutServiceImpl.java
@Override public String createTamperProofSeal(String customerId, String orderId) throws NoSuchAlgorithmException, InvalidKeyException { String transactionKey = configuration.getTransactionKey(); Base64 encoder = new Base64(); Mac sha1Mac = Mac.getInstance("HmacSHA1"); SecretKeySpec publicKeySpec = new SecretKeySpec(transactionKey.getBytes(), "HmacSHA1"); sha1Mac.init(publicKeySpec);/* ww w.jav a 2 s . c om*/ String customerOrderString = customerId + orderId; byte[] publicBytes = sha1Mac.doFinal(customerOrderString.getBytes()); String publicDigest = encoder.encodeToString(publicBytes); return publicDigest.replaceAll("\\r|\\n", ""); }
From source file:org.basinmc.irc.bridge.github.GitHubServerHandler.java
/** * Verifies a request signature./* w w w. j a va 2s .c o m*/ * * @param data a payload. * @param signature a signature. * @return true if valid, false otherwise. */ private boolean verifySignature(@Nonnull String data, @Nonnull String signature) { if (this.secret == null) { logger.warn("No secret key specified. Signature checks will be skipped!"); return true; } try { Mac mac = Mac.getInstance(SIGNATURE_ALGORITHM); mac.init(this.secret); byte[] expected = mac.doFinal(data.getBytes(StandardCharsets.UTF_8)); return Arrays.equals(expected, Hex.decodeHex(signature.toCharArray())); } catch (InvalidKeyException | NoSuchAlgorithmException ex) { logger.error("Could not verify signature: " + ex.getMessage(), ex); } catch (DecoderException ex) { logger.warn("Could not decode signature: " + ex.getMessage(), ex); } throw new IllegalStateException("Could not verify signature"); }
From source file:com.here.account.auth.OAuth1SignerTest.java
protected String HmacSHAN(String keyString, String algorithm, String baseString) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException { /*/*from w w w.j a va2 s . com*/ 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); }
From source file:org.cryptonode.jncryptor.AES256v2Cryptor.java
/** * Encrypts plaintext data, 256-bit AES CBC-mode with PKCS#5 padding. * /*w w w.j a v a 2 s . co m*/ * @param plaintext * the plaintext * @param password * the password (can be <code>null</code> or empty) * @param encryptionSalt * eight bytes of random salt value * @param hmacSalt * eight bytes of random salt value * @param iv * sixteen bytes of AES IV * @return a formatted ciphertext * @throws CryptorException * if an error occurred */ byte[] encryptData(byte[] plaintext, char[] password, byte[] encryptionSalt, byte[] hmacSalt, byte[] iv) throws CryptorException { SecretKey encryptionKey = keyForPassword(password, encryptionSalt); SecretKey hmacKey = keyForPassword(password, hmacSalt); try { Cipher cipher = Cipher.getInstance(AES_CIPHER_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, encryptionKey, new IvParameterSpec(iv)); byte[] ciphertext = cipher.doFinal(plaintext); AES256v2Ciphertext output = new AES256v2Ciphertext(encryptionSalt, hmacSalt, iv, ciphertext); Mac mac = Mac.getInstance(HMAC_ALGORITHM); mac.init(hmacKey); byte[] hmac = mac.doFinal(output.getDataToHMAC()); output.setHmac(hmac); return output.getRawData(); } catch (GeneralSecurityException e) { throw new CryptorException("Failed to generate ciphertext.", e); } }
From source file:nl.nn.adapterframework.pipes.HashPipe.java
public PipeRunResult doPipe(Object input, IPipeLineSession session) throws PipeRunException { String message = (String) input; String authAlias = getAuthAlias(); String secret = getSecret();//from ww w . j a va 2 s . com try { ParameterList parameterList = getParameterList(); ParameterResolutionContext prc = new ParameterResolutionContext(message, session); ParameterValueList pvl = prc.getValues(parameterList); if (pvl != null) { Parameter authAliasParam = parameterList.findParameter("authAlias"); if (authAliasParam != null) authAlias = (String) authAliasParam.getValue(pvl, prc); Parameter secretParam = parameterList.findParameter("secret"); if (secretParam != null) secret = (String) secretParam.getValue(pvl, prc); } } catch (Exception e) { throw new PipeRunException(this, getLogPrefix(session) + "exception extracting authAlias", e); } CredentialFactory accessTokenCf = new CredentialFactory(authAlias, "", secret); String cfSecret = accessTokenCf.getPassword(); if (cfSecret == null || cfSecret.isEmpty()) throw new PipeRunException(this, getLogPrefix(session) + "empty secret, unable to hash"); try { Mac mac = Mac.getInstance(getAlgorithm()); SecretKeySpec secretkey = new SecretKeySpec(cfSecret.getBytes(getEncoding()), "algorithm"); mac.init(secretkey); String hash = Base64.encodeBase64String(mac.doFinal(message.getBytes())); return new PipeRunResult(getForward(), hash); } catch (Exception e) { throw new PipeRunException(this, getLogPrefix(session) + "error creating hash", e); } }
From source file:org.cryptonode.jncryptor.AES256v2Cryptor.java
/** * Decrypts data./*w ww .j ava2s. co m*/ * * @param aesCiphertext * the ciphertext from the message * @param decryptionKey * the key to decrypt * @param hmacKey * the key to recalculate the HMAC * @return the decrypted data * @throws CryptorException * if a JCE error occurs */ private byte[] decryptData(AES256v2Ciphertext aesCiphertext, SecretKey decryptionKey, SecretKey hmacKey) throws CryptorException { try { Mac mac = Mac.getInstance(HMAC_ALGORITHM); mac.init(hmacKey); byte[] hmacValue = mac.doFinal(aesCiphertext.getDataToHMAC()); if (!Arrays.equals(hmacValue, aesCiphertext.getHmac())) { throw new InvalidHMACException("Incorrect HMAC value."); } Cipher cipher = Cipher.getInstance(AES_CIPHER_ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, decryptionKey, new IvParameterSpec(aesCiphertext.getIv())); return cipher.doFinal(aesCiphertext.getCiphertext()); } catch (GeneralSecurityException e) { throw new CryptorException("Failed to decrypt message.", e); } }
From source file:com.tripit.auth.OAuthCredential.java
private String generateSignature(String baseUrl, SortedMap<String, String> args) throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException { String encoding = "UTF-8"; baseUrl = URLEncoder.encode(baseUrl, encoding); StringBuilder sb = new StringBuilder(); boolean isFirst = true; for (Map.Entry<String, String> arg : args.entrySet()) { if (isFirst) { isFirst = false;//from w ww.j av a2s .c o m } else { sb.append('&'); } sb.append(URLEncoder.encode(arg.getKey(), encoding)); sb.append('='); sb.append(URLEncoder.encode(arg.getValue(), encoding)); } String parameters = URLEncoder.encode(sb.toString(), encoding); String signatureBaseString = "GET&" + baseUrl + "&" + parameters; String key = (consumerSecret != null ? consumerSecret : "") + "&" + (userSecret != null ? userSecret : ""); String macName = "HmacSHA1"; Mac mac = Mac.getInstance(macName); mac.init(new SecretKeySpec(key.getBytes(encoding), macName)); byte[] signature = mac.doFinal(signatureBaseString.getBytes(encoding)); return new Base64().encodeToString(signature).trim(); }
From source file:org.cryptonode.jncryptor.AES256v2Cryptor.java
@Override public byte[] encryptData(byte[] plaintext, SecretKey encryptionKey, SecretKey hmacKey) throws CryptorException { Validate.notNull(plaintext, "Plaintext cannot be null."); Validate.notNull(encryptionKey, "Encryption key cannot be null."); Validate.notNull(hmacKey, "HMAC key cannot be null."); byte[] iv = getSecureRandomData(AES_BLOCK_SIZE); try {/*from w w w . ja v a 2 s .co m*/ Cipher cipher = Cipher.getInstance(AES_CIPHER_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, encryptionKey, new IvParameterSpec(iv)); byte[] ciphertext = cipher.doFinal(plaintext); AES256v2Ciphertext output = new AES256v2Ciphertext(iv, ciphertext); Mac mac = Mac.getInstance(HMAC_ALGORITHM); mac.init(hmacKey); byte[] hmac = mac.doFinal(output.getDataToHMAC()); output.setHmac(hmac); return output.getRawData(); } catch (GeneralSecurityException e) { throw new CryptorException("Failed to generate ciphertext.", e); } }
From source file:Main.java
public static String completeJweFromSIM(String jweSIM) { // android.os.Debug.waitForDebugger(); try {// w w w.j ava2 s . c om if (jweSIM != null && jweSIM.length() > 0) { String parts[] = jweSIM.split("\\."); ; if (parts != null && parts.length == 5) { // retrieve hmac key byte hmac_key[] = Base64.decode(parts[4], Base64.URL_SAFE); if (hmac_key != null && hmac_key.length == 16) { // init hash instance Mac hmac = Mac.getInstance("HmacSHA256", "SC"); hmac.init(new SecretKeySpec(hmac_key, "HmacSHA256")); byte[] aad = parts[0].getBytes(); long al = aad.length * 8; byte[] iv_key = decodeB64(parts[2]); byte[] cryptedBytes = decodeB64(parts[3]); // build data to hash 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); // compute hac value 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 = parts[0] + "." + parts[1] + "." + parts[2] + "." + parts[3] + "." + auth_tag64; // // just for verification // byte jwt64 [] = decryptJWE(finalString, RsaKeyTim.privRsaKey); // if(jwt64!=null) { // String jws = new String(jwt64); // Log.d("completeJweFromSIM", "jws verify Key TIM :"+verifyJWS(jws,RsaKeyTim.pubRsaKey)); // } return finalString; } } // } } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:com.altcanvas.asocial.Twitter.java
private byte[] generateSignature(String data) { SecretKeySpec spec = null;/*from w w w .j ava2s. c om*/ if (this.tokenSecret == null) { spec = new SecretKeySpec((Http.encode(OAUTH_CONSUMER_SECRET) + "&").getBytes(), HMACSHA1); } else { spec = new SecretKeySpec( (Http.encode(OAUTH_CONSUMER_SECRET) + "&" + Http.encode(tokenSecret)).getBytes(), HMACSHA1); } try { Mac mac = Mac.getInstance(HMACSHA1); mac.init(spec); byte[] byteHMAC = mac.doFinal(data.getBytes()); return Base64.encodeBase64(byteHMAC); } catch (NoSuchAlgorithmException nsae) { } catch (InvalidKeyException ike) { } return null; }