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   View source code 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   View source code 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   View source code 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   View source code 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: Android_Code_Arbiter   File: KeyStoresTrustManager.java   View source code 6 votes vote down vote up
public KeyStoresTrustManager(KeyStore... keyStores) throws NoSuchAlgorithmException, KeyStoreException {
    super();

    for (KeyStore keystore : keyStores) {
        TrustManagerFactory factory = TrustManagerFactory.getInstance("JKS");
        factory.init(keystore);
        TrustManager[] tms = factory.getTrustManagers();
        if (tms.length == 0) {
            throw new NoSuchAlgorithmException("Unable to load keystore");
        }
        trustManagers.add((X509TrustManager) tms[0]);
    }

    //Build accepted issuers list
    Set<X509Certificate> issuers = new HashSet<X509Certificate>();
    for (X509TrustManager tm : trustManagers) {
        for (X509Certificate issuer : tm.getAcceptedIssuers()) {
            issuers.add(issuer);
        }
    }
    acceptedIssuers = issuers.toArray(new X509Certificate[issuers.size()]);
}
 
Example 6
Project: bubble2   File: HttpUtils.java   View source code 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 7
Project: pub-service   File: StringUtil.java   View source code 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 8
Project: xitk   File: DfltConcurrentContentSigner.java   View source code 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 9
Project: springboot-shiro-cas-mybatis   File: DuoWeb.java   View source code 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 10
Project: rapid-io-android   File: SubscriptionDiskCache.java   View source code 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 11
Project: lams   File: Security.java   View source code 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 12
Project: file-transfer   File: HtmlPage.java   View source code 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 13
Project: OpenJSharp   File: URICertStore.java   View source code 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 14
Project: Ships   File: DigitalSignature.java   View source code 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 15
Project: osc-core   File: SslContextProvider.java   View source code 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 16
Project: dhus-core   File: User.java   View source code 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 17
Project: appinventor-extensions   File: PasswordHash.java   View source code 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 18
Project: NoraUi   File: Security.java   View source code 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 19
Project: firebase-admin-java   File: FirebaseTokenVerifierTest.java   View source code 6 votes vote down vote up
private void initCrypto(String privateKey, String certificate)
    throws NoSuchAlgorithmException, InvalidKeySpecException {
  byte[] privateBytes = BaseEncoding.base64().decode(privateKey);
  KeySpec spec = new PKCS8EncodedKeySpec(privateBytes);
  String serviceAccountCertificates =
      String.format("{\"%s\" : \"%s\"}", PRIVATE_KEY_ID, certificate);

  MockHttpTransport mockTransport =
      new MockHttpTransport.Builder()
          .setLowLevelHttpResponse(
              new MockLowLevelHttpResponse().setContent(serviceAccountCertificates))
          .build();
  this.privateKey = KeyFactory.getInstance("RSA").generatePrivate(spec);
  this.verifier =
      new FirebaseTokenVerifier.Builder()
          .setClock(CLOCK)
          .setPublicKeysManager(
              new GooglePublicKeysManager.Builder(mockTransport, FACTORY)
                  .setClock(CLOCK)
                  .setPublicCertsEncodedUrl(FirebaseTokenVerifier.CLIENT_CERT_URL)
                  .build())
          .setProjectId(PROJECT_ID)
          .build();
}
 
Example 20
Project: rongyunDemo   File: MD5.java   View source code 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 21
Project: Cross-Platform-AES   File: CryptLib.java   View source code 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 22
Project: slardar   File: CodecUtils.java   View source code 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 23
Project: paillier   File: PaillierCryptosystemUtil.java   View source code 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 24
Project: lams   File: AdvertiseListener.java   View source code 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 25
Project: encrypt   File: RSAUtil.java   View source code 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 26
Project: AndroidUtilCode-master   File: EncryptUtils.java   View source code 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 27
Project: BTNotifierAndroid   File: SslUtils.java   View source code 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 28
Project: PeSanKita-android   File: MasterSecretUtil.java   View source code 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 29
Project: xmrwallet   File: BitcoinAddressValidator.java   View source code 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 30
Project: mobile-store   File: Hasher.java   View source code 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 31
Project: jdk8u-jdk   File: CipherTestUtils.java   View source code 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 32
Project: openjdk-jdk10   File: CICOSkipTest.java   View source code 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 33
Project: jerrydog   File: HttpConnector.java   View source code 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 34
Project: NGB-master   File: FeatureIndexManagerTest.java   View source code 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 35
Project: wolfcrypt-jni   File: WolfCryptMessageDigestSha256Test.java   View source code 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 36
Project: hadoop-oss   File: CachingKeyProvider.java   View source code 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 37
Project: jdk8u-jdk   File: WrongAAD.java   View source code 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 38
Project: ipack   File: X509Store.java   View source code 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 39
Project: XERUNG   File: Comman.java   View source code 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 40
Project: FirefoxData-android   File: SSLSocketFactory.java   View source code 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);
}