List of usage examples for java.security NoSuchAlgorithmException printStackTrace
public void printStackTrace()
From source file:org.apache.marmotta.ldclient.services.ldclient.LDClient.java
public LDClient(ClientConfiguration config) { log.info("Initialising Linked Data Client Service ..."); this.config = config; endpoints = new ArrayList<>(); for (Endpoint endpoint : defaultEndpoints) { endpoints.add(endpoint);//w w w.ja va 2 s . com } endpoints.addAll(config.getEndpoints()); Collections.sort(endpoints); if (log.isInfoEnabled()) { for (Endpoint endpoint : endpoints) { log.info("- LDClient Endpoint: {}", endpoint.getName()); } } providers = new ArrayList<>(); for (DataProvider provider : defaultProviders) { providers.add(provider); } providers.addAll(config.getProviders()); if (log.isInfoEnabled()) { for (DataProvider provider : providers) { log.info("- LDClient Provider: {}", provider.getName()); } } retrievalSemaphore = new Semaphore(config.getMaxParallelRequests()); if (config.getHttpClient() != null) { log.debug("Using HttpClient provided in the configuration"); this.client = config.getHttpClient(); } else { log.debug("Creating default HttpClient based on the configuration"); HttpParams httpParams = new BasicHttpParams(); httpParams.setParameter(CoreProtocolPNames.USER_AGENT, "Apache Marmotta LDClient"); httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, config.getSocketTimeout()); httpParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, config.getConnectionTimeout()); httpParams.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true); httpParams.setIntParameter(ClientPNames.MAX_REDIRECTS, 3); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); try { SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, null, null); SSLSocketFactory sf = new SSLSocketFactory(sslcontext, SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); schemeRegistry.register(new Scheme("https", 443, sf)); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry); cm.setMaxTotal(20); cm.setDefaultMaxPerRoute(10); DefaultHttpClient client = new DefaultHttpClient(cm, httpParams); client.setRedirectStrategy(new LMFRedirectStrategy()); client.setHttpRequestRetryHandler(new LMFHttpRequestRetryHandler()); idleConnectionMonitorThread = new IdleConnectionMonitorThread(client.getConnectionManager()); idleConnectionMonitorThread.start(); this.client = client; } }
From source file:com.nokia.example.pepperfarm.iap.Payment.java
/** * Checks SHA1 fingerprint of the enabler * * @return true if signature matches, false if package is not found or signature does not match. *//*from w ww.jav a 2s . c o m*/ private boolean verifyFingreprint() { try { PackageInfo info = activity.getBaseContext().getPackageManager().getPackageInfo(ENABLER_PACKAGENAME, PackageManager.GET_SIGNATURES); if (info.signatures.length == 1) { byte[] cert = info.signatures[0].toByteArray(); MessageDigest digest; digest = MessageDigest.getInstance("SHA1"); byte[] ENABLER_FINGERPRINT = digest.digest(cert); byte[] EXPECTED_FINGERPRINT = hexStringToByteArray(EXPECTED_SHA1_FINGERPRINT); if (Arrays.equals(ENABLER_FINGERPRINT, EXPECTED_FINGERPRINT)) { Log.i("isBillingAvailable", "NIAP signature verified"); return true; } } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NameNotFoundException e) { e.printStackTrace(); } return false; }
From source file:org.sharextras.webscripts.connector.HttpOAuthConnector.java
private String generateSignature(Map<String, String> authParams, Map<String, String> extraParams, String httpMethod, String url) { Map<String, String> sigParams = new HashMap<String, String>(authParams); if (extraParams != null) sigParams.putAll(extraParams);//from ww w.ja v a2 s .c o m String sigMethod = sigParams.get(OAUTH_SIGNATURE_METHOD); if (sigMethod.equals(SIGNATURE_METHOD_PLAINTEXT)) { if (logger.isDebugEnabled()) logger.debug("Generating PLAINTEXT signature"); String tokenSecret = authParams.get(OAUTH_TOKEN_SECRET); StringBuffer signatureBuffer = new StringBuffer(getConsumerSecret()).append("&"); signatureBuffer.append(tokenSecret != null ? tokenSecret : ""); return signatureBuffer.toString(); } else if (sigMethod.equals(SIGNATURE_METHOD_HMACSHA1)) { if (logger.isDebugEnabled()) logger.debug("Generating HMAC-SHA1 signature"); StringBuffer baseStrBuffer = new StringBuffer(); baseStrBuffer.append(httpMethod).append("&"); baseStrBuffer.append(encodeParameter(url)); baseStrBuffer.append("&"); // Add all request params to the list, combine request and auth params in a single map // as per http://tools.ietf.org/html/rfc5849#section-3.4.1.3.1 // TODO Support multiple parameters with same name // Sort keys by param name // TODO Sort *after* encoding List<String> keys = new ArrayList<String>(sigParams.keySet()); Collections.sort(keys); int i = 0; for (String key : keys) { if (!key.equals(OAUTH_REALM) && !key.equals(OAUTH_SIGNATURE) && !key.equals(OAUTH_TOKEN_SECRET)) { if (i > 0) baseStrBuffer.append(encodeParameter("&")); baseStrBuffer.append( encodeParameter(encodeParameter(key) + "=" + encodeParameter(sigParams.get(key)))); i++; } } // Final base string String baseString = baseStrBuffer.toString(); // Key to use for signing String tokenSecret = authParams.get(OAUTH_TOKEN_SECRET); String key = encodeParameter(getConsumerSecret()) + "&" + encodeParameter(tokenSecret != null ? tokenSecret : ""); if (logger.isDebugEnabled()) logger.debug("Generating signature with key '" + key + "', base string '" + baseString + "'"); try { SecretKey keyStr = new SecretKeySpec(key.getBytes(), "HmacSHA1"); Mac m = Mac.getInstance("HmacSHA1"); m.init(keyStr); m.update(baseString.getBytes()); byte[] mac = m.doFinal(); return new String(Base64.encodeBytes(mac)).trim(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } else { throw new UnsupportedOperationException(); } }
From source file:net.mms_projects.copy_it.api.oauth.HeaderVerifier.java
/** * Validate the signature for the request, make sure you've called all verify* methods first * @param postRequestDecoder The post parameters for the request, pass null if it's a GET request instead * @param https Should we use https to generate our signature? * @throws OAuthException Thrown if the signature is invalid *//* w w w . j av a2 s. c om*/ public void checkSignature(HttpPostRequestDecoder postRequestDecoder, boolean https) throws UnsupportedEncodingException, URISyntaxException, OAuthException { final String signed_with = oauth_params.get(OAuthParameters.OAUTH_SIGNATURE); final String raw = createRaw(postRequestDecoder, https); final String secretkey = consumer.getSecretKey() + "&" + user.getSecretKey(); try { final Key signingKey = new SecretKeySpec(secretkey.getBytes(), HMAC_SHA1); final Mac mac = Mac.getInstance(HMAC_SHA1); mac.init(signingKey); byte[] rawHmac = mac.doFinal(raw.getBytes()); final String signature = new String(Base64.encodeBase64(rawHmac)); System.err.println("Signed with: " + URLDecoder.decode(signed_with, UTF_8)); System.err.println("Should be::: " + signature); if (!URLDecoder.decode(signed_with, UTF_8).equals(signature)) throw new OAuthException(ErrorMessages.INVALID_SIGNATURE); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } }
From source file:ch.bfh.evoting.alljoyn.MessageEncrypter.java
/** * //from w w w .j a v a 2 s. co m * Method that decrypts data * @param ciphertext byte array to decrypt * @return the decrypted string if decryption was successful, * null otherwise * */ public String decrypt(byte[] ciphertext) { //Inspired from http://stackoverflow.com/questions/992019/java-256-bit-aes-password-based-encryption //iv is same as block size: for AES => 128 bits = 16 bytes byte[] iv = Arrays.copyOfRange(ciphertext, 0, 16); byte[] cipherText = Arrays.copyOfRange(ciphertext, 16, ciphertext.length); Cipher cipher; try { cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(iv)); String s = new String(cipher.doFinal(cipherText)); //Since this decryption was successful, it means we have the correct key, //so we can disable the count of failed decryptions countDecryptionFailed = false; return s; } catch (NoSuchAlgorithmException e) { Log.d(TAG, e.getMessage() + " "); e.printStackTrace(); return null; } catch (NoSuchPaddingException e) { Log.d(TAG, e.getMessage() + " "); e.printStackTrace(); return null; } catch (InvalidKeyException e) { Log.d(TAG, e.getMessage() + " "); e.printStackTrace(); return null; } catch (InvalidAlgorithmParameterException e) { Log.d(TAG, e.getMessage() + " "); e.printStackTrace(); return null; } catch (IllegalBlockSizeException e) { Log.d(TAG, e.getMessage() + " "); countFailedDecryption(); e.printStackTrace(); return null; } catch (BadPaddingException e) { Log.d(TAG, e.getMessage() + " "); countFailedDecryption(); e.printStackTrace(); return null; } }
From source file:ch.bfh.evoting.alljoyn.MessageEncrypter.java
/** * Compute a truncated digest on the salt * We only take the three first letters (not chars!) of the Base64 encoded digest, because * this truncated digest must be transmitted with the group password (only letters) * @param salt the salt from on we want to compute the digest * @return the three first letters of the Base64 encoded digest *//*from ww w.j a v a 2 s. c o m*/ public String getSaltShortDigest(byte[] salt) { if (salt == null) return ""; //Compute the digest MessageDigest md; String saltHash; Log.d(TAG, "Computing salt digest"); try { md = MessageDigest.getInstance("SHA-1"); md.update(salt, 0, salt.length); saltHash = Base64.encodeToString(md.digest(), Base64.DEFAULT); } catch (NoSuchAlgorithmException e) { Log.e(TAG, "Digest of salt could not be computed"); e.printStackTrace(); return null; } //Truncate the digest String shortDigest = ""; int i = 0; while (shortDigest.length() < 3) { char c = saltHash.charAt(i); if (Character.isLetter(c)) { shortDigest = shortDigest.concat(String.valueOf(Character.toLowerCase(c))); } i++; if (i >= saltHash.length()) { break; } } Log.d(TAG, "Short digest is " + shortDigest); return shortDigest; }
From source file:at.stefanproell.ResultSetVerification.ResultSetVerificationAPI.java
private MessageDigest initCryptoModule(String algorithm) { HashSet<String> algorithms = new HashSet<String>(); algorithms.add("SHA-1"); algorithms.add("MD5"); algorithms.add("SHA-256"); if (algorithms.contains(algorithm)) { this.crypto = null; try {/*from ww w .ja v a 2 s . com*/ this.crypto = MessageDigest.getInstance(algorithm); this.crypto.reset(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } return this.crypto; }
From source file:com.ailk.oci.ocnosql.tools.load.csvbulkload.PhoenixCsvToKeyValueMapper.java
/** * ?16??/*from ww w. j a v a 2s.c om*/ */ private String getUniquePostfix(String plainText) { String result = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } result = buf.toString().substring(8, 24); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return result; }
From source file:ch.bfh.evoting.alljoyn.MessageEncrypter.java
/** * Method that encrypts data/*from w ww .j a va 2s .co m*/ * @param data The data which should be encrypted * @return The encrypted bytes, null if encryption failed * */ public byte[] encrypt(byte[] data) { //Inspired from http://stackoverflow.com/questions/992019/java-256-bit-aes-password-based-encryption Cipher cipher; try { cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); // cipher.getParameters() seems to return null on Android 4.3 (Bug?) // Solution implemented from here: // https://code.google.com/p/android/issues/detail?id=58191 byte[] iv; if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) { iv = generateIv(); cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(iv)); } else { cipher.init(Cipher.ENCRYPT_MODE, secretKey); AlgorithmParameters params = cipher.getParameters(); iv = params.getParameterSpec(IvParameterSpec.class).getIV(); } byte[] cipherText = cipher.doFinal(data); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); outputStream.write(iv); outputStream.write(cipherText); return outputStream.toByteArray(); } catch (NoSuchAlgorithmException e) { Log.d(TAG, e.getMessage() + " "); e.printStackTrace(); return null; } catch (NoSuchPaddingException e) { Log.d(TAG, e.getMessage() + " "); e.printStackTrace(); return null; } catch (InvalidKeyException e) { Log.d(TAG, e.getMessage() + " "); e.printStackTrace(); return null; } catch (InvalidParameterSpecException e) { Log.d(TAG, e.getMessage() + " "); e.printStackTrace(); return null; } catch (IllegalBlockSizeException e) { Log.d(TAG, e.getMessage() + " "); e.printStackTrace(); return null; } catch (BadPaddingException e) { Log.d(TAG, e.getMessage() + " "); e.printStackTrace(); return null; } catch (IOException e) { Log.d(TAG, e.getMessage() + " "); e.printStackTrace(); return null; } catch (InvalidAlgorithmParameterException e) { Log.d(TAG, e.getMessage() + " "); e.printStackTrace(); return null; } }
From source file:edu.hm.muse.controller.testcontroller.java
@RequestMapping(value = "/test.secu", method = RequestMethod.POST) ModelAndView nummernanalyse(@RequestParam(value = "zahl", required = true) String z, HttpSession session) { ModelAndView mv = new ModelAndView("test"); if (this == null) return mv; mv.addObject("msg", "Hier ist die Analyse. Und jetzt die nchste Zahl. " + "(Fr Zahlen kleiner 10 knnen auch Fakultten berechnet werden.)"); mv.addObject("ergebnis", "Hier ist die Analyse. Und jetzt die nchste Zahl."); int zahl = Integer.parseInt(z.toString()); int no = zahl; int i = 0, temp[] = new int[10000]; int binary[]; while (no > 0) { temp[i++] = no % 2;/*from w w w . j a v a 2 s . c o m*/ no /= 2; } binary = new int[i]; int k = 0; for (int j = i - 1; j >= 0; j--) { binary[k++] = temp[j]; } String binaryErgebnis = new String(); int laengeBinary = binary.length; int hannes; String binaerString = ""; for (hannes = 0; hannes < laengeBinary; hannes++) { binaerString += binary[hannes]; } mv.addObject("binaer", "In Binr:." + binaerString); int tausendvierunzwanzigfache; tausendvierunzwanzigfache = erstelletausendvierunzwanzigfache(zahl, 0); mv.addObject("tausendvierundzwanzigfache", "Das 1024-Fache der Zahl ist " + tausendvierunzwanzigfache); String isprime = "Nein"; boolean found = false; //calculate if prime if (zahl % 2 == 0) { isprime = "Nein"; } else { for (int c = 3; c * c <= zahl; c = c + 2) { if (zahl % c == 0) { found = true; isprime = "Nein"; } } if (found == false) { isprime = "Ja"; ; } } if (isprime == "Nein") { mv.addObject("prime", "Die Zahl ist keine Primzahl"); } else if (isprime == "Ja") { mv.addObject("prime", "Die Zahl ist eine Primzahl"); } class fakultaet { private final int number; public HashMap<Integer, Integer> fakultaet = new HashMap<Integer, Integer>(); private fakultaet() { this.number = 0; } public fakultaet(int number) { this.number = number; setNumberAndCalcHash(number); } public void setNumberAndCalcHash(int fkZahl) { for (int c = fkZahl; c > 0; c--) { fakultaet.put(c, calcFakRec(c)); System.out.println(c); //System.out.println(fakultaet.get(c)); } } private int calcFakRec(int fkZahl) { if (fkZahl == 1) { return 1; } else { return calcFakRec(fkZahl - 1) * fkZahl; } } } if (zahl < 10) { fakultaet fk = new fakultaet(zahl); fk.setNumberAndCalcHash(zahl); Object hashFK = fk.hashCode(); String fkString = ""; for (int a = 0; a <= fk.fakultaet.size(); a++) { fkString = fkString + " Zahl: " + a + " - " + "Fakultt: " + fk.fakultaet.get(a) + " ---- "; } fk.setNumberAndCalcHash(5); Object hashFKFuenf = fk.hashCode(); mv.addObject("fakultaet", "Die Zahl ist klein genug um eine Fakultt zu berechnen. Die Fakultt ist " + fk.fakultaet.get(zahl) + " ----------- Alle Fakultten in der bersicht: " + "" + fkString); mv.addObject("fakultaetFuenf", "Die Fakultt ist " + (hashFK.equals(hashFKFuenf) ? "gleich " : "nicht gleich") + " der Fakultt der Zahl 5." + "Die Fakultt der Zahl 5 ist " + "" + fk.fakultaet.get(5)); } else { mv.addObject("fakultaet", "Die Zahl ist zu gro um die Fakultt zu berechnen"); } class percentage { private float[] numbers; public float[] calcPercentageWithNumAs100Percent(float[] num, float percentage) { this.numbers = num; float[] result = new float[numbers.length]; for (int c = 0; c < numbers.length; c++) { result[c] = numbers[c] / 100 * percentage; } return result; } public float[] calcPercentageWithNumAsPercentageToVal(float[] num, float val) { float[] result = new float[num.length]; this.numbers = num; for (int c = 0; c < numbers.length; c++) { num[c] = val / 100 * numbers[c]; } return num; } } percentage p = new percentage(); float[] nums = new float[1]; nums[0] = zahl; try { float[] p1 = p.calcPercentageWithNumAs100Percent(nums, 25); float[] p2 = p.calcPercentageWithNumAsPercentageToVal(nums, 50); float pwSalt1 = p1[0] + p2[0] + nums[0]; System.out.println(p1[0] + " " + p2[0] + " " + nums[0]); String password1 = " SuperSicher " + pwSalt1; float[] p4 = p.calcPercentageWithNumAsPercentageToVal(nums, 50); float[] p3 = p.calcPercentageWithNumAs100Percent(nums, 25); float pwSalt2 = p3[0] + p4[0] + nums[0]; System.out.println(p3[0] + " " + p4[0] + " " + nums[0]); String password2 = " SuperSicher " + pwSalt2; System.out.println(password1 + " - " + password2); MessageDigest md = MessageDigest.getInstance("MD5"); String pw1 = convertToHex(md.digest(password1.getBytes())); md.reset(); String pw2 = convertToHex(md.digest(password2.getBytes())); if (pw1.equals(pw2)) { mv.addObject("password", "Es wurden zwei gleiche Passwrter-Hashes generiert. Der Hash / Die Hashes lauten " + pw1); } else { mv.addObject("password", "Es wurden zwei gleiche Passwrter-Hashes generiert. Leider ist wohl ein Fehler aufgetreten. Die Passwrter wurden aus den gleichen Daten genereiert, gleichen sich aber nicht. Die Hashes lauten: PW1: " + pw1 + " PW2: " + pw2); } //Check if Salt-generator works properly float[] check = new float[1]; check[0] = 100; float[] check1 = p.calcPercentageWithNumAs100Percent(check, 25); check[0] = 100; float[] check2 = p.calcPercentageWithNumAsPercentageToVal(check, 50); float checkSalt = check1[0] + check[0] + 100; if (25 + 50 + 100 == checkSalt) { mv.addObject("generator", "Der Generator funktioniert korrekt."); } else { mv.addObject("generator", "Der Generator funktioniert nicht."); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return mv; }