Java Code Examples for java.security.NoSuchAlgorithmException

The following are top voted examples for showing how to use java.security.NoSuchAlgorithmException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: E-Clinic   File: AdminClinicServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
public void updatePassword(AdminClinicForm value) throws PasswordException, RepositoryException, NoSuchAlgorithmException {
    if (value.getCurrentPassword() == null || value.getConfirmPassword() == null || value.getNewPassword() == null) {
        throw new PasswordException("Please fill all the required filds");
    }
    if (!value.getConfirmPassword().equals(value.getNewPassword())) {
        throw new PasswordException("Password didnt match");
    }

    Adminclinic adminclinic = adminClinicRepository.findById(Integer.valueOf(value.getId()));
    if (!encodehashPassword(value.getCurrentPassword()).equals(adminclinic.getPassCode())) {
        throw new PasswordException("Old password didnt match");
    }

    adminclinic.setPassCode(encodehashPassword(value.getNewPassword()));
    adminClinicRepository.update(adminclinic);
}
 
Example 2
Project: osc-core   File: AddSSLCertificateWindow.java   Source Code and License 6 votes vote down vote up
private ArrayList<CertificateBasicInfoModel> getCertificateBasicInfoModelList() {
    ArrayList<CertificateBasicInfoModel> certificateBasicInfoModels = new ArrayList<>();

    for (CertificateResolverModel basicInfoModel : this.certificateResolverModels) {
        try {
            certificateBasicInfoModels.add(new CertificateBasicInfoModel(
                    basicInfoModel.getAlias(),
                    this.trustManager.getSha1Fingerprint(basicInfoModel.getCertificate()),
                    basicInfoModel.getCertificate().getIssuerDN().getName(),
                    basicInfoModel.getCertificate().getNotBefore(),
                    basicInfoModel.getCertificate().getNotAfter(),
                    basicInfoModel.getCertificate().getSigAlgName(),
                    this.trustManager.certificateToString(basicInfoModel.getCertificate()))
            );
        } catch (NoSuchAlgorithmException | CertificateEncodingException e) {
            log.error("Cannot create certificate basic information model", e);
        }
    }
    return certificateBasicInfoModels;
}
 
Example 3
Project: https-github.com-apache-zookeeper   File: DigestAuthenticationProvider.java   Source Code and License 6 votes vote down vote up
public KeeperException.Code 
    handleAuthentication(ServerCnxn cnxn, byte[] authData)
{
    String id = new String(authData);
    try {
        String digest = generateDigest(id);
        if (digest.equals(superDigest)) {
            cnxn.addAuthInfo(new Id("super", ""));
        }
        cnxn.addAuthInfo(new Id(getScheme(), digest));
        return KeeperException.Code.OK;
    } catch (NoSuchAlgorithmException e) {
        LOG.error("Missing algorithm",e);
    }
    return KeeperException.Code.AUTHFAILED;
}
 
Example 4
Project: Drones-Simulator   File: RabbitConnection.java   Source Code and License 6 votes vote down vote up
/**
 * Updates the connection config based on a discovered configuration.
 * @param config The configuration.
 */
public void setConfig(Dictionary<String, String> config) {
    this.connectionFactory = new ConnectionFactory();

    if (config != null) {
        String username = config.get("username");
        this.connectionFactory.setUsername(username);

        String password = config.get("password");
        this.connectionFactory.setPassword(password);
        try {
            String uri = config.get("uri");
            this.connectionFactory.setUri(uri);
            this.getLogger().debug("Received configuration, RabbitMQ URI is {}", uri);
        } catch (URISyntaxException | NoSuchAlgorithmException | KeyManagementException e) {
            this.getLogger().error("Invalid URI found in configuration", e);
        }
    } else {
        this.getLogger().debug("Unset RabbitMQ configuration");
    }
}
 
Example 5
Project: bubble2   File: HttpUtils.java   Source Code and License 6 votes vote down vote up
/**
 * 获取LayeredConnectionSocketFactory 使用ssl单向认证
 * 
 * @date 2015年7月17日
 * @return
 */
private LayeredConnectionSocketFactory getSSLSocketFactory() {
	try {
		SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

			// 信任所有
			public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
				return true;
			}
		}).build();

		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
				SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		return sslsf;
	} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
		logger.error(e.getMessage(), e);
		throw new RuntimeException(e.getMessage(), e);
	}
}
 
Example 6
Project: pub-service   File: StringUtil.java   Source Code and License 6 votes vote down vote up
public static String md5(String str, boolean zero) {
	MessageDigest messageDigest = null;
	try {
		messageDigest = MessageDigest.getInstance("MD5");
	} catch (NoSuchAlgorithmException ex) {
		ex.printStackTrace();
		return null;
	}
	byte[] resultByte = messageDigest.digest(str.getBytes());
	StringBuffer result = new StringBuffer();
	for (int i = 0; i < resultByte.length; ++i) {
		int v = 0xFF & resultByte[i];
		if(v<16 && zero)
			result.append("0");
		result.append(Integer.toHexString(v));
	}
	return result.toString();
}
 
Example 7
Project: xitk   File: DfltConcurrentContentSigner.java   Source Code and License 6 votes vote down vote up
public DfltConcurrentContentSigner(boolean mac, List<XiContentSigner> signers,
        Key signingKey) throws NoSuchAlgorithmException {
    ParamUtil.requireNonEmpty("signers", signers);

    this.mac = mac;
    AlgorithmIdentifier algorithmIdentifier = signers.get(0).getAlgorithmIdentifier();
    this.algorithmName = AlgorithmUtil.getSigOrMacAlgoName(algorithmIdentifier);
    this.algorithmCode = AlgorithmUtil.getSigOrMacAlgoCode(algorithmIdentifier);

    for (XiContentSigner signer : signers) {
        this.signers.add(new ConcurrentBagEntrySigner(signer));
    }

    this.signingKey = signingKey;
    this.name = "defaultSigner-" + NAME_INDEX.getAndIncrement();
}
 
Example 8
Project: springboot-shiro-cas-mybatis   File: DuoWeb.java   Source Code and License 6 votes vote down vote up
public static String verifyResponse(final String ikey, final String skey, final String akey, final String sig_response, final long time)
    throws DuoWebException, NoSuchAlgorithmException, InvalidKeyException, IOException {

    final String[] sigs = sig_response.split(":");
    final String auth_sig = sigs[0];
    final String app_sig = sigs[1];

    String auth_user = parseVals(skey, auth_sig, AUTH_PREFIX, ikey, time);
    String app_user = parseVals(akey, app_sig, APP_PREFIX, ikey, time);

    if (!auth_user.equals(app_user)) {
        throw new DuoWebException("Authentication failed.");
    }

    return auth_user;
}
 
Example 9
Project: rapid-io-android   File: SubscriptionDiskCache.java   Source Code and License 6 votes vote down vote up
@Nullable
public synchronized String get(@NonNull BaseCollectionSubscription subscription) throws IOException, JSONException, NoSuchAlgorithmException {
	if(!mEnabled)
		return null;
	String fingerprint = subscription.getFingerprint();
	DiskLruCache.Snapshot record = mCache.get(fingerprint);
	if(record != null) {
		InputStream inputstream = record.getInputStream(DEFAULT_INDEX);
		byte[] rec = StreamUtility.toByteArray(inputstream);
		String jsonValue = XorUtility.xor(rec, subscription.getAuthToken());
		Logcat.d("Reading from subscription cache. key=%s; value=%s", fingerprint, jsonValue);
		JSONArray documentIdArray = new JSONArray(jsonValue);
		JSONArray documentArray = new JSONArray();
		for(int i = 0; i < documentIdArray.length(); i++) {
			String document = getDocument(subscription, documentIdArray.optString(i));
			if(document == null) {
				return null;
			}
			documentArray.put(new JSONObject(document));
		}

		return documentArray.toString();
	}
	Logcat.d("Reading from disk subscription cache. key=%s; value=null", fingerprint);
	return null;
}
 
Example 10
Project: lams   File: Security.java   Source Code and License 6 votes vote down vote up
/**
 * Stage one password hashing, used in MySQL 4.1 password handling
 * 
 * @param password
 *            plaintext password
 * 
 * @return stage one hash of password
 * 
 * @throws NoSuchAlgorithmException
 *             if the message digest 'SHA-1' is not available.
 */
static byte[] passwordHashStage1(String password) throws NoSuchAlgorithmException {
    MessageDigest md = MessageDigest.getInstance("SHA-1");
    StringBuilder cleansedPassword = new StringBuilder();

    int passwordLength = password.length();

    for (int i = 0; i < passwordLength; i++) {
        char c = password.charAt(i);

        if ((c == ' ') || (c == '\t')) {
            continue; /* skip space in password */
        }

        cleansedPassword.append(c);
    }

    return md.digest(StringUtils.getBytes(cleansedPassword.toString()));
}
 
Example 11
Project: file-transfer   File: HtmlPage.java   Source Code and License 6 votes vote down vote up
public HtmlPage(String link) {
    VBox root = new VBox();
    Scene scene = new Scene(root);
    setTitle("FileSend - Page");
    final WebView browser = new WebView();
    final WebEngine webEngine = browser.getEngine();
    try {
        httpsLoad(webEngine, link);
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        e.printStackTrace();
    }
    root.getChildren().add(browser);
    VBox.setVgrow(browser, Priority.ALWAYS);
    getIcons().add(new Image(getClass().getResourceAsStream(".." + File.separator + "images" + File.separator + "logo.png")));
    setScene(scene);
    setMaximized(true);
}
 
Example 12
Project: OpenJSharp   File: URICertStore.java   Source Code and License 6 votes vote down vote up
/**
 * Creates a URICertStore.
 *
 * @param parameters specifying the URI
 */
URICertStore(CertStoreParameters params)
    throws InvalidAlgorithmParameterException, NoSuchAlgorithmException {
    super(params);
    if (!(params instanceof URICertStoreParameters)) {
        throw new InvalidAlgorithmParameterException
            ("params must be instanceof URICertStoreParameters");
    }
    this.uri = ((URICertStoreParameters) params).uri;
    // if ldap URI, use an LDAPCertStore to fetch certs and CRLs
    if (uri.getScheme().toLowerCase(Locale.ENGLISH).equals("ldap")) {
        ldap = true;
        ldapHelper = CertStoreHelper.getInstance("LDAP");
        ldapCertStore = ldapHelper.getCertStore(uri);
        ldapPath = uri.getPath();
        // strip off leading '/'
        if (ldapPath.charAt(0) == '/') {
            ldapPath = ldapPath.substring(1);
        }
    }
    try {
        factory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        throw new RuntimeException();
    }
}
 
Example 13
Project: Ships   File: DigitalSignature.java   Source Code and License 6 votes vote down vote up
/**
 * Create a signature with the private key
 * @param data The data to sign
 * @return Base64 encoded signature
 */
public String sign(final String data) {
    final String tag = "sign - ";

    String result = null;

    try {
        Signature rsa = Signature.getInstance(CryptConstants.ALGORITHM_SIGNATURE);
        final PrivateKey key=retrievePrivateKey();
        if (key!=null) {
            rsa.initSign(key);
            rsa.update(data.getBytes());
            result = Base64.encodeToString(rsa.sign(),Base64.DEFAULT);
        }
    } catch (SignatureException | NoSuchAlgorithmException | InvalidKeyException e) {
        Log.e(TAG, tag, e);
    }

    return result;
}
 
Example 14
Project: osc-core   File: SslContextProvider.java   Source Code and License 6 votes vote down vote up
private SslContextProvider() {
    // load SSL context
    TrustManager[] trustManager = new TrustManager[]{X509TrustManagerFactory.getInstance()};
    try {
        this.sslContext = SSLContext.getInstance("TLSv1.2");
        this.sslContext.init(null, trustManager, new SecureRandom());

        // disable SSL session caching - we load SSL certificates dinamically so we need to ensure
        // that we have up to date cached certificates list
        this.sslContext.getClientSessionContext().setSessionCacheSize(1);
        this.sslContext.getClientSessionContext().setSessionTimeout(1);
        this.sslContext.getServerSessionContext().setSessionCacheSize(1);
        this.sslContext.getServerSessionContext().setSessionTimeout(1);

    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        LOG.error("Encountering security exception in SSL context", e);
        throw new RuntimeException("Internal error with SSL context", e);
    }
}
 
Example 15
Project: dhus-core   File: User.java   Source Code and License 6 votes vote down vote up
public String hash ()
{
   String source = getUUID() + "-" + getUsername () + "@" + getEmail () + 
      " - " + getPassword ();
   MessageDigest md;
   byte[] digest;
   try
   {
      md = MessageDigest.getInstance ("MD5");
      digest = md.digest (source.getBytes ());
   }
   catch (NoSuchAlgorithmException e)
   {
      throw new UnsupportedOperationException (
         "Cannot compute MD5 digest for user " + getUsername (), e);
   }
   StringBuffer sb = new StringBuffer ();
   for (int i = 0; i < digest.length; ++i)
   {
      sb.append (Integer.toHexString ( (digest[i] & 0xFF) | 0x100)
         .substring (1, 3));
   }
   return sb.toString ();
}
 
Example 16
Project: appinventor-extensions   File: PasswordHash.java   Source Code and License 6 votes vote down vote up
/**
 * Validates a password using a hash.
 *
 * @param   password        the password to check
 * @param   correctHash     the hash of the valid password
 * @return                  true if the password is correct, false if not
 */
public static boolean validatePassword(char[] password, String correctHash)
    throws NoSuchAlgorithmException, InvalidKeySpecException
{
    // Decode the hash into its parameters
    String[] params = correctHash.split(":");
    int iterations = Integer.parseInt(params[ITERATION_INDEX]);
    byte[] salt = fromHex(params[SALT_INDEX]);
    byte[] hash = fromHex(params[PBKDF2_INDEX]);
    // Compute the hash of the provided password, using the same salt,
    // iteration count, and hash length
    byte[] testHash = pbkdf2(password, salt, iterations, hash.length);
    // Compare the hashes in constant time. The password is correct if
    // both hashes match.
    return slowEquals(hash, testHash);
}
 
Example 17
Project: NoraUi   File: Security.java   Source Code and License 6 votes vote down vote up
public String createSha1(File file) throws TechnicalException {
    try (InputStream fis = new FileInputStream(file);) {
        MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
        int n = 0;
        byte[] buffer = new byte[8192];
        while (n != -1) {
            n = fis.read(buffer);
            if (n > 0) {
                sha1.update(buffer, 0, n);
            }
        }
        return new HexBinaryAdapter().marshal(sha1.digest());
    } catch (NoSuchAlgorithmException | IOException e) {
        throw new TechnicalException(Messages.getMessage(TechnicalException.TECHNICAL_ERROR_MESSAGE_CHECKSUM_IO_EXCEPTION), e);
    }
}
 
Example 18
Project: rongyunDemo   File: MD5.java   Source Code and License 5 votes vote down vote up
/**
 * MD5加密
 * @param str 待加密的字符串
 * @param lowerCase 大小写
 * @return
 */
public static String encrypt(String str, boolean lowerCase) {
    String result = null;
    try {
        result = str;
        MessageDigest md = MessageDigest.getInstance("MD5");
        result = byteToString(md.digest(str.getBytes()));
        if (lowerCase) {
            result = result.toLowerCase();
        }
    } catch (NoSuchAlgorithmException ex) {
        ex.printStackTrace();
    }
    return result;
}
 
Example 19
Project: Cross-Platform-AES   File: CryptLib.java   Source Code and License 5 votes vote down vote up
/***
 * This function computes the SHA256 hash of input string
 * @param text input text whose SHA256 hash has to be computed
 * @param length length of the text to be returned
 * @return returns SHA256 hash of input text
 * @throws NoSuchAlgorithmException
 * @throws UnsupportedEncodingException
 */
public static String SHA256 (String text, int length) throws NoSuchAlgorithmException, UnsupportedEncodingException {

    String resultStr;
    MessageDigest md = MessageDigest.getInstance("SHA-256");

    md.update(text.getBytes("UTF-8"));
    byte[] digest = md.digest();

    StringBuffer result = new StringBuffer();
    for (byte b : digest) {
        result.append(String.format("%02x", b)); //convert to hex
    }
    //return result.toString();

    if(length > result.toString().length())
    {
        resultStr = result.toString();
    }
    else
    {
        resultStr = result.toString().substring(0, length);
    }

    return resultStr;

}
 
Example 20
Project: slardar   File: CodecUtils.java   Source Code and License 5 votes vote down vote up
public static long hash(String key) {
    MessageDigest md5 = null;
    try {
        md5 = MessageDigest.getInstance(SHA1.name);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    md5.update(key.getBytes());
    byte[] bKey = md5.digest();
    long res = ((long) (bKey[3] & 0xFF) << 24) | ((long) (bKey[2] & 0xFF) << 16) | ((long) (bKey[1] & 0xFF) << 8)
            | (long) (bKey[0] & 0xFF);
    return res & 0xffffffffL;
}
 
Example 21
Project: paillier   File: PaillierCryptosystemUtil.java   Source Code and License 5 votes vote down vote up
/**
 * The method does the encryption by passing the bytes array and the
 * Paillier Public key as parameters.
 * 
 * @param VoteMessage
 *            - byte[]
 * @param pubKey
 * @return result - BigInteger (ciphertext)
 * @throws NoSuchAlgorithmException
 * @throws GeneralSecurityException
 * 
 */
private final BigInteger encrypt(final byte[] VoteMessage, final PublicKey pubKey)
		throws NoSuchAlgorithmException, GeneralSecurityException {

	byte[] cipherText = null;
    Cipher cipher = Cipher.getInstance("PaillierHP");
	// encrypt the voter's message using the public key
	cipher.init(Cipher.ENCRYPT_MODE, pubKey);
	cipherText = cipher.update(VoteMessage);
	BigInteger result = new BigInteger(cipherText);

	return result;

}
 
Example 22
Project: lams   File: AdvertiseListener.java   Source Code and License 5 votes vote down vote up
/** Set Advertise security key
 * @param key The key to use.<br/>
 *      Security key must match the AdvertiseKey
 *      on the advertised server.
 */
public void     setSecurityKey(String key)
    throws NoSuchAlgorithmException
{
    securityKey = key;
    if (md == null)
        md = MessageDigest.getInstance("MD5");
}
 
Example 23
Project: encrypt   File: RSAUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 获取 KeyFactory
 *
 * @throws NoSuchAlgorithmException 异常
 */
private static KeyFactory getKeyFactory() throws NoSuchAlgorithmException,
        NoSuchProviderException {
    KeyFactory keyFactory;
    if (Build.VERSION.SDK_INT >= 16) {
        keyFactory = KeyFactory.getInstance("RSA", "BC");
    } else {
        keyFactory = KeyFactory.getInstance("RSA");
    }
    return keyFactory;
}
 
Example 24
Project: AndroidUtilCode-master   File: EncryptUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Hmac加密模板
 *
 * @param data      数据
 * @param key       秘钥
 * @param algorithm 加密算法
 * @return 密文字节数组
 */
private static byte[] hmacTemplate(byte[] data, byte[] key, String algorithm) {
    if (data == null || data.length == 0 || key == null || key.length == 0) return null;
    try {
        SecretKeySpec secretKey = new SecretKeySpec(key, algorithm);
        Mac mac = Mac.getInstance(algorithm);
        mac.init(secretKey);
        return mac.doFinal(data);
    } catch (InvalidKeyException | NoSuchAlgorithmException e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 25
Project: BTNotifierAndroid   File: SslUtils.java   Source Code and License 5 votes vote down vote up
private void trustCertificate(Certificate cert, String deviceLabel) throws KeyStoreException, CertificateException, IOException, NoSuchAlgorithmException {
    KeyStore ts = getKeyStore();

    Log.i(TAG, "Adding certificate ID " + deviceLabel + " to Trust store (" + trustStorePath + "): " + cert);
    ts.setCertificateEntry(deviceLabel, cert);

    ts.store(new FileOutputStream(trustStorePath), null);
}
 
Example 26
Project: PeSanKita-android   File: MasterSecretUtil.java   Source Code and License 5 votes vote down vote up
private static byte[] generateSalt() throws NoSuchAlgorithmException {
  SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
  byte[] salt         = new byte[16];
  random.nextBytes(salt);

  return salt;
}
 
Example 27
Project: xmrwallet   File: BitcoinAddressValidator.java   Source Code and License 5 votes vote down vote up
private static byte[] sha256(byte[] data) {
    try {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(data);
        return md.digest();
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 28
Project: mobile-store   File: Hasher.java   Source Code and License 5 votes vote down vote up
private void init(String type) throws NoSuchAlgorithmException {
    try {
        digest = MessageDigest.getInstance(type);
    } catch (Exception e) {
        throw new NoSuchAlgorithmException(e);
    }
}
 
Example 29
Project: jdk8u-jdk   File: CipherTestUtils.java   Source Code and License 5 votes vote down vote up
public AlwaysTrustManager(KeyStore keyStore)
        throws NoSuchAlgorithmException, KeyStoreException {

    TrustManagerFactory tmf
            = TrustManagerFactory.getInstance(TrustManagerFactory.
                    getDefaultAlgorithm());
    tmf.init(keyStore);

    TrustManager tms[] = tmf.getTrustManagers();
    for (TrustManager tm : tms) {
        trustManager = (X509TrustManager) tm;
        return;
    }

}
 
Example 30
Project: openjdk-jdk10   File: CICOSkipTest.java   Source Code and License 5 votes vote down vote up
private void initCiphers(String algo, SecretKey key,
        AlgorithmParameterSpec aps) throws NoSuchAlgorithmException,
        NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException {
    Provider provider = Security.getProvider("SunJCE");
    if (provider == null) {
        throw new RuntimeException("SunJCE provider does not exist.");
    }
    Cipher ci1 = Cipher.getInstance(algo, provider);
    ci1.init(Cipher.ENCRYPT_MODE, key, aps);
    pair[0] = ci1;
    Cipher ci2 = Cipher.getInstance(algo, provider);
    ci2.init(Cipher.DECRYPT_MODE, key, aps);
    pair[1] = ci2;
}
 
Example 31
Project: jerrydog   File: HttpConnector.java   Source Code and License 5 votes vote down vote up
/**
 * Initialize this connector (create ServerSocket here!)
 */
public void initialize()
throws LifecycleException {
    if (initialized)
        throw new LifecycleException (
            sm.getString("httpConnector.alreadyInitialized"));

    this.initialized=true;
    Exception eRethrow = null;

    // Establish a server socket on the specified port
    try {
        serverSocket = open();
    } catch (IOException ioe) {
        log("httpConnector, io problem: ", ioe);
        eRethrow = ioe;
    } catch (KeyStoreException kse) {
        log("httpConnector, keystore problem: ", kse);
        eRethrow = kse;
    } catch (NoSuchAlgorithmException nsae) {
        log("httpConnector, keystore algorithm problem: ", nsae);
        eRethrow = nsae;
    } catch (CertificateException ce) {
        log("httpConnector, certificate problem: ", ce);
        eRethrow = ce;
    } catch (UnrecoverableKeyException uke) {
        log("httpConnector, unrecoverable key: ", uke);
        eRethrow = uke;
    } catch (KeyManagementException kme) {
        log("httpConnector, key management problem: ", kme);
        eRethrow = kme;
    }

    if ( eRethrow != null )
        throw new LifecycleException(threadName + ".open", eRethrow);

}
 
Example 32
Project: NGB-master   File: FeatureIndexManagerTest.java   Source Code and License 5 votes vote down vote up
@Test
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void testIntervalQuery() throws IOException, InterruptedException, FeatureIndexException,
        NoSuchAlgorithmException, VcfReadingException {
    Resource resource = context.getResource(CLASSPATH_TEMPLATES_GENES_SORTED);

    FeatureIndexedFileRegistrationRequest request = new FeatureIndexedFileRegistrationRequest();
    request.setReferenceId(referenceId);
    request.setName("GENES_SORTED_INT");
    request.setPath(resource.getFile().getAbsolutePath());

    GeneFile geneFile = gffManager.registerGeneFile(request);
    Assert.assertNotNull(geneFile);
    Assert.assertNotNull(geneFile.getId());

    referenceGenomeManager.updateReferenceGeneFileId(testReference.getId(), geneFile.getId());

    Project project = new Project();
    project.setName(TEST_PROJECT_NAME + "_INT");

    project.setItems(Arrays.asList(new ProjectItem(new BiologicalDataItem(testReference.getBioDataItemId())),
            new ProjectItem(new BiologicalDataItem(geneFile.getBioDataItemId()))));
    projectManager.saveProject(project);

    IndexSearchResult result1 = featureIndexDao
            .searchFeaturesInInterval(Collections.singletonList(geneFile), INTERVAL1_START, INTERVAL1_END,
                    testChromosome);

    Assert.assertEquals(3, result1.getEntries().size());

    IndexSearchResult result2 = featureIndexDao
            .searchFeaturesInInterval(Collections.singletonList(geneFile), INTERVAL2_START, INTERVAL2_END,
                    testChromosome);
    Assert.assertEquals(0, result2.getEntries().size());

    IndexSearchResult result3 = featureIndexDao
            .searchFeaturesInInterval(Collections.singletonList(geneFile), INTERVAL3_START, INTERVAL3_END,
                    testChromosome);
    Assert.assertEquals(3, result3.getEntries().size());
}
 
Example 33
Project: wolfcrypt-jni   File: WolfCryptMessageDigestSha256Test.java   Source Code and License 5 votes vote down vote up
@Test
public void testSha256Reset()
    throws NoSuchProviderException, NoSuchAlgorithmException {

    String input = "Hello World";
    byte[] inArray = input.getBytes();
    final byte expected[] = new byte[] {
        (byte)0xa5, (byte)0x91, (byte)0xa6, (byte)0xd4,
        (byte)0x0b, (byte)0xf4, (byte)0x20, (byte)0x40,
        (byte)0x4a, (byte)0x01, (byte)0x17, (byte)0x33,
        (byte)0xcf, (byte)0xb7, (byte)0xb1, (byte)0x90,
        (byte)0xd6, (byte)0x2c, (byte)0x65, (byte)0xbf,
        (byte)0x0B, (byte)0xcd, (byte)0xa3, (byte)0x2b,
        (byte)0x57, (byte)0xb2, (byte)0x77, (byte)0xd9,
        (byte)0xad, (byte)0x9f, (byte)0x14, (byte)0x6e
    };

    byte[] output;

    MessageDigest sha256 = MessageDigest.getInstance("SHA-256", "wolfJCE");

    for (int i = 0; i < inArray.length; i++) {
        sha256.update(inArray[i]);
    }

    sha256.reset();

    for (int i = 0; i < inArray.length; i++) {
        sha256.update(inArray[i]);
    }
    output = sha256.digest();
    assertEquals(expected.length, output.length);
    assertArrayEquals(expected, output);
}
 
Example 34
Project: hadoop-oss   File: CachingKeyProvider.java   Source Code and License 5 votes vote down vote up
@Override
public KeyVersion rollNewVersion(String name)
    throws NoSuchAlgorithmException, IOException {
  KeyVersion key = getKeyProvider().rollNewVersion(name);
  getExtension().currentKeyCache.invalidate(name);
  getExtension().keyMetadataCache.invalidate(name);
  return key;
}
 
Example 35
Project: jdk8u-jdk   File: WrongAAD.java   Source Code and License 5 votes vote down vote up
private Cipher createCipher(int mode, AlgorithmParameters params)
        throws NoSuchAlgorithmException, NoSuchProviderException,
        NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException {
    Cipher cipher = Cipher.getInstance(TRANSFORMATION, PROVIDER);
    if (params != null) {
        cipher.init(mode, key, params);
    } else {
        cipher.init(mode, key);
    }
    return cipher;
}
 
Example 36
Project: ipack   File: X509Store.java   Source Code and License 5 votes vote down vote up
public static X509Store getInstance(String type, X509StoreParameters parameters)
    throws NoSuchStoreException
{
    try
    {
        X509Util.Implementation impl = X509Util.getImplementation("X509Store", type);

        return createStore(impl, parameters);
    }
    catch (NoSuchAlgorithmException e)
    {
        throw new NoSuchStoreException(e.getMessage());
    }
}
 
Example 37
Project: XERUNG   File: Comman.java   Source Code and License 5 votes vote down vote up
public String random(int size) {

        StringBuilder generatedToken = new StringBuilder();
        try {
            SecureRandom number = SecureRandom.getInstance("SHA1PRNG");
            // Generate 20 integers 0..20
            for (int i = 0; i < size; i++) {
                generatedToken.append(number.nextInt(9));
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return generatedToken.toString();
    }
 
Example 38
Project: FirefoxData-android   File: SSLSocketFactory.java   Source Code and License 5 votes vote down vote up
public SSLSocketFactory(
        final KeyStore keystore,
        final String keystorePassword)
            throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException{
    this(SSLContexts.custom()
            .loadKeyMaterial(keystore, keystorePassword != null ? keystorePassword.toCharArray() : null)
            .build(),
            BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
}
 
Example 39
Project: Reer   File: HashUtil.java   Source Code and License 5 votes vote down vote up
private static MessageDigest createMessageDigest(String algorithm) {
    try {
        return MessageDigest.getInstance(algorithm);
    } catch (NoSuchAlgorithmException e) {
        throw UncheckedException.throwAsUncheckedException(e);
    }
}
 
Example 40
Project: DecompiledMinecraft   File: CryptManager.java   Source Code and License 5 votes vote down vote up
/**
 * Generate a new shared secret AES key from a secure random source
 */
public static SecretKey createNewSharedKey()
{
    try
    {
        KeyGenerator keygenerator = KeyGenerator.getInstance("AES");
        keygenerator.init(128);
        return keygenerator.generateKey();
    }
    catch (NoSuchAlgorithmException nosuchalgorithmexception)
    {
        throw new Error(nosuchalgorithmexception);
    }
}
 
Example 41
Project: AppCoins-ethereumj   File: ECKeyAgreement.java   Source Code and License 5 votes vote down vote up
public static KeyAgreement getInstance(final String provider) throws NoSuchProviderException {
  try {
    return KeyAgreement.getInstance(ALGORITHM, provider);
  } catch (NoSuchAlgorithmException ex) {
    throw new AssertionError(algorithmAssertionMsg, ex);
  }
}
 
Example 42
Project: skLib   File: ExprSHA256Hash.java   Source Code and License 5 votes vote down vote up
@Override
@Nullable
protected String[] get(Event arg0) {
	String s = string.getSingle(arg0);
	MessageDigest m = null;
	try {
		m = MessageDigest.getInstance("SHA-256");
		m.update(s.getBytes(),0,s.length());
	} catch (NoSuchAlgorithmException e) {
		e.printStackTrace();
	}
	return new String[] {new BigInteger(1,m.digest()).toString(16)};
}
 
Example 43
Project: letv   File: PinningTrustManager.java   Source Code and License 5 votes vote down vote up
private boolean isValidPin(X509Certificate certificate) throws CertificateException {
    try {
        byte[] pin = MessageDigest.getInstance("SHA1").digest(certificate.getPublicKey().getEncoded());
        for (byte[] validPin : this.pins) {
            if (Arrays.equals(validPin, pin)) {
                return true;
            }
        }
        return false;
    } catch (NoSuchAlgorithmException nsae) {
        throw new CertificateException(nsae);
    }
}
 
Example 44
Project: xitk   File: P12ComplexCsrGenCmd.java   Source Code and License 5 votes vote down vote up
public KeyStore getKeyStore()
        throws IOException, KeyStoreException, NoSuchProviderException,
            NoSuchAlgorithmException, CertificateException {
    KeyStore ks;
    try (FileInputStream in = new FileInputStream(expandFilepath(p12File))) {
        ks = KeyUtil.getKeyStore("PKCS12");
        ks.load(in, getPassword());
    }
    return ks;
}
 
Example 45
Project: ideal   File: KeyStoreTarget1.java   Source Code and License 5 votes vote down vote up
public static void main(String... args)
    throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
  KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());

  java.io.FileInputStream fis = null;
  try {
    fis = new java.io.FileInputStream("keyStoreName");
    ks.load(fis, null);
  } finally {
    if (fis != null) {
      fis.close();
    }
  }
}
 
Example 46
Project: citizen-sdk-android   File: CryptoService.java   Source Code and License 5 votes vote down vote up
public Signature initSignature(PrivateKey privateKey) throws CryptoException
{
	Signature signature = null;

	try {
		signature = Signature.getInstance(REST_AUTH_SIGNATURE_ALGORITHM);
		signature.initSign(privateKey);
	} catch (IllegalArgumentException | NoSuchAlgorithmException | InvalidKeyException e) {
           throw new CryptoException(e.getMessage());
	}

	return signature;
}
 
Example 47
Project: toshi-headless-client   File: ECKeyAgreement.java   Source Code and License 5 votes vote down vote up
public static KeyAgreement getInstance(final Provider provider) {
    try {
        return KeyAgreement.getInstance(ALGORITHM, provider);
    } catch (NoSuchAlgorithmException ex) {
        throw new RuntimeException(algorithmAssertionMsg, ex);
    }
}
 
Example 48
Project: messages-java-sdk   File: TestHelper.java   Source Code and License 5 votes vote down vote up
/**
 * Get SHA1 hash of a string
 * @param convertme The string to convert
 * @return SHA1 hash
 */
public static String toSHA1(String convertme) 
{
    byte[] data = convertme.getBytes();
    MessageDigest md = null;
    try {
        md = MessageDigest.getInstance("SHA-1");
    }
    catch(NoSuchAlgorithmException e) {
        e.printStackTrace();
    } 
    return byteArrayToHexString(md.digest(data));
}
 
Example 49
Project: xitk   File: SoftTokenMacContentSignerBuilder.java   Source Code and License 5 votes vote down vote up
public SoftTokenMacContentSignerBuilder(String keystoreType, InputStream keystoreStream,
        char[] keystorePassword, String keyname, char[] keyPassword)
        throws XiSecurityException {
    if (!"JCEKS".equalsIgnoreCase(keystoreType)) {
        throw new IllegalArgumentException("unsupported keystore type: " + keystoreType);
    }
    ParamUtil.requireNonNull("keystoreStream", keystoreStream);
    ParamUtil.requireNonNull("keystorePassword", keystorePassword);
    ParamUtil.requireNonNull("keyPassword", keyPassword);

    try {
        KeyStore ks = KeyUtil.getKeyStore(keystoreType);
        ks.load(keystoreStream, keystorePassword);

        String tmpKeyname = keyname;
        if (tmpKeyname == null) {
            Enumeration<String> aliases = ks.aliases();
            while (aliases.hasMoreElements()) {
                String alias = aliases.nextElement();
                if (ks.isKeyEntry(alias)) {
                    tmpKeyname = alias;
                    break;
                }
            }
        } else {
            if (!ks.isKeyEntry(tmpKeyname)) {
                throw new XiSecurityException("unknown key named " + tmpKeyname);
            }
        }

        this.key = (SecretKey) ks.getKey(tmpKeyname, keyPassword);
    } catch (KeyStoreException | NoSuchProviderException | NoSuchAlgorithmException
            | CertificateException | IOException | UnrecoverableKeyException
            | ClassCastException ex) {
        throw new XiSecurityException(ex.getMessage(), ex);
    }
}
 
Example 50
Project: incubator-netbeans   File: JavaParsingContext.java   Source Code and License 5 votes vote down vote up
@NonNull
public CheckSums getCheckSums() throws IOException {
    if (checkSums == null) {
        try {
            checkSums = CheckSums.forContext(ctx);
        } catch (NoSuchAlgorithmException e) {
            throw new IOException(e);
        }
    }
    return checkSums;
}
 
Example 51
Project: GitHub   File: PubkeyUtilsTest.java   Source Code and License 5 votes vote down vote up
@Test
public void getOidFromPkcs8Encoded_Null_Failure() throws Exception {
	try {
		PubkeyUtils.getOidFromPkcs8Encoded(null);
		fail("Should throw NoSuchAlgorithmException");
	} catch (NoSuchAlgorithmException expected) {
	}
}
 
Example 52
Project: AngularAndSpring   File: PasswordEncryption.java   Source Code and License 5 votes vote down vote up
public String generateSalt() throws NoSuchAlgorithmException {
	// VERY important to use SecureRandom instead of just Random
	SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
	// Generate a 8 byte (64 bit) salt as recommended by RSA PKCS5
	byte[] salt = new byte[8];
	random.nextBytes(salt);
	return Base64.getEncoder().encodeToString(salt);
}
 
Example 53
Project: PACE   File: LocalSignatureKeyContainer.java   Source Code and License 5 votes vote down vote up
/**
 * Create the signature key container that can sign using the given key.
 *
 * @param privateKey
 *          Private key to use for signing.
 * @param signingKeyId
 *          Identifier for the signing key.
 */
private LocalSignatureKeyContainer(PrivateKey privateKey, byte[] signingKeyId) {
  checkArgument(privateKey != null, "private key is null");
  checkArgument(signingKeyId != null, "signingKeyId is null");
  checkArgument(signingKeyId.length != 0, "signingKeyId is empty");

  try {
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
    KeyFactory keyFactory = KeyFactory.getInstance(privateKey.getAlgorithm());
    this.signingKey = new PrivateKeyWithId(keyFactory.generatePrivate(keySpec), signingKeyId.clone());
  } catch (InvalidKeySpecException | NoSuchAlgorithmException e) { // Won't be thrown, as we having a working algorithm and key spec.
    throw new IllegalStateException(e);
  }
}
 
Example 54
Project: Brevent   File: BreventProtocol.java   Source Code and License 5 votes vote down vote up
public static byte[] sha1(byte[] bytes) {
    try {
        MessageDigest md = MessageDigest.getInstance("SHA");
        md.update(bytes);
        return md.digest();
    } catch (NoSuchAlgorithmException e) {
        return null;
    }
}
 
Example 55
Project: JodelAPI   File: JodelHelper.java   Source Code and License 5 votes vote down vote up
protected static String calculateHMAC(String key, String data)
        throws SignatureException, NoSuchAlgorithmException, InvalidKeyException {
    SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1");
    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(signingKey);
    return toHexString(mac.doFinal(data.getBytes())).toUpperCase();
}
 
Example 56
Project: messages-java-sdk   File: BaseController.java   Source Code and License 5 votes vote down vote up
private String getHmacEncodingFor(
   		String signature
) throws 
   		NoSuchAlgorithmException, 
   		InvalidKeyException, UnsupportedEncodingException 
   {
    Mac hasher = Mac.getInstance(HMAC_SHA1_ALGORITHM);
    hasher.init(new SecretKeySpec(Configuration.hmacAuthPassword.getBytes(), HMAC_SHA1_ALGORITHM));

    byte[] hash = hasher.doFinal(signature.getBytes());

    String base64Encoded = Base64.getEncoder().encodeToString(hash);

    return base64Encoded;
     }
 
Example 57
Project: DNASDKJava   File: RestClient.java   Source Code and License 5 votes vote down vote up
public String sendToTrfService(String data) throws RestException {
	try {
		return RestHttp.post(url + Consts.Url_send_to_trfService, data);
	} catch (KeyManagementException | NoSuchAlgorithmException
			| NoSuchProviderException | IOException e) {
		e.printStackTrace();
		throw new RestException("Invalid url:"+e.getMessage());
	}
}
 
Example 58
Project: Gospy   File: HttpFetcher.java   Source Code and License 5 votes vote down vote up
public static HttpFetcher getDefault() {
    HttpFetcher fetcher = new HttpFetcher();
    try {
        fetcher.init();
    } catch (KeyManagementException | NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return fetcher;
}
 
Example 59
Project: dice   File: SecureRandomEntropySource.java   Source Code and License 5 votes vote down vote up
public SecureRandomEntropySource() {
    try {
        this.secureRandom = SecureRandom.getInstanceStrong();
        /*
         * Right after the SecureRandom constructor, perform a single nextBytes with some small numBytes > 0
         * and disregard the result (even though 0 should do if a Vulcan implemented the spec), then setSeed()
         * with whatever unpredictable data at hand, then use nextBytes.
         *
         * https://crypto.stackexchange.com/a/51222/44838
         */
        secureRandom.nextBytes(new byte[4]);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("could not get strong secure random instace", e);
    }
}
 
Example 60
Project: oscm   File: SamlKeyLoaderIT.java   Source Code and License 5 votes vote down vote up
@Test(expected = IOException.class)
public void loadPrivateKeyFromStore_invalidPassword()
        throws CertificateException, SaaSApplicationException,
        UnrecoverableKeyException, NoSuchAlgorithmException, IOException,
        KeyStoreException {
    // given
    String password = "invalidPassword";
    // when
    samlKeyLoader.loadPrivateKeyFromStore(getPath(KEYSTORE_FILE), password,
            ALIAS);
    // then
}