List of usage examples for javax.crypto Mac init
public final void init(Key key) throws InvalidKeyException
From source file:jp.co.yahoo.yconnect.core.oidc.JWTVerification.java
/** * HMAC-SHA256????????????/*from ww w . ja v a 2 s . c om*/ * * @return ????? */ private String generateSignature() { // mac??? Mac sha256_HMAC = null; try { sha256_HMAC = Mac.getInstance("HmacSHA256"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } // secret_key?? SecretKeySpec secret_key = null; try { secret_key = new SecretKeySpec(this.clientSecret.getBytes("UTF-8"), "HmacSHA256"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } // mac?? try { sha256_HMAC.init(secret_key); } catch (InvalidKeyException e) { e.printStackTrace(); } String[] idTokenArray = this.idTokenString.split("\\."); this.dataPart = idTokenArray[0] + "." + idTokenArray[1]; String hash = null; try { hash = Base64.encodeBase64String(sha256_HMAC.doFinal(this.dataPart.getBytes("UTF-8"))); } catch (IllegalStateException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } // URLSafe?Base64?? hash = hash.replace("=", ""); hash = hash.replace("+", "-"); hash = hash.replace("/", "_"); return hash; }
From source file:com.telesign.util.TeleSignRequest.java
/** * Creates the Signature component for the Authorization header field. * Uses your Secret Key to encode the stringToSign. * This is a <em>helper method</em>, used internally by the {@link TeleSignRequest#executeRequest()} method. * * @param data//w w w .ja va 2 s .c o m * [Required] The stringToSign. * @param key * [Required] Your TeleSign API Key. Also known as your Secret * Key, and your Shared Cryptographic Key. It s a bese64-encoded * string value. * @return A String containing the Base64-encoded hash-based message * authentication code. * @throws java.security.SignatureException * Failed to generate HMAC. IllegalArgumentException - if * algorithm is null or key is null or empty. */ private String encode(String data, String key) throws java.security.SignatureException { String result; byte[] decoded_key = Base64.decodeBase64(key); try { // Get an hmac_sha key from the raw key bytes. SecretKeySpec signingKey = new SecretKeySpec(decoded_key, auth.value()); // Get an hmac_sha Mac instance, and initialize it with the signing key. Mac mac = Mac.getInstance(auth.value()); mac.init(signingKey); // Compute the HMAC on input data bytes. byte[] rawHmac = mac.doFinal(data.getBytes()); // Base64-encode the HMAC. result = new String(Base64.encodeBase64(rawHmac)); } catch (Exception e) { throw new SignatureException("Failed to generate HMAC : " + e.getMessage()); } return result; }
From source file:org.cryptomator.crypto.aes256.Aes256Cryptor.java
private Mac hmacSha256(SecretKey key) { try {//w w w . ja v a 2 s. c o m final Mac mac = Mac.getInstance(HMAC_KEY_ALGORITHM); mac.init(key); return mac; } catch (NoSuchAlgorithmException e) { throw new AssertionError("Every implementation of the Java platform is required to support HmacSHA256.", e); } catch (InvalidKeyException e) { throw new IllegalArgumentException("Invalid key", e); } }
From source file:com.microsoft.windowsazure.messaging.Connection.java
/** * Generates an AuthToken//from w w w . j ava2s . c om * @param url The target URL * @return An AuthToken * @throws java.security.InvalidKeyException */ private String generateAuthToken(String url) throws InvalidKeyException { String keyName = mConnectionData.get(SHARED_ACCESS_KEY_NAME); if (isNullOrWhiteSpace(keyName)) { throw new AssertionError("SharedAccessKeyName"); } String key = mConnectionData.get(SHARED_ACCESS_KEY); if (isNullOrWhiteSpace(key)) { throw new AssertionError("SharedAccessKey"); } try { url = URLEncoder.encode(url, UTF8_ENCODING).toLowerCase(Locale.ENGLISH); } catch (UnsupportedEncodingException e) { // this shouldn't happen because of the fixed encoding } // Set expiration in seconds Calendar expireDate = Calendar.getInstance(TimeZone.getTimeZone(UTC_TIME_ZONE)); expireDate.add(Calendar.MINUTE, EXPIRE_MINUTES); long expires = expireDate.getTimeInMillis() / 1000; String toSign = url + '\n' + expires; // sign byte[] bytesToSign = toSign.getBytes(); Mac mac = null; try { mac = Mac.getInstance("HmacSHA256"); } catch (NoSuchAlgorithmException e) { // This shouldn't happen because of the fixed algorithm } SecretKeySpec secret = new SecretKeySpec(key.getBytes(), mac.getAlgorithm()); mac.init(secret); byte[] signedHash = mac.doFinal(bytesToSign); String base64Signature = Base64.encodeToString(signedHash, Base64.DEFAULT); base64Signature = base64Signature.trim(); try { base64Signature = URLEncoder.encode(base64Signature, UTF8_ENCODING); } catch (UnsupportedEncodingException e) { // this shouldn't happen because of the fixed encoding } // construct authorization string String token = "SharedAccessSignature sr=" + url + "&sig=" + base64Signature + "&se=" + expires + "&skn=" + keyName; return token; }
From source file:com.konakart.actions.ipn.EPaybgAction.java
/** * //from w ww .j a va 2 s.co m * @param mapping * The ActionMapping used to select this instance * @param form * The optional ActionForm bean for this request (if any) * @param request * The HTTP request we are processing * @param response * The HTTP response we are creating * */ @SuppressWarnings("unchecked") public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { String encoded = null, checksum = null, username = null, password = null, secretKey = null; // The response print writer used to send a response back to ePay PrintWriter pw = null; if (log.isDebugEnabled()) { log.debug("*********** ePay Callback"); } // Create thes outside of try / catch since they are needed in the case of a general // exception IpnHistoryIf ipnHistory = new IpnHistory(); ipnHistory.setOrderId(-1); ipnHistory.setModuleCode(code); String sessionId = null; KKAppEng kkAppEng = null; try { // Get the PrintWriter from the response try { pw = response.getWriter(); if (pw == null) { throw new Exception(); } } catch (IOException e2) { e2.printStackTrace(); throw new Exception("Could not get a PrintWriter for the response"); } // Get an instance of the KonaKart engine kkAppEng = this.getKKAppEng(request, response); // We get from configurations, the username and password used to log into the engine // in order to save the changes of the IPN username = kkAppEng.getConfig(MODULE_PAYMENT_EPAYBG_CALLBACK_USERNAME); password = kkAppEng.getConfig(MODULE_PAYMENT_EPAYBG_CALLBACK_PASSWORD); if (username == null || password == null) { throw new Exception("The callback username and password must be defined for the epaybg module by" + " setting the configuration variables MODULE_PAYMENT_EPAYBG_CALLBACK_USERNAME" + " and MODULE_PAYMENT_EPAYBG_CALLBACK_PASSWORD"); } // We log into the engine to get a session. sessionId = kkAppEng.getEng().login(username, password); kkAppEng.setSessionId(sessionId); if (sessionId == null) { throw new Exception("The callback username and password must be defined for the epaybg module by" + " setting the configuration variables MODULE_PAYMENT_EPAYBG_CALLBACK_USERNAME" + " and MODULE_PAYMENT_EPAYBG_CALLBACK_PASSWORD"); } // Get the secret key secretKey = kkAppEng.getConfig(MODULE_PAYMENT_EPAYBG_SECRET); if (secretKey == null) { throw new Exception("The Configuration MODULE_PAYMENT_EPAYBG_SECRET must be set to the secret key" + " shared between the merchant and ePay)"); } // See if we need to send an email, by looking at the configuration String sendEmailsConfig = kkAppEng.getConfig(ConfigConstants.SEND_EMAILS); boolean sendEmail = false; if (sendEmailsConfig != null && sendEmailsConfig.equalsIgnoreCase("true")) { sendEmail = true; } // Process the parameters sent in the callback if (log.isDebugEnabled()) { log.debug("Callback Data :"); } StringBuffer sb = new StringBuffer(); String invoice = null, status = null, payTime = null, stan = null, bcode = null; if (request != null) { Enumeration en = request.getParameterNames(); while (en.hasMoreElements()) { String paramName = (String) en.nextElement(); String paramValue = request.getParameter(paramName); if (log.isDebugEnabled()) { log.debug("ParamName = " + paramName + " ParamValue = " + paramValue); } if (sb.length() > 0) { sb.append("\n"); } sb.append(paramName); sb.append(" = "); sb.append(paramValue); // Capture important variables so that we can determine whether the // transaction was successful or not if (paramName != null) { if (paramName.equalsIgnoreCase(EPaybgAction.checksum)) { checksum = paramValue; } else if (paramName.equalsIgnoreCase(EPaybgAction.encoded)) { encoded = paramValue; } } } // Save the data to the IpnHistory class ipnHistory.setGatewayFullResponse(sb.toString()); if (encoded == null || checksum == null) { ipnHistory.setKonakartResultDescription(RET2_DESC); ipnHistory.setKonakartResultId(RET2); kkAppEng.getEng().saveIpnHistory(sessionId, ipnHistory); pw.print("ERR=" + RET2_DESC + "\n"); return null; } // Get a checksum for the data Mac sha = Mac.getInstance("HmacSHA1"); sha.init(new SecretKeySpec(secretKey.getBytes(), "HmacSHA1")); byte[] mac = new byte[20]; mac = sha.doFinal(encoded.getBytes()); String calculatedChecksum = bytesToHex(mac); if (log.isDebugEnabled()) { log.debug("Calculated Checksum = " + calculatedChecksum); } // Check the checksum if (calculatedChecksum == null || !calculatedChecksum.equalsIgnoreCase(checksum)) { ipnHistory.setKonakartResultDescription(RET3_DESC); ipnHistory.setKonakartResultId(RET3); kkAppEng.getEng().saveIpnHistory(sessionId, ipnHistory); pw.print("ERR=" + RET3_DESC + "\n"); return null; } // Decode the data String decoded = null; try { byte[] decodedByteArray = Base64.decode(encoded); decoded = new String(decodedByteArray); if (log.isDebugEnabled()) { log.debug("Decoded Data = \n" + decoded); } } catch (Exception e) { ipnHistory.setKonakartResultDescription(RET4_DESC + decoded); ipnHistory.setKonakartResultId(RET4); kkAppEng.getEng().saveIpnHistory(sessionId, ipnHistory); pw.print("ERR=" + RET4_DESC + decoded + "\n"); return null; } // At this point we have decode the data sent by ePay and now we have to get the // parameters String[] parmArray = decoded.split(":"); for (int i = 0; i < parmArray.length; i++) { if (parmArray[i] != null) { String[] innerArray = parmArray[i].split("="); if (innerArray.length == 2) { if (innerArray[0] != null && innerArray[0].equals("INVOICE")) { invoice = innerArray[1].trim(); sb.append("&"); sb.append("INVOICE="); sb.append(invoice); } else if (innerArray[0] != null && innerArray[0].equals("STATUS")) { status = innerArray[1].trim(); sb.append("&"); sb.append("STATUS="); sb.append(status); ipnHistory.setGatewayResult(status); } else if (innerArray[0] != null && innerArray[0].equals("PAY_TIME")) { payTime = innerArray[1].trim(); sb.append("&"); sb.append("PAY_TIME="); sb.append(payTime); } else if (innerArray[0] != null && innerArray[0].equals("STAN")) { stan = innerArray[1].trim(); sb.append("&"); sb.append("STAN="); sb.append(stan); } else if (innerArray[0] != null && innerArray[0].equals("BCODE")) { bcode = innerArray[1].trim(); sb.append("&"); sb.append("BCODE="); sb.append(bcode); } } } } // Update the full response ipnHistory.setGatewayFullResponse(sb.toString()); // Since we've verified the data with the secret key, the order number should be // equal to invoice int orderId; try { if (invoice == null) { throw new Exception(); } orderId = new Integer(invoice).intValue(); ipnHistory.setOrderId(orderId); } catch (Exception e) { ipnHistory.setKonakartResultDescription(RET5_DESC + invoice); ipnHistory.setKonakartResultId(RET5); kkAppEng.getEng().saveIpnHistory(sessionId, ipnHistory); pw.print("ERR=" + RET5_DESC + invoice + "\n"); return null; } // If successful, we update the inventory as well as changing the state of the // order. String comment = null; if (status != null && status.equalsIgnoreCase("PAID")) { comment = ORDER_HISTORY_COMMENT_OK + status; kkAppEng.getEng().changeOrderStatus(sessionId, orderId, com.konakart.bl.OrderMgr.PAYMENT_RECEIVED_STATUS, sendEmail, comment); // If the order payment was approved we update the inventory kkAppEng.getEng().updateInventory(sessionId, orderId); if (sendEmail) { sendOrderConfirmationMail(kkAppEng, orderId, /* success */true); } } else { comment = ORDER_HISTORY_COMMENT_KO + status; kkAppEng.getEng().changeOrderStatus(sessionId, orderId, com.konakart.bl.OrderMgr.PAYMENT_DECLINED_STATUS, sendEmail, comment); if (sendEmail) { sendOrderConfirmationMail(kkAppEng, orderId, /* success */false); } } ipnHistory.setKonakartResultDescription(RET0_DESC); ipnHistory.setKonakartResultId(RET0); kkAppEng.getEng().saveIpnHistory(sessionId, ipnHistory); } pw.print("INVOICE=" + invoice + ":STATUS=OK\n"); return null; } catch (Exception e) { try { if (sessionId != null) { ipnHistory.setKonakartResultDescription(RET6_DESC); ipnHistory.setKonakartResultId(RET6); if (kkAppEng != null) { kkAppEng.getEng().saveIpnHistory(sessionId, ipnHistory); } } } catch (KKException e1) { e1.printStackTrace(); } e.printStackTrace(); if (pw != null) { pw.print("ERR=" + RET6_DESC + "\n"); } return null; } }
From source file:com.cloud.bridge.util.EC2RestAuth.java
/** * Create a signature by the following method: * new String( Base64( SHA1 or SHA256 ( key, byte array ))) * /*w w w . j a v a 2s. co m*/ * @param signIt - the data to generate a keyed HMAC over * @param secretKey - the user's unique key for the HMAC operation * @param useSHA1 - if false use SHA256 * @return String - the recalculated string * @throws SignatureException */ private String calculateRFC2104HMAC(String signIt, String secretKey, boolean useSHA1) throws SignatureException { SecretKeySpec key = null; Mac hmacShaAlg = null; String result = null; try { if (useSHA1) { key = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1"); hmacShaAlg = Mac.getInstance("HmacSHA1"); } else { key = new SecretKeySpec(secretKey.getBytes(), "HmacSHA256"); hmacShaAlg = Mac.getInstance("HmacSHA256"); } hmacShaAlg.init(key); byte[] rawHmac = hmacShaAlg.doFinal(signIt.getBytes()); result = new String(Base64.encodeBase64(rawHmac)); } catch (Exception e) { throw new SignatureException("Failed to generate keyed HMAC on REST request: " + e.getMessage()); } return result.trim(); }
From source file:com.zimbra.cs.account.ZimbraAuthToken.java
@Override public String getCrumb() throws AuthTokenException { String authToken = getEncoded(); try {//w ww.j av a 2 s.c o m ByteKey bk = new ByteKey(getCurrentKey().getKey()); Mac mac = Mac.getInstance("HmacMD5"); mac.init(bk); return new String(Hex.encodeHex(mac.doFinal(authToken.getBytes()))); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("fatal error", e); } catch (InvalidKeyException e) { throw new RuntimeException("fatal error", e); } }
From source file:com.wandisco.s3hdfs.auth.AWSAuthenticationHandler.java
/** * Create a signature by the following method: * new String( Base64( SHA1 or SHA256 ( key, byte array ))) * * @param signIt - the data to generate a keyed HMAC over * @param secretKey - the user's unique key for the HMAC operation * @param useSHA1 - if false use SHA256 * @return String - the recalculated string * @throws SignatureException/*from w w w . j a va 2 s.co m*/ */ private String calculateRFC2104HMAC(String signIt, String secretKey, boolean useSHA1) throws SignatureException { SecretKeySpec key = null; Mac hmacShaAlg = null; String result = null; try { if (useSHA1) { key = new SecretKeySpec(secretKey.getBytes(DEFAULT_CHARSET), "HmacSHA1"); hmacShaAlg = Mac.getInstance("HmacSHA1"); } else { key = new SecretKeySpec(secretKey.getBytes(DEFAULT_CHARSET), "HmacSHA256"); hmacShaAlg = Mac.getInstance("HmacSHA256"); } hmacShaAlg.init(key); byte[] rawHmac = hmacShaAlg.doFinal(signIt.getBytes(DEFAULT_CHARSET)); result = new String(Base64.encodeBase64(rawHmac), DEFAULT_CHARSET); } catch (Exception e) { throw new SignatureException("Failed to generate keyed HMAC on REST request: " + e.getMessage()); } return result.trim(); }
From source file:org.akvo.flow.service.DataSyncService.java
private ZipFileData formZip(long surveyInstanceId) { ZipFileData zipFileData = new ZipFileData(); StringBuilder surveyBuf = new StringBuilder(); // Hold the responses in the StringBuilder String uuid = processSurveyData(surveyInstanceId, surveyBuf, zipFileData.imagePaths); // THe filename will match the Survey Instance UUID File zipFile = new File(FileUtil.getFilesDir(FileType.DATA), uuid + ConstantUtil.ARCHIVE_SUFFIX); // Write the data into the zip file try {/*from w w w.ja v a 2s. c o m*/ String fileName = zipFile.getAbsolutePath();// Will normalize filename. zipFileData.filename = fileName; Log.i(TAG, "Creating zip file: " + fileName); FileOutputStream fout = new FileOutputStream(zipFile); CheckedOutputStream checkedOutStream = new CheckedOutputStream(fout, new Adler32()); ZipOutputStream zos = new ZipOutputStream(checkedOutStream); writeTextToZip(zos, surveyBuf.toString(), SURVEY_DATA_FILE); String signingKeyString = mProps.getProperty(SIGNING_KEY_PROP); if (!StringUtil.isNullOrEmpty(signingKeyString)) { MessageDigest sha1Digest = MessageDigest.getInstance("SHA1"); byte[] digest = sha1Digest.digest(surveyBuf.toString().getBytes("UTF-8")); SecretKeySpec signingKey = new SecretKeySpec(signingKeyString.getBytes("UTF-8"), SIGNING_ALGORITHM); Mac mac = Mac.getInstance(SIGNING_ALGORITHM); mac.init(signingKey); byte[] hmac = mac.doFinal(digest); String encodedHmac = Base64.encodeBytes(hmac); writeTextToZip(zos, encodedHmac, SIG_FILE_NAME); } final String checksum = "" + checkedOutStream.getChecksum().getValue(); zos.close(); Log.i(TAG, "Closed zip output stream for file: " + fileName + ". Checksum: " + checksum); } catch (IOException e) { PersistentUncaughtExceptionHandler.recordException(e); Log.e(TAG, e.getMessage()); zipFileData = null; } catch (NoSuchAlgorithmException e) { PersistentUncaughtExceptionHandler.recordException(e); Log.e(TAG, e.getMessage()); zipFileData = null; } catch (InvalidKeyException e) { PersistentUncaughtExceptionHandler.recordException(e); Log.e(TAG, e.getMessage()); zipFileData = null; } return zipFileData; }
From source file:com.example.android.hawifi.MainActivity.java
public boolean throwCmd(String command) { final Charset asciiCs = Charset.forName("US-ASCII"); long nonce = myTime(); String HMAC_PASS = "password"; String HMAC_KEY = "key"; //String beforeHmac = "The quick brown fox jumps over the lazy dog"; String beforeHmac = "/" + HMAC_PASS + "/" + command + "/" + nonce + "/"; String result = ""; try {/* w w w . j a va2 s . co m*/ final Mac sha256_HMAC = Mac.getInstance("HmacSHA256"); final SecretKeySpec secret_key = new javax.crypto.spec.SecretKeySpec(asciiCs.encode(HMAC_KEY).array(), "HmacSHA256"); sha256_HMAC.init(secret_key); final byte[] mac_data = sha256_HMAC.doFinal(asciiCs.encode(beforeHmac).array()); for (final byte element : mac_data) { result += Integer.toString((element & 0xff) + 0x100, 16).substring(1); } } catch (Exception e) { if (D) Log.e(TAG, "Crypto Exception"); } DownloadTask dt; String url = null; if (((RadioButton) findViewById(R.id.radioButton0)).isChecked()) url = myUrls[0].url; else if (((RadioButton) findViewById(R.id.radioButton1)).isChecked()) url = myUrls[1].url; else if (((RadioButton) findViewById(R.id.radioButton2)).isChecked()) url = myUrls[2].url; else if (((RadioButton) findViewById(R.id.radioButton3)).isChecked()) url = myUrls[3].url; else if (((RadioButton) findViewById(R.id.radioButton4)).isChecked()) url = myUrls[4].url; if (url != null) { //new DownloadTask().execute(url + command + "/" + nonce + "/" + result); dt = new DownloadTask(); dt.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, url + command + "/" + nonce + "/" + result); } Log.e(TAG, url + command); return true; }