Search in sources :

Example 81 with PBEParameterSpec

use of javax.crypto.spec.PBEParameterSpec in project vcell by virtualcell.

the class VCellApiMain method main.

/**
 * @param args
 */
public static void main(String[] args) {
    try {
        if (args.length != 2) {
            System.out.println("usage: VCellApiMain javascriptDir port");
            System.exit(1);
        }
        File javascriptDir = new File(args[0]);
        if (!javascriptDir.isDirectory()) {
            throw new RuntimeException("javascriptDir '" + args[0] + "' is not a directory");
        }
        // don't validate
        PropertyLoader.loadProperties();
        lg.debug("properties loaded");
        String portString = args[1];
        // was hard-coded at 8080
        Integer port = null;
        try {
            port = Integer.parseInt(portString);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            throw new RuntimeException("failed to parse port argument '" + portString + "'", e);
        }
        lg.trace("connecting to database");
        lg.trace("oracle factory (next)");
        ConnectionFactory conFactory = DatabaseService.getInstance().createConnectionFactory();
        KeyFactory keyFactory = conFactory.getKeyFactory();
        lg.trace("database impl (next)");
        DatabaseServerImpl databaseServerImpl = new DatabaseServerImpl(conFactory, keyFactory);
        lg.trace("local db server (next)");
        LocalAdminDbServer localAdminDbServer = new LocalAdminDbServer(conFactory, keyFactory);
        lg.trace("admin db server (next)");
        AdminDBTopLevel adminDbTopLevel = new AdminDBTopLevel(conFactory);
        lg.trace("messaging service (next)");
        VCMessagingService vcMessagingService = VCellServiceHelper.getInstance().loadService(VCMessagingService.class);
        vcMessagingService.setDelegate(new VCMessagingDelegate() {

            @Override
            public void onTraceEvent(String string) {
                System.out.println("Trace: " + string);
            }

            @Override
            public void onRpcRequestSent(VCRpcRequest vcRpcRequest, UserLoginInfo userLoginInfo, VCMessage vcRpcRequestMessage) {
                System.out.println("request sent:");
            }

            @Override
            public void onRpcRequestProcessed(VCRpcRequest vcRpcRequest, VCMessage rpcVCMessage) {
                System.out.println("request processed:");
            }

            @Override
            public void onMessageSent(VCMessage message, VCDestination desintation) {
                System.out.println("message sent:");
            }

            @Override
            public void onMessageReceived(VCMessage vcMessage, VCDestination vcDestination) {
                System.out.println("message received");
            }

            @Override
            public void onException(Exception e) {
                System.out.println("Exception: " + e.getMessage());
                e.printStackTrace();
            }
        });
        lg.trace("rest database service (next)");
        RestDatabaseService restDatabaseService = new RestDatabaseService(databaseServerImpl, localAdminDbServer, vcMessagingService);
        lg.trace("rest event service (next)");
        RestEventService restEventService = new RestEventService(vcMessagingService);
        lg.trace("use verifier (next)");
        UserVerifier userVerifier = new UserVerifier(adminDbTopLevel);
        lg.trace("mongo (next)");
        VCMongoMessage.enabled = true;
        VCMongoMessage.serviceStartup(ServiceName.unknown, port, args);
        System.out.println("setting up server configuration");
        lg.trace("register engine (next)");
        Engine.register(true);
        WadlComponent component = new WadlComponent();
        // Server httpServer = component.getServers().add(Protocol.HTTP, 80);
        // Server httpsServer = component.getServers().add(Protocol.HTTPS, 443);
        // Client httpsClient = component.getClients().add(Protocol.HTTPS);
        // Client httpClient = component.getClients().add(Protocol.HTTP);
        lg.trace("adding FILE protcol");
        @SuppressWarnings("unused") Client httpClient = component.getClients().add(Protocol.FILE);
        lg.trace("adding CLAP protcol");
        @SuppressWarnings("unused") Client clapClient = component.getClients().add(Protocol.CLAP);
        lg.trace("adding CLAP https");
        File keystorePath = new File(PropertyLoader.getRequiredProperty(PropertyLoader.vcellapiKeystoreFile));
        String keystorePassword = PropertyLoader.getSecretValue(PropertyLoader.vcellapiKeystorePswd, PropertyLoader.vcellapiKeystorePswdFile);
        try {
            // 
            // keystorePassword may be encrypted with dbPassword, if it is decypt it.
            // 
            String dbPassword = PropertyLoader.getSecretValue(PropertyLoader.dbPasswordValue, PropertyLoader.dbPasswordFile);
            SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
            SecretKey key = kf.generateSecret(new PBEKeySpec(dbPassword.toCharArray()));
            Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
            pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(new byte[] { 32, 11, 55, 121, 01, 42, 89, 11 }, 20));
            keystorePassword = new String(pbeCipher.doFinal(DatatypeConverter.parseBase64Binary(keystorePassword)));
        } catch (Exception e) {
            System.out.println("password unhashing didn't work - trying clear text password");
            e.printStackTrace();
        }
        Server httpsServer = component.getServers().add(Protocol.HTTPS, port);
        Series<Parameter> parameters = httpsServer.getContext().getParameters();
        parameters.add("keystorePath", keystorePath.toString());
        parameters.add("keystorePassword", keystorePassword);
        parameters.add("keystoreType", "JKS");
        parameters.add("keyPassword", keystorePassword);
        parameters.add("disabledCipherSuites", "SSL_RSA_WITH_3DES_EDE_CBC_SHA " + "SSL_DHE_RSA_WITH_DES_CBC_SHA " + "SSL_DHE_DSS_WITH_DES_CBC_SHA");
        parameters.add("enabledCipherSuites", "TLS_DHE_DSS_WITH_AES_128_CBC_SHA " + "TLS_DHE_RSA_WITH_AES_128_CBC_SHA " + "TLS_RSA_WITH_AES_128_CBC_SHA " + "TLS_DHE_DSS_WITH_AES_256_CBC_SHA " + "TLS_DHE_RSA_WITH_AES_256_CBC_SHA " + "TLS_RSA_WITH_AES_256_CBC_SHA");
        lg.trace("create config");
        Configuration templateConfiguration = new Configuration();
        templateConfiguration.setObjectWrapper(new DefaultObjectWrapper());
        lg.trace("verify python installation");
        PythonSupport.verifyInstallation(new PythonPackage[] { PythonPackage.COPASI, PythonPackage.LIBSBML, PythonPackage.THRIFT });
        lg.trace("start Optimization Service");
        OptServerImpl optServerImpl = new OptServerImpl();
        optServerImpl.start();
        lg.trace("create app");
        boolean bIgnoreHostProblems = true;
        boolean bIgnoreCertProblems = true;
        User testUser = localAdminDbServer.getUser(TEST_USER);
        // lookup hashed auth credentials in database.
        UserInfo testUserInfo = localAdminDbServer.getUserInfo(testUser.getID());
        HealthService healthService = new HealthService(restEventService, "localhost", port, bIgnoreCertProblems, bIgnoreHostProblems, testUserInfo.userid, testUserInfo.digestedPassword0);
        AdminService adminService = new AdminService(adminDbTopLevel, databaseServerImpl);
        RpcService rpcService = new RpcService(vcMessagingService);
        WadlApplication app = new VCellApiApplication(restDatabaseService, userVerifier, optServerImpl, rpcService, restEventService, adminService, templateConfiguration, healthService, javascriptDir);
        lg.trace("attach app");
        component.getDefaultHost().attach(app);
        System.out.println("component start()");
        lg.trace("start component");
        component.start();
        System.out.println("component ended.");
        lg.trace("component started");
        lg.trace("start VCell Health Monitoring service");
        healthService.start();
    } catch (Exception e) {
        e.printStackTrace(System.out);
    }
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) WadlComponent(org.restlet.ext.wadl.WadlComponent) User(org.vcell.util.document.User) AdminService(org.vcell.rest.admin.AdminService) Server(org.restlet.Server) LocalAdminDbServer(cbit.vcell.modeldb.LocalAdminDbServer) Configuration(freemarker.template.Configuration) VCMessagingDelegate(cbit.vcell.message.VCMessagingDelegate) OptServerImpl(org.vcell.optimization.OptServerImpl) UserInfo(org.vcell.util.document.UserInfo) VCMessagingService(cbit.vcell.message.VCMessagingService) ConnectionFactory(org.vcell.db.ConnectionFactory) VCDestination(cbit.vcell.message.VCDestination) VCMessage(cbit.vcell.message.VCMessage) HealthService(org.vcell.rest.health.HealthService) DatabaseServerImpl(cbit.vcell.modeldb.DatabaseServerImpl) RestDatabaseService(org.vcell.rest.server.RestDatabaseService) Client(org.restlet.Client) SecretKeyFactory(javax.crypto.SecretKeyFactory) SecretKeyFactory(javax.crypto.SecretKeyFactory) KeyFactory(org.vcell.db.KeyFactory) PBEParameterSpec(javax.crypto.spec.PBEParameterSpec) AdminDBTopLevel(cbit.vcell.modeldb.AdminDBTopLevel) DefaultObjectWrapper(freemarker.template.DefaultObjectWrapper) VCRpcRequest(cbit.vcell.message.VCRpcRequest) SecretKey(javax.crypto.SecretKey) RestEventService(org.vcell.rest.events.RestEventService) WadlApplication(org.restlet.ext.wadl.WadlApplication) RpcService(org.vcell.rest.rpc.RpcService) LocalAdminDbServer(cbit.vcell.modeldb.LocalAdminDbServer) Parameter(org.restlet.data.Parameter) Cipher(javax.crypto.Cipher) UserLoginInfo(org.vcell.util.document.UserLoginInfo) File(java.io.File)

Example 82 with PBEParameterSpec

use of javax.crypto.spec.PBEParameterSpec in project freeplane by freeplane.

the class DesEncrypter method init.

/**
 */
private void init(final byte[] salt) {
    if (ecipher != null && mSalt != null && !Arrays.equals(mSalt, salt)) {
        ecipher = null;
        dcipher = null;
    }
    if (salt != null) {
        mSalt = salt;
    }
    if (ecipher == null) {
        try {
            SecretKey key;
            try {
                KeySpec keySpec = new PBEKeySpec(passPhrase, mSalt, iterationCount);
                key = SecretKeyFactory.getInstance(mAlgorithm).generateSecret(keySpec);
            } catch (final java.security.spec.InvalidKeySpecException e) {
                try {
                    passPhrase = URLEncoder.encode(new String(passPhrase), "UTF-8").toCharArray();
                } catch (UnsupportedEncodingException e1) {
                    throw e;
                }
                KeySpec keySpec = new PBEKeySpec(passPhrase, mSalt, iterationCount);
                key = SecretKeyFactory.getInstance(mAlgorithm).generateSecret(keySpec);
            }
            ecipher = Cipher.getInstance(mAlgorithm);
            dcipher = Cipher.getInstance(mAlgorithm);
            final AlgorithmParameterSpec paramSpec = new PBEParameterSpec(mSalt, iterationCount);
            ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
            dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
        } catch (final java.security.InvalidAlgorithmParameterException e) {
            LogUtils.severe(e);
        } catch (final java.security.spec.InvalidKeySpecException e) {
            LogUtils.severe(e);
        } catch (final javax.crypto.NoSuchPaddingException e) {
            LogUtils.severe(e);
        } catch (final java.security.NoSuchAlgorithmException e) {
            LogUtils.severe(e);
        } catch (final java.security.InvalidKeyException e) {
            LogUtils.severe(e);
        }
    }
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) KeySpec(java.security.spec.KeySpec) PBEKeySpec(javax.crypto.spec.PBEKeySpec) UnsupportedEncodingException(java.io.UnsupportedEncodingException) SecretKey(javax.crypto.SecretKey) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec) PBEParameterSpec(javax.crypto.spec.PBEParameterSpec)

Example 83 with PBEParameterSpec

use of javax.crypto.spec.PBEParameterSpec in project BiglyBT by BiglySoftware.

the class CryptoManagerImpl method decryptWithPBE.

protected byte[] decryptWithPBE(byte[] data, char[] password) throws CryptoManagerException {
    boolean fail_is_pw_error = false;
    try {
        byte[] salt = new byte[8];
        System.arraycopy(data, 0, salt, 0, 8);
        PBEKeySpec keySpec = new PBEKeySpec(password);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(PBE_ALG);
        SecretKey key = keyFactory.generateSecret(keySpec);
        PBEParameterSpec paramSpec = new PBEParameterSpec(salt, PBE_ITERATIONS);
        Cipher cipher = Cipher.getInstance(PBE_ALG);
        cipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
        fail_is_pw_error = true;
        return (cipher.doFinal(data, 8, data.length - 8));
    } catch (Throwable e) {
        if (fail_is_pw_error) {
            throw (new CryptoManagerPasswordException(true, "Password incorrect", e));
        } else {
            throw (new CryptoManagerException("PBE decryption failed", e));
        }
    }
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) SecretKey(javax.crypto.SecretKey) Cipher(javax.crypto.Cipher) SecretKeyFactory(javax.crypto.SecretKeyFactory) PBEParameterSpec(javax.crypto.spec.PBEParameterSpec)

Example 84 with PBEParameterSpec

use of javax.crypto.spec.PBEParameterSpec in project xipki by xipki.

the class PasswordBasedEncryption method decrypt.

public static byte[] decrypt(PBEAlgo algo, byte[] cipherTextWithIv, char[] password, int iterationCount, byte[] salt) throws GeneralSecurityException {
    ParamUtil.requireNonNull("cipherTextWithIv", cipherTextWithIv);
    ParamUtil.requireNonNull("password", password);
    ParamUtil.requireMin("iterationCount", iterationCount, 1);
    ParamUtil.requireNonNull("salt", salt);
    PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
    SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algo.algoName());
    SecretKey pbeKey = secretKeyFactory.generateSecret(pbeKeySpec);
    Cipher cipher = Cipher.getInstance(algo.algoName());
    // extract the IV and cipherText
    byte bb = cipherTextWithIv[0];
    int ivLen = (bb < 0) ? 256 + bb : bb;
    PBEParameterSpec pbeParameterSpec;
    if (ivLen == 0) {
        pbeParameterSpec = new PBEParameterSpec(salt, iterationCount);
    } else {
        byte[] iv = new byte[ivLen];
        System.arraycopy(cipherTextWithIv, 1, iv, 0, ivLen);
        pbeParameterSpec = new PBEParameterSpec(salt, iterationCount, new IvParameterSpec(iv));
    }
    int cipherTextOffset = 1 + ivLen;
    byte[] cipherText = new byte[cipherTextWithIv.length - cipherTextOffset];
    System.arraycopy(cipherTextWithIv, 1 + ivLen, cipherText, 0, cipherText.length);
    cipher.init(Cipher.DECRYPT_MODE, pbeKey, pbeParameterSpec);
    return cipher.doFinal(cipherText);
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) SecretKey(javax.crypto.SecretKey) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) SecretKeyFactory(javax.crypto.SecretKeyFactory) PBEParameterSpec(javax.crypto.spec.PBEParameterSpec)

Example 85 with PBEParameterSpec

use of javax.crypto.spec.PBEParameterSpec in project xipki by xipki.

the class PasswordBasedEncryption method encrypt.

/**
 * Encrypts the message using password based encryption.
 * @param algo
 *        the encryption algorithm
 * @param plaintext
 *        the message to be encrypted
 * @param password
 *        the password
 * @param iterationCount
 *        the iteration count
 * @param salt
 *        the salt
 * @return iv and the cipher text in form of
 *         len(iv) of 1 byte | iv of len(iv) bytes | cipher text.
 * @throws GeneralSecurityException
 *         if error occurs.
 */
public static byte[] encrypt(PBEAlgo algo, byte[] plaintext, char[] password, int iterationCount, byte[] salt) throws GeneralSecurityException {
    ParamUtil.requireNonNull("plaintext", plaintext);
    ParamUtil.requireNonNull("password", password);
    ParamUtil.requireMin("iterationCount", iterationCount, 1);
    ParamUtil.requireNonNull("salt", salt);
    SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algo.algoName());
    PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
    SecretKey pbeKey = secretKeyFactory.generateSecret(pbeKeySpec);
    Cipher cipher = Cipher.getInstance(algo.algoName());
    PBEParameterSpec pbeParameterSpec = new PBEParameterSpec(salt, iterationCount);
    cipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParameterSpec);
    pbeKeySpec.clearPassword();
    byte[] iv = cipher.getIV();
    int ivLen = (iv == null) ? 0 : iv.length;
    if (ivLen > 255) {
        throw new GeneralSecurityException("IV too long: " + ivLen);
    }
    byte[] cipherText = cipher.doFinal(plaintext);
    byte[] ret = new byte[1 + ivLen + cipherText.length];
    // length of IV
    ret[0] = (byte) (ivLen & 0xFF);
    if (ivLen > 0) {
        System.arraycopy(iv, 0, ret, 1, ivLen);
    }
    System.arraycopy(cipherText, 0, ret, 1 + ivLen, cipherText.length);
    return ret;
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) SecretKey(javax.crypto.SecretKey) GeneralSecurityException(java.security.GeneralSecurityException) Cipher(javax.crypto.Cipher) SecretKeyFactory(javax.crypto.SecretKeyFactory) PBEParameterSpec(javax.crypto.spec.PBEParameterSpec)

Aggregations

PBEParameterSpec (javax.crypto.spec.PBEParameterSpec)101 SecretKey (javax.crypto.SecretKey)72 Cipher (javax.crypto.Cipher)65 PBEKeySpec (javax.crypto.spec.PBEKeySpec)59 SecretKeyFactory (javax.crypto.SecretKeyFactory)51 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)19 IvParameterSpec (javax.crypto.spec.IvParameterSpec)18 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)17 InvalidKeyException (java.security.InvalidKeyException)17 KeyStoreException (java.security.KeyStoreException)14 UnrecoverableKeyException (java.security.UnrecoverableKeyException)14 CertificateException (java.security.cert.CertificateException)14 AlgorithmParameters (java.security.AlgorithmParameters)12 SecureRandom (java.security.SecureRandom)12 CipherParameters (org.bouncycastle.crypto.CipherParameters)12 KeyParameter (org.bouncycastle.crypto.params.KeyParameter)12 ParametersWithIV (org.bouncycastle.crypto.params.ParametersWithIV)12 IOException (java.io.IOException)11 AlgorithmParameterSpec (java.security.spec.AlgorithmParameterSpec)9 Key (java.security.Key)8