List of usage examples for java.security NoSuchAlgorithmException toString
public String toString()
From source file:utils.Hash.java
/** * Outputs a MD5 digest/*from w w w. j av a2s. c o m*/ * @param toHash String to hash * @return Hashed String */ public static String md5ThisString(String toHash) { String hashed = null; byte[] byteArray = new byte[512]; MessageDigest md; try { md = MessageDigest.getInstance("MD5"); log.debug("Hashing Value With " + md.getAlgorithm()); byteArray = toHash.getBytes(); md.update(byteArray); byteArray = md.digest(); } catch (NoSuchAlgorithmException e) { log.fatal("Could not Find MD5 Algorithm: " + e.toString()); } hashed = new String(byteArray, Charset.forName("US-ASCII")); return hashed; }
From source file:utils.Hash.java
/** * Outputs a SHA256 digest//from w w w .j a va2s . com * @param toHash String to hash * @return Hashed string */ public static String thisString(String toHash) { String hashed = null; byte[] byteArray = new byte[256]; MessageDigest md; try { md = MessageDigest.getInstance("SHA"); log.debug("Hashing Value With " + md.getAlgorithm()); byteArray = toHash.getBytes(); md.update(byteArray); byteArray = md.digest(); } catch (NoSuchAlgorithmException e) { log.fatal("Could not Find SHA Algorithm: " + e.toString()); } hashed = new String(byteArray, Charset.forName("US-ASCII")); return hashed; }
From source file:de.niklasmerz.cordova.fingerprint.Fingerprint.java
/** * Creates a symmetric key in the Android Key Store which can only be used after the user has * authenticated with fingerprint./* ww w . j a v a2 s .c o m*/ */ public static boolean createKey() { String errorMessage = ""; String createKeyExceptionErrorPrefix = "Failed to create key: "; boolean isKeyCreated = false; // The enrolling flow for fingerprint. This is where you ask the user to set up fingerprint // for your flow. Use of keys is necessary if you need to know if the set of // enrolled fingerprints has changed. try { mKeyStore.load(null); // Set the alias of the entry in Android KeyStore where the key will appear // and the constrains (purposes) in the constructor of the Builder mKeyGenerator.init(new KeyGenParameterSpec.Builder(mClientId, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) .setBlockModes(KeyProperties.BLOCK_MODE_CBC) // Require the user to authenticate with a fingerprint to authorize every use // of the key .setUserAuthenticationRequired(true) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7).build()); mKeyGenerator.generateKey(); isKeyCreated = true; } catch (NoSuchAlgorithmException e) { errorMessage = createKeyExceptionErrorPrefix + "NoSuchAlgorithmException: " + e.toString(); ; } catch (InvalidAlgorithmParameterException e) { errorMessage = createKeyExceptionErrorPrefix + "InvalidAlgorithmParameterException: " + e.toString(); ; } catch (CertificateException e) { errorMessage = createKeyExceptionErrorPrefix + "CertificateException: " + e.toString(); ; } catch (IOException e) { errorMessage = createKeyExceptionErrorPrefix + "IOException: " + e.toString(); ; } if (!isKeyCreated) { Log.e(TAG, errorMessage); setPluginResultError(errorMessage); } return isKeyCreated; }
From source file:main.java.vasolsim.common.GenericUtils.java
/** * initializes a cipher/*from w w w .j ava 2 s . c o m*/ * * @param key the key * @param mode the mode (Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE) * * @return an initialized cipher * * @throws VaSolSimException for all the usual crypto stuff */ public static Cipher initCrypto(byte[] key, int mode) throws VaSolSimException { if (mode != Cipher.ENCRYPT_MODE && mode != Cipher.DECRYPT_MODE) throw new VaSolSimException(ERROR_MESSAGE_BAD_CIPHER_MODE); byte[] parametricIV = new byte[16]; Cipher cipher; try { //create an IV SecureRandom random = new SecureRandom(); random.nextBytes(parametricIV); //initialize the crypto cipher = Cipher.getInstance(DEFAULT_SERVICE_PROVIDER_INTERFACE, DEFAULT_SERVICE_PROVIDER); cipher.init(mode, new SecretKeySpec(key, DEFAULT_ENCRYPTION_ALGORITHM), new IvParameterSpec(parametricIV)); } catch (NoSuchAlgorithmException e) { throw new VaSolSimException(ERROR_MESSAGE_GENERIC_CRYPTO + "\n\nBAD ALGORITHM\n" + e.toString() + "\n" + e.getCause() + "\n" + ExceptionUtils.getStackTrace(e), e); } catch (NoSuchProviderException e) { throw new VaSolSimException(ERROR_MESSAGE_GENERIC_CRYPTO + "\n\nBAD PROVIDER\n" + e.toString() + "\n" + e.getCause() + "\n" + ExceptionUtils.getStackTrace(e), e); } catch (NoSuchPaddingException e) { throw new VaSolSimException(ERROR_MESSAGE_GENERIC_CRYPTO + "\n\nNO SUCH PADDING\n" + e.toString() + "\n" + e.getCause() + "\n" + ExceptionUtils.getStackTrace(e), e); } catch (InvalidKeyException e) { throw new VaSolSimException(ERROR_MESSAGE_GENERIC_CRYPTO + "\n\nBAD KEY\n" + e.toString() + "\n" + e.getCause() + "\n" + ExceptionUtils.getStackTrace(e), e); } catch (InvalidAlgorithmParameterException e) { throw new VaSolSimException(ERROR_MESSAGE_GENERIC_CRYPTO + "\n\nBAD ALGORITHM PARAMS\n" + e.toString() + "\n" + e.getCause() + "\n" + ExceptionUtils.getStackTrace(e), e); } return cipher; }
From source file:com.streamsets.pipeline.lib.http.oauth2.OAuth2ConfigBean.java
private static PrivateKey parseRSAKey(String key, Stage.Context context, List<Stage.ConfigIssue> issues) { String privKeyPEM = key.replace("-----BEGIN PRIVATE KEY-----\n", ""); privKeyPEM = privKeyPEM.replace("-----END PRIVATE KEY-----", ""); privKeyPEM = privKeyPEM.replace("\n", ""); privKeyPEM = privKeyPEM.replace("\r", ""); try {// ww w.j a v a 2 s . c o m // Base64 decode the data byte[] encoded = Base64.getDecoder().decode(privKeyPEM.getBytes()); // PKCS8 decode the encoded RSA private key PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded); KeyFactory kf = KeyFactory.getInstance(RSA); return kf.generatePrivate(keySpec); } catch (NoSuchAlgorithmException ex) { LOG.error(Utils.format("'{}' algorithm not available", RSA), ex); issues.add(context.createConfigIssue(CONFIG_GROUP, PREFIX + "algorithm", HTTP_25)); } catch (InvalidKeySpecException ex) { LOG.error(Utils.format("'{}' algorithm not available", RSA), ex); issues.add(context.createConfigIssue(CONFIG_GROUP, PREFIX + "key", HTTP_26)); } catch (IllegalArgumentException ex) { LOG.error("Invalid key", ex); issues.add(context.createConfigIssue(CONFIG_GROUP, PREFIX + "key", HTTP_27, ex.toString())); } return null; }
From source file:org.openintents.safe.CryptoHelper.java
/** * @return null if failure, otherwise hex string version of key * @author Isaac Potoczny-Jones/*from w w w .j a v a2s.co m*/ */ public static String generateMasterKey() throws NoSuchAlgorithmException { try { KeyGenerator keygen; keygen = KeyGenerator.getInstance("AES"); keygen.init(256); SecretKey genDesKey = keygen.generateKey(); return toHexString(genDesKey.getEncoded()); } catch (NoSuchAlgorithmException e) { Log.e(TAG, "generateMasterKey(): " + e.toString()); throw e; } }
From source file:org.openintents.safe.CryptoHelper.java
/** * @param message//from w w w.ja v a 2 s . c om * @return MD5 digest of message in a byte array * @throws NoSuchAlgorithmException * @throws IOException */ public static byte[] md5String(String message) { byte[] input = message.getBytes(); MessageDigest hash; ByteArrayInputStream bIn = null; DigestInputStream dIn = null; try { hash = MessageDigest.getInstance("MD5"); bIn = new ByteArrayInputStream(input); dIn = new DigestInputStream(bIn, hash); for (int i = 0; i < input.length; i++) { dIn.read(); } } catch (NoSuchAlgorithmException e) { Log.e(TAG, "md5String(): " + e.toString()); } catch (IOException e) { Log.e(TAG, "md5String(): " + e.toString()); } return dIn.getMessageDigest().digest(); }
From source file:com.vmware.identity.samlservice.DefaultSamlServiceFactory.java
@Override public SamlService createSamlService(PrivateKey privateKey, SignatureAlgorithm signAlgorithm, SignatureAlgorithm checkAlgorithm, String issuer, CertPath certPath) { SamlServiceImpl samlServiceImpl = null; try {/* w ww. j a va 2s.c o m*/ samlServiceImpl = new SamlServiceImpl(); samlServiceImpl.setPrivateKey(privateKey); samlServiceImpl.setSignAlgorithm(signAlgorithm); samlServiceImpl.setCheckAlgorithm(checkAlgorithm); samlServiceImpl.setIssuer(issuer); samlServiceImpl.setCertPath(certPath); } catch (NoSuchAlgorithmException e) { log.debug("Caught exception " + e.toString()); } Validate.notNull(samlServiceImpl, "samlServiceImpl"); return samlServiceImpl; }
From source file:org.jivesoftware.community.util.ssl.DummySSLSocketFactory.java
public DummySSLSocketFactory() { try {/*from w ww . j a va2 s. c o m*/ SSLContext sslcontent = SSLContext.getInstance("SSL"); sslcontent.init(null, new TrustManager[] { new DummyTrustManager() }, new SecureRandom()); factory = sslcontent.getSocketFactory(); } catch (NoSuchAlgorithmException e) { Log.error(e.toString()); } catch (KeyManagementException e) { Log.error(e.toString()); } }
From source file:org.opendatakit.briefcase.util.FileSystemUtils.java
private static boolean decryptSubmissionFiles(String base64EncryptedSymmetricKey, FormInstanceMetadata fim, List<String> mediaNames, String encryptedSubmissionFile, String base64EncryptedElementSignature, PrivateKey rsaPrivateKey, File instanceDir, File unencryptedDir) throws FileSystemException, CryptoException, ParsingException { EncryptionInformation ei = new EncryptionInformation(base64EncryptedSymmetricKey, fim.instanceId, rsaPrivateKey);// ww w.j ava2s . com byte[] elementDigest; try { // construct the base64-encoded RSA-encrypted symmetric key Cipher pkCipher; pkCipher = Cipher.getInstance(ASYMMETRIC_ALGORITHM); // extract digest pkCipher.init(Cipher.DECRYPT_MODE, rsaPrivateKey); byte[] encryptedElementSignature = Base64.decodeBase64(base64EncryptedElementSignature); elementDigest = pkCipher.doFinal(encryptedElementSignature); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new CryptoException("Error decrypting base64EncryptedElementSignature Cause: " + e.toString()); } catch (NoSuchPaddingException e) { e.printStackTrace(); throw new CryptoException("Error decrypting base64EncryptedElementSignature Cause: " + e.toString()); } catch (InvalidKeyException e) { e.printStackTrace(); throw new CryptoException("Error decrypting base64EncryptedElementSignature Cause: " + e.toString()); } catch (IllegalBlockSizeException e) { e.printStackTrace(); throw new CryptoException("Error decrypting base64EncryptedElementSignature Cause: " + e.toString()); } catch (BadPaddingException e) { e.printStackTrace(); throw new CryptoException("Error decrypting base64EncryptedElementSignature Cause: " + e.toString()); } // NOTE: will decrypt only the files in the media list, plus the encryptedSubmissionFile File[] allFiles = instanceDir.listFiles(); List<File> filesToProcess = new ArrayList<File>(); for (File f : allFiles) { if (mediaNames.contains(f.getName())) { filesToProcess.add(f); } else if (encryptedSubmissionFile.equals(f.getName())) { filesToProcess.add(f); } } // should have all media files plus one submission.xml.enc file if (filesToProcess.size() != mediaNames.size() + 1) { // figure out what we're missing... int lostFileCount = 0; List<String> missing = new ArrayList<String>(); for (String name : mediaNames) { if (name == null) { // this was lost due to an pre-ODK Aggregate 1.4.5 mark-as-complete action ++lostFileCount; continue; } File f = new File(instanceDir, name); if (!filesToProcess.contains(f)) { missing.add(name); } } StringBuilder b = new StringBuilder(); for (String name : missing) { b.append(" ").append(name); } if (!filesToProcess.contains(new File(instanceDir, encryptedSubmissionFile))) { b.append(" ").append(encryptedSubmissionFile); throw new FileSystemException( "Error decrypting: " + instanceDir.getName() + " Missing files:" + b.toString()); } else { // ignore the fact that we don't have the lost files if (filesToProcess.size() + lostFileCount != mediaNames.size() + 1) { throw new FileSystemException( "Error decrypting: " + instanceDir.getName() + " Missing files:" + b.toString()); } } } // decrypt the media files IN ORDER. for (String mediaName : mediaNames) { String displayedName = (mediaName == null) ? "<missing .enc file>" : mediaName; File f = (mediaName == null) ? null : new File(instanceDir, mediaName); try { decryptFile(ei, f, unencryptedDir); } catch (InvalidKeyException e) { e.printStackTrace(); throw new CryptoException("Error decrypting:" + displayedName + " Cause: " + e.toString()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new CryptoException("Error decrypting:" + displayedName + " Cause: " + e.toString()); } catch (InvalidAlgorithmParameterException e) { e.printStackTrace(); throw new CryptoException("Error decrypting:" + displayedName + " Cause: " + e.toString()); } catch (NoSuchPaddingException e) { e.printStackTrace(); throw new CryptoException("Error decrypting:" + displayedName + " Cause: " + e.toString()); } catch (IOException e) { e.printStackTrace(); throw new FileSystemException("Error decrypting:" + displayedName + " Cause: " + e.toString()); } } // decrypt the submission file File f = new File(instanceDir, encryptedSubmissionFile); try { decryptFile(ei, f, unencryptedDir); } catch (InvalidKeyException e) { e.printStackTrace(); throw new CryptoException("Error decrypting:" + f.getName() + " Cause: " + e.toString()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new CryptoException("Error decrypting:" + f.getName() + " Cause: " + e.toString()); } catch (InvalidAlgorithmParameterException e) { e.printStackTrace(); throw new CryptoException("Error decrypting:" + f.getName() + " Cause: " + e.toString()); } catch (NoSuchPaddingException e) { e.printStackTrace(); throw new CryptoException("Error decrypting:" + f.getName() + " Cause: " + e.toString()); } catch (IOException e) { e.printStackTrace(); throw new FileSystemException("Error decrypting:" + f.getName() + " Cause: " + e.toString()); } // get the FIM for the decrypted submission file File submissionFile = new File(unencryptedDir, encryptedSubmissionFile.substring(0, encryptedSubmissionFile.lastIndexOf(".enc"))); FormInstanceMetadata submissionFim; try { Document subDoc = XmlManipulationUtils.parseXml(submissionFile); submissionFim = XmlManipulationUtils.getFormInstanceMetadata(subDoc.getRootElement()); } catch (ParsingException e) { e.printStackTrace(); throw new FileSystemException( "Error decrypting: " + submissionFile.getName() + " Cause: " + e.toString()); } catch (FileSystemException e) { e.printStackTrace(); throw new FileSystemException( "Error decrypting: " + submissionFile.getName() + " Cause: " + e.getMessage()); } boolean same = submissionFim.xparam.formId.equals(fim.xparam.formId); if (!same) { throw new FileSystemException("Error decrypting:" + unencryptedDir.getName() + " Cause: form instance metadata differs from that in manifest"); } // Construct the element signature string StringBuilder b = new StringBuilder(); appendElementSignatureSource(b, fim.xparam.formId); if (fim.xparam.modelVersion != null) { appendElementSignatureSource(b, Long.toString(fim.xparam.modelVersion)); } appendElementSignatureSource(b, base64EncryptedSymmetricKey); appendElementSignatureSource(b, fim.instanceId); boolean missingFile = false; for (String encFilename : mediaNames) { if (encFilename == null) { missingFile = true; continue; } File decryptedFile = new File(unencryptedDir, encFilename.substring(0, encFilename.lastIndexOf(".enc"))); if (decryptedFile.getName().endsWith(".missing")) { // this is a missing file -- we will not be able to // confirm the signature of the submission. missingFile = true; continue; } String md5 = FileSystemUtils.getMd5Hash(decryptedFile); appendElementSignatureSource(b, decryptedFile.getName() + "::" + md5); } String md5 = FileSystemUtils.getMd5Hash(submissionFile); appendElementSignatureSource(b, submissionFile.getName() + "::" + md5); // compute the digest of the element signature string byte[] messageDigest; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(b.toString().getBytes("UTF-8")); messageDigest = md.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new CryptoException("Error computing xml signature Cause: " + e.toString()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); throw new CryptoException("Error computing xml signature Cause: " + e.toString()); } same = true; for (int i = 0; i < messageDigest.length; ++i) { if (messageDigest[i] != elementDigest[i]) { same = false; break; } } return same; }