Java Examples for java.security.Security

The following java examples will help you to understand the usage of java.security.Security. These source code samples are taken from different open source projects.

Example 1
Project: cloudstore-master  File: BouncyCastleRegistrationUtil.java View source code
public static synchronized void registerBouncyCastleIfNeeded() {
    Provider provider = Security.getProvider("BC");
    if (provider != null)
        return;
    Security.addProvider(new BouncyCastleProvider());
    provider = Security.getProvider("BC");
    if (provider == null)
        throw new IllegalStateException("Registration of BouncyCastleProvider failed!");
}
Example 2
Project: JTor-master  File: ControlCommandSignal.java View source code
/**
	 * Handles a signal from an incoming control connection
	 * @param in - the signal to be executed
	 * @return true if successful, false if signal not found/supported
	 */
public static boolean handleSignal(ControlConnectionHandler cch, String in) {
    in = in.toLowerCase();
    TorConfig tc = cch.getControlServer().getTorConfig();
    if (in.equals("reload")) {
        if (tc.is__ReloadTorrcOnSIGHUP()) {
            tc.loadDefaults();
            tc.loadConf();
        }
    } else if (in.equals("shutdown")) {
        System.exit(0);
    } else if (in.equals("dump")) {
    // TODO what needs to be dumped here?
    } else if (in.equals("debug")) {
    // TODO we currently have just the debug level
    } else if (in.equals("halt")) {
        System.exit(0);
    } else if (in.equals("cleardnscache")) {
        java.security.Security.setProperty("networkaddress.cache.ttl", "0");
        Thread.yield();
        System.gc();
        java.security.Security.setProperty("networkaddress.cache.ttl", "-1");
    } else if (in.equals("newnym")) {
        java.security.Security.setProperty("networkaddress.cache.ttl", "0");
        Thread.yield();
        System.gc();
        java.security.Security.setProperty("networkaddress.cache.ttl", "-1");
    // TODO make new circuits and new connections must use these circuits
    } else {
        return false;
    }
    return true;
}
Example 3
Project: muCommander-master  File: MuProvider.java View source code
/**
     * Registers an instance of this Provider with the <code>java.security.Security</code> class, to expose the
     * additional <code>MessageDigest</code> implementations and have them returned by
     * <code>java.security.Security.getAlgorithms("MessageDigest")</code>.
     * This method should be called once
     */
public static void registerProvider() {
    // A Provider must be registered only once
    if (initialized)
        return;
    MuProvider provider = new MuProvider();
    // Add our own MessageDigest implementations
    provider.put("MessageDigest." + Adler32MessageDigest.getAlgorithmName(), Adler32MessageDigest.class.getName());
    provider.put("MessageDigest." + CRC32MessageDigest.getAlgorithmName(), CRC32MessageDigest.class.getName());
    // Register the provider with java.security.Security
    Security.addProvider(provider);
    // A Provider must be registered only once
    initialized = true;
}
Example 4
Project: android_libcore-master  File: MessageDigestTestMD2.java View source code
@TestTargetNew(level = TestLevel.ADDITIONAL, method = "getInstance", args = { String.class })
@AndroidOnly("Android allows usage of MD2 in third party providers")
public void testMessageDigest2() throws Exception {
    Provider provider = new MyProvider();
    Security.addProvider(provider);
    try {
        MessageDigest digest = MessageDigest.getInstance("MD2");
        digest = MessageDigest.getInstance("1.2.840.113549.2.2");
    } finally {
        Security.removeProvider(provider.getName());
    }
}
Example 5
Project: cagrid2-master  File: LoadProviders.java View source code
/** Force the CSP loads*/
public static void init() {
    try {
        String cl_name = "COM.claymoresystems.gnp.GoNativeProvider";
        Class clazz;
        clazz = Class.forName(cl_name);
        Provider openssl = (Provider) clazz.newInstance();
        Security.addProvider(openssl);
        hasOpenssl = true;
    } catch (NoClassDefFoundError e) {
        ;
    } catch (Exception e) {
        ;
    }
    Security.addProvider(new cryptix.provider.Cryptix());
    Security.addProvider(new COM.claymoresystems.provider.ClaymoreProvider());
}
Example 6
Project: atlas-lb-master  File: RSAKeyPairGenerator.java View source code
public static void main(String[] args) throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "BC");
    kpg.initialize(1024);
    KeyPair kp = kpg.generateKeyPair();
    if (args.length < 2) {
        System.out.println("RSAKeyPairGenerator [-a] identity passPhrase");
        System.exit(0);
    }
    if (args[0].equals("-a")) {
        if (args.length < 3) {
            System.out.println("RSAKeyPairGenerator [-a] identity passPhrase");
            System.exit(0);
        }
        FileOutputStream out1 = new FileOutputStream("secret.asc");
        FileOutputStream out2 = new FileOutputStream("pub.asc");
        exportKeyPair(out1, out2, kp.getPublic(), kp.getPrivate(), args[1], args[2].toCharArray(), true);
    } else {
        FileOutputStream out1 = new FileOutputStream("secret.bpg");
        FileOutputStream out2 = new FileOutputStream("pub.bpg");
        exportKeyPair(out1, out2, kp.getPublic(), kp.getPrivate(), args[0], args[1].toCharArray(), false);
    }
}
Example 7
Project: irma_future_id-master  File: PubringDump.java View source code
public static void main(String[] args) throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    PGPUtil.setDefaultProvider("BC");
    //
    // Read the public key rings
    //
    PGPPublicKeyRingCollection pubRings = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(new FileInputStream(args[0])));
    Iterator rIt = pubRings.getKeyRings();
    while (rIt.hasNext()) {
        PGPPublicKeyRing pgpPub = (PGPPublicKeyRing) rIt.next();
        try {
            pgpPub.getPublicKey();
        } catch (Exception e) {
            e.printStackTrace();
            continue;
        }
        Iterator it = pgpPub.getPublicKeys();
        boolean first = true;
        while (it.hasNext()) {
            PGPPublicKey pgpKey = (PGPPublicKey) it.next();
            if (first) {
                System.out.println("Key ID: " + Long.toHexString(pgpKey.getKeyID()));
                first = false;
            } else {
                System.out.println("Key ID: " + Long.toHexString(pgpKey.getKeyID()) + " (subkey)");
            }
            System.out.println("            Algorithm: " + getAlgorithm(pgpKey.getAlgorithm()));
            System.out.println("            Fingerprint: " + new String(Hex.encode(pgpKey.getFingerprint())));
        }
    }
}
Example 8
Project: java-csp-master  File: LoadNative.java View source code
public static void loadProvider() {
    CSPNative.init("target/classes/native", "lib/java-csp-platform-amd64-linux.so; osname=Linux; processor=x86-64," + "lib/java-csp-platform-x86-linux.so; osname=Linux; processor=x86," + "lib/java-csp-platform-amd64-windows.dll; osname=Win32; processor=x86-64," + "lib/java-csp-platform-x86-windows.dll; osname=Win32; processor=x86");
    if (Security.getProvider(CSP_PROVIDER) == null)
        Security.addProvider(new CSPProvider());
}
Example 9
Project: bc-java-master  File: SSLUtils.java View source code
public void run() {
    try {
        KeyManagerFactory keyManagerFactory;
        if (Security.getProvider("IBMJSSE2") != null) {
            keyManagerFactory = KeyManagerFactory.getInstance("IBMX509");
        } else {
            keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
        }
        keyManagerFactory.init(keyStore, password);
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("PKIX");
        trustManagerFactory.init(serverStore);
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
        SSLServerSocketFactory sslSocketFactory = context.getServerSocketFactory();
        SSLServerSocket ss = (SSLServerSocket) sslSocketFactory.createServerSocket(port);
        enableAll(ss);
        ss.setNeedClientAuth(needClientAuth);
        latch.countDown();
        SSLSocket s = (SSLSocket) ss.accept();
        s.setUseClientMode(false);
        s.getInputStream().read();
        s.getOutputStream().write('!');
        s.close();
        ss.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 10
Project: oxAuth-master  File: SecurityProviderUtility.java View source code
public static void installBCProvider(boolean silent) {
    Provider provider = Security.getProvider(BouncyCastleProvider.PROVIDER_NAME);
    if (provider == null) {
        if (!silent) {
            log.info("Adding Bouncy Castle Provider");
        }
        Security.addProvider(new BouncyCastleProvider());
    } else {
        if (!silent) {
            log.info("Bouncy Castle Provider was added already");
        }
    }
}
Example 11
Project: uma-master  File: SecurityProviderUtility.java View source code
public static void installBCProvider(boolean silent) {
    Provider provider = Security.getProvider(BouncyCastleProvider.PROVIDER_NAME);
    if (provider == null) {
        if (!silent) {
            log.info("Adding Bouncy Castle Provider");
        }
        Security.addProvider(new BouncyCastleProvider());
    } else {
        if (!silent) {
            log.info("Bouncy Castle Provider was added already");
        }
    }
}
Example 12
Project: AndroidHttpCapture-master  File: NativeCacheManipulatingResolver.java View source code
@Override
public void setPositiveDNSCacheTimeout(int timeout, TimeUnit timeUnit) {
    try {
        Class<?> inetAddressCachePolicyClass = Class.forName("sun.net.InetAddressCachePolicy");
        Field positiveCacheTimeoutSeconds = inetAddressCachePolicyClass.getDeclaredField("cachePolicy");
        positiveCacheTimeoutSeconds.setAccessible(true);
        if (timeout < 0) {
            positiveCacheTimeoutSeconds.setInt(null, -1);
            java.security.Security.setProperty("networkaddress.cache.ttl", "-1");
        } else {
            positiveCacheTimeoutSeconds.setInt(null, (int) TimeUnit.SECONDS.convert(timeout, timeUnit));
            java.security.Security.setProperty("networkaddress.cache.ttl", Long.toString(TimeUnit.SECONDS.convert(timeout, timeUnit)));
        }
    } catch (ClassNotFoundExceptionNoSuchFieldException | IllegalAccessException |  e) {
        log.warn("Unable to modify native JVM DNS cache timeouts", e);
    }
}
Example 13
Project: caelum-stella-master  File: TokenKeyStoreForWindows.java View source code
private void createKeyStore() {
    InputStream configFileStream = this.getClass().getResourceAsStream("/" + configFileName);
    Provider p = new sun.security.pkcs11.SunPKCS11(configFileStream);
    Security.addProvider(p);
    char[] pin = senhaDoCertificado.toCharArray();
    try {
        this.ks = KeyStore.getInstance(algorithm.toString(), p);
        this.ks.load(null, pin);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 14
Project: cryptoapplet-master  File: TestODFSignatureFactory.java View source code
public static void main(String[] args) throws Exception {
    BouncyCastleProvider bcp = new BouncyCastleProvider();
    Security.addProvider(bcp);
    // Cargando certificado de aplicacion
    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(new FileInputStream("../uji.keystore"), "cryptoapplet".toCharArray());
    // Recuperando clave privada para firmar
    X509Certificate certificate = (X509Certificate) keystore.getCertificate(keystore.aliases().nextElement());
    Key key = keystore.getKey("uji", "cryptoapplet".toCharArray());
    SignatureOptions signatureOptions = new SignatureOptions();
    signatureOptions.setDataToSign(new FileInputStream("src/main/resources/original.odt"));
    signatureOptions.setCertificate(certificate);
    signatureOptions.setPrivateKey((PrivateKey) key);
    signatureOptions.setProvider(bcp);
    ODFSignatureFactory odfSignatureFactory = new ODFSignatureFactory();
    SignatureResult signatureResult = odfSignatureFactory.formatSignature(signatureOptions);
    if (signatureResult.isValid()) {
        OS.dumpToFile(new File("src/main/resources/signed-cryptoapplet.odt"), signatureResult.getSignatureData());
        signatureOptions = new SignatureOptions();
        signatureOptions.setDataToSign(new FileInputStream("src/main/resources/signed-cryptoapplet.odt"));
        signatureOptions.setCertificate(certificate);
        signatureOptions.setPrivateKey((PrivateKey) key);
        signatureOptions.setProvider(bcp);
        odfSignatureFactory = new ODFSignatureFactory();
        signatureResult = odfSignatureFactory.formatSignature(signatureOptions);
        if (signatureResult.isValid()) {
            OS.dumpToFile(new File("src/main/resources/signed2-cryptoapplet.odt"), signatureResult.getSignatureData());
        } else {
            for (String error : signatureResult.getErrors()) {
                System.out.println(error);
            }
        }
    } else {
        for (String error : signatureResult.getErrors()) {
            System.out.println(error);
        }
    }
}
Example 15
Project: fast-serialization-master  File: I52.java View source code
@Test
public void test() throws Exception {
    // install BouncyCastle provider
    Security.addProvider(new BouncyCastleProvider());
    // generate a keypair
    KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA", "BC");
    RSAKeyGenParameterSpec params = new RSAKeyGenParameterSpec(STRENGTH, PUBLIC_EXP);
    gen.initialize(params, new SecureRandom());
    KeyPair keyPair = gen.generateKeyPair();
    FSTConfiguration fst = FSTConfiguration.createDefaultConfiguration();
    // serialize
    byte[] serialized = fst.asByteArray(keyPair);
    // deserialize --> crash
    KeyPair deserialized = (KeyPair) fst.asObject(serialized);
}
Example 16
Project: fluxtream-app-master  File: MymeeCryptoTest.java View source code
/**
     * This is testing that we get the correct result as specified by Thomas' email of May 28th '13
     */
@Test
public void testCrypto() throws Exception {
    Security.addProvider(new MymeeCrypto());
    MessageDigest digest;
    try {
        digest = MessageDigest.getInstance("SHA-224", "MymeeCrypto");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        return;
    } catch (NoSuchProviderException e) {
        e.printStackTrace();
        return;
    }
    byte[] result;
    result = digest.digest("flxtest5i88vzf8orqj".getBytes());
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < result.length; i++) sb.append(String.format("%02x", result[i]));
    assertTrue("fbfc986da9dc02cb5f6395d926f349b1674727be2fefda8d6044187d".equals(sb.toString()));
}
Example 17
Project: ontology-master  File: DigestList.java View source code
public static void main(String[] args) {
    Provider[] providers = Security.getProviders();
    for (int i = 0; i < providers.length; i++) {
        System.out.println(providers[i]);
        Set ks = providers[i].keySet();
        for (Iterator j = ks.iterator(); j.hasNext(); ) {
            String s = j.next().toString();
            if (s.contains("MessageDigest")) {
                System.out.println("\t" + s);
            }
        }
    }
}
Example 18
Project: opensc-java-master  File: PKCS11ProviderTestCase.java View source code
public void setUp() throws IOException {
    // Add provider "SunPKCS11-OpenSC"
    String pkcs11_path;
    if (System.getProperty("os.name").contains("Windows"))
        pkcs11_path = System.getenv("ProgramFiles") + "\\Smart Card Bundle\\opensc-pkcs11.dll";
    else
        pkcs11_path = "/usr/lib/opensc-pkcs11.so";
    this.provider = new PKCS11Provider(pkcs11_path);
    Security.addProvider(this.provider);
    Provider providers[] = Security.getProviders();
    for (Provider p : providers) System.out.println("Found provider: " + p.getName());
    this.testData = new byte[199];
    Random random = new Random(System.currentTimeMillis());
    random.nextBytes(this.testData);
}
Example 19
Project: redPandaj-master  File: Stromchiffre.java View source code
public static void main(String[] args) throws Exception {
    //Security.addProvider(new org.spongycastle.jce.provider.BouncyCastleProvider());
    Provider[] providers = Security.getProviders();
    for (int i = 0; i < providers.length; i++) {
        System.out.println("Provider: " + providers[i].toString());
    }
    byte[] input = "input".getBytes();
    byte[] keyBytes = "input123".getBytes();
    SecretKeySpec key = new SecretKeySpec(keyBytes, "ARC4");
    Cipher cipher = Cipher.getInstance("AES", "SC");
    //Cipher cipher = Cipher.getInstance("ARC4");
    byte[] cipherText = new byte[input.length];
    cipher.init(Cipher.ENCRYPT_MODE, key);
    int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
    ctLength += cipher.doFinal(cipherText, ctLength);
    System.out.println("cipher text: " + new String(cipherText));
    byte[] plainText = new byte[ctLength];
    cipher.init(Cipher.DECRYPT_MODE, key);
    int ptLength = cipher.update(cipherText, 0, ctLength, plainText, 0);
    ptLength += cipher.doFinal(plainText, ptLength);
    System.out.println("plain text : " + new String(plainText));
}
Example 20
Project: showmyip-master  File: Core.java View source code
public void disableNetworkCache() {
    Security.setProperty("networkaddress.cache.ttl", "0");
    Security.setProperty("networkaddress.cache.negative.ttl", "0");
//System.setProperty("sun.net.client.defaultConnectTimeout", "2000"); //2 seconds timeout
//System.setProperty("sun.net.client.defaultReadTimeout", "2000"); //2 seconds timeout
}
Example 21
Project: TLS-Attacker-master  File: BleichenbacherAttackPlaintextTest.java View source code
@Test
public final void testBleichenbacherAttack() throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(2048);
    KeyPair keyPair = keyPairGenerator.genKeyPair();
    SecureRandom sr = new SecureRandom();
    byte[] plainBytes = new byte[PREMASTER_SECRET_LENGTH];
    sr.nextBytes(plainBytes);
    byte[] cipherBytes;
    Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding");
    cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
    cipherBytes = cipher.doFinal(plainBytes);
    cipher = Cipher.getInstance("RSA/None/NoPadding");
    cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
    byte[] message = cipher.doFinal(cipherBytes);
    Pkcs1Oracle oracle = new StdPlainPkcs1Oracle(keyPair.getPublic(), TestPkcs1Oracle.OracleType.TTT, cipher.getBlockSize());
    Bleichenbacher attacker = new Bleichenbacher(message, oracle, true);
    attacker.attack();
    BigInteger solution = attacker.getSolution();
    Assert.assertArrayEquals("The computed solution for Bleichenbacher must be equal to the original message", message, solution.toByteArray());
}
Example 22
Project: android-15-master  File: SSLServerSocketFactory.java View source code
/**
     * Returns the default {@code SSLServerSocketFactory} instance. The default
     * implementation is defined by the security property
     * "ssl.ServerSocketFactory.provider".
     *
     * @return the default {@code SSLServerSocketFactory} instance.
     */
public static synchronized ServerSocketFactory getDefault() {
    if (defaultServerSocketFactory != null) {
        return defaultServerSocketFactory;
    }
    if (defaultName == null) {
        defaultName = Security.getProperty("ssl.ServerSocketFactory.provider");
        if (defaultName != null) {
            ClassLoader cl = Thread.currentThread().getContextClassLoader();
            if (cl == null) {
                cl = ClassLoader.getSystemClassLoader();
            }
            try {
                final Class<?> ssfc = Class.forName(defaultName, true, cl);
                defaultServerSocketFactory = (ServerSocketFactory) ssfc.newInstance();
            } catch (Exception e) {
            }
        }
    }
    if (defaultServerSocketFactory == null) {
        SSLContext context;
        try {
            context = SSLContext.getDefault();
        } catch (NoSuchAlgorithmException e) {
            context = null;
        }
        if (context != null) {
            defaultServerSocketFactory = context.getServerSocketFactory();
        }
    }
    if (defaultServerSocketFactory == null) {
        // Use internal dummy implementation
        defaultServerSocketFactory = new DefaultSSLServerSocketFactory("No ServerSocketFactory installed");
    }
    return defaultServerSocketFactory;
}
Example 23
Project: android-libcore64-master  File: MessageDigestTestMD2.java View source code
@AndroidOnly("Android allows usage of MD2 in third party providers")
public void testMessageDigest2() throws Exception {
    Provider provider = new MyProvider();
    Security.addProvider(provider);
    try {
        MessageDigest digest = MessageDigest.getInstance("MD2");
        digest = MessageDigest.getInstance("1.2.840.113549.2.2");
    } finally {
        Security.removeProvider(provider.getName());
    }
}
Example 24
Project: android-sdk-sources-for-api-level-23-master  File: Security2Test.java View source code
/**
     * java.security.Security#getProviders(java.lang.String)
     */
public void test_getProvidersLjava_lang_String() {
    // Test for method void
    // java.security.Security.getProviders(java.lang.String)
    Map<String, Integer> allSupported = new HashMap<String, Integer>();
    Provider[] allProviders = Security.getProviders();
    // Add all non-alias entries to allSupported
    for (Provider provider : allProviders) {
        for (Object k : provider.keySet()) {
            String key = (String) k;
            // No aliases and no provider data
            if (!isAlias(key) && !isProviderData(key)) {
                addOrIncrementTable(allSupported, key);
            }
        }
    // end while more entries
    }
    // entry that is being aliased.
    for (Provider provider : allProviders) {
        for (Map.Entry entry : provider.entrySet()) {
            String key = (String) entry.getKey();
            if (isAlias(key)) {
                String aliasName = key.substring("ALG.ALIAS.".length()).toUpperCase();
                String realName = aliasName.substring(0, aliasName.indexOf(".") + 1) + entry.getValue();
                // aliased are identical. Such entries can occur.
                if (!aliasName.equalsIgnoreCase(realName)) {
                    // Has a real entry been added for aliasName ?
                    if (allSupported.containsKey(aliasName)) {
                        // Add 1 to the provider count of the thing being aliased
                        addOrIncrementTable(allSupported, aliasName);
                    }
                }
            }
        }
    // end while more entries
    }
    for (String filterString : allSupported.keySet()) {
        try {
            Provider[] provTest = Security.getProviders(filterString);
            int expected = allSupported.get(filterString);
            assertEquals("Unexpected number of providers returned for filter " + filterString + ":\n" + allSupported, expected, provTest.length);
        } catch (InvalidParameterException e) {
        }
    }
    // exception
    try {
        Security.getProviders("Signature.SHA1withDSA :512");
        fail("InvalidParameterException should be thrown <Signature.SHA1withDSA :512>");
    } catch (InvalidParameterException e) {
    }
}
Example 25
Project: android_platform_libcore-master  File: MessageDigestTestMD2.java View source code
@AndroidOnly("Android allows usage of MD2 in third party providers")
public void testMessageDigest2() throws Exception {
    Provider provider = new MyProvider();
    Security.addProvider(provider);
    try {
        MessageDigest digest = MessageDigest.getInstance("MD2");
        digest = MessageDigest.getInstance("1.2.840.113549.2.2");
    } finally {
        Security.removeProvider(provider.getName());
    }
}
Example 26
Project: ARTPart-master  File: MessageDigestTestMD2.java View source code
@AndroidOnly("Android allows usage of MD2 in third party providers")
public void testMessageDigest2() throws Exception {
    Provider provider = new MyProvider();
    Security.addProvider(provider);
    try {
        MessageDigest digest = MessageDigest.getInstance("MD2");
        digest = MessageDigest.getInstance("1.2.840.113549.2.2");
    } finally {
        Security.removeProvider(provider.getName());
    }
}
Example 27
Project: property-db-master  File: Security2Test.java View source code
/**
     * java.security.Security#getProviders(java.lang.String)
     */
public void test_getProvidersLjava_lang_String() {
    // Test for method void
    // java.security.Security.getProviders(java.lang.String)
    Map<String, Integer> allSupported = new HashMap<String, Integer>();
    Provider[] allProviders = Security.getProviders();
    // Add all non-alias entries to allSupported
    for (Provider provider : allProviders) {
        for (Object k : provider.keySet()) {
            String key = (String) k;
            // No aliases and no provider data
            if (!isAlias(key) && !isProviderData(key)) {
                addOrIncrementTable(allSupported, key);
            }
        }
    // end while more entries
    }
    // entry that is being aliased.
    for (Provider provider : allProviders) {
        for (Map.Entry entry : provider.entrySet()) {
            String key = (String) entry.getKey();
            if (isAlias(key)) {
                String aliasVal = key.substring("ALG.ALIAS.".length());
                String aliasKey = aliasVal.substring(0, aliasVal.indexOf(".") + 1) + entry.getValue();
                // aliased are identical. Such entries can occur.
                if (!aliasVal.equalsIgnoreCase(aliasKey)) {
                    // Has a real entry been added for aliasValue ?
                    if (allSupported.containsKey(aliasVal.toUpperCase())) {
                        // Add 1 to the provider count of the thing being
                        // aliased
                        addOrIncrementTable(allSupported, aliasKey);
                    }
                }
            }
        }
    // end while more entries
    }
    for (String filterString : allSupported.keySet()) {
        try {
            Provider[] provTest = Security.getProviders(filterString);
            int expected = allSupported.get(filterString);
            assertEquals("Unexpected number of providers returned for filter " + filterString + ":\n" + allSupported, expected, provTest.length);
        } catch (InvalidParameterException e) {
        }
    }
    // exception
    try {
        Security.getProviders("Signature.SHA1withDSA :512");
        fail("InvalidParameterException should be thrown <Signature.SHA1withDSA :512>");
    } catch (InvalidParameterException e) {
    }
}
Example 28
Project: robovm-master  File: Security2Test.java View source code
/**
     * java.security.Security#getProviders(java.lang.String)
     */
public void test_getProvidersLjava_lang_String() {
    // Test for method void
    // java.security.Security.getProviders(java.lang.String)
    Map<String, Integer> allSupported = new HashMap<String, Integer>();
    Provider[] allProviders = Security.getProviders();
    // Add all non-alias entries to allSupported
    for (Provider provider : allProviders) {
        for (Object k : provider.keySet()) {
            String key = (String) k;
            // No aliases and no provider data
            if (!isAlias(key) && !isProviderData(key)) {
                addOrIncrementTable(allSupported, key);
            }
        }
    // end while more entries
    }
    // entry that is being aliased.
    for (Provider provider : allProviders) {
        for (Map.Entry entry : provider.entrySet()) {
            String key = (String) entry.getKey();
            if (isAlias(key)) {
                String aliasName = key.substring("ALG.ALIAS.".length()).toUpperCase();
                String realName = aliasName.substring(0, aliasName.indexOf(".") + 1) + entry.getValue();
                // aliased are identical. Such entries can occur.
                if (!aliasName.equalsIgnoreCase(realName)) {
                    // Has a real entry been added for aliasName ?
                    if (allSupported.containsKey(aliasName)) {
                        // Add 1 to the provider count of the thing being aliased
                        addOrIncrementTable(allSupported, aliasName);
                    }
                }
            }
        }
    // end while more entries
    }
    for (String filterString : allSupported.keySet()) {
        try {
            Provider[] provTest = Security.getProviders(filterString);
            int expected = allSupported.get(filterString);
            assertEquals("Unexpected number of providers returned for filter " + filterString + ":\n" + allSupported, expected, provTest.length);
        } catch (InvalidParameterException e) {
        }
    }
    // exception
    try {
        Security.getProviders("Signature.SHA1withDSA :512");
        fail("InvalidParameterException should be thrown <Signature.SHA1withDSA :512>");
    } catch (InvalidParameterException e) {
    }
}
Example 29
Project: jruby-openssl-master  File: SecurityHelperTest.java View source code
@Test
public void registersSecurityProviderWhenRequested() {
    SecurityHelper.setRegisterProvider(true);
    try {
        SecurityHelper.getSecurityProvider();
        assertNotNull(java.security.Security.getProvider("BC"));
    } finally {
        java.security.Security.removeProvider("BC");
        SecurityHelper.setRegisterProvider(false);
    }
}
Example 30
Project: all-inhonmodman-master  File: Internet.java View source code
public static void main(String[] args) {
    try {
        //System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
        //java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        System.setProperty("javax.net.ssl.trustStore", "C:\\xampp\\apache\\conf\\ssl.key\\server.key");
        System.setProperty("javax.net.ssl.trustStorePassword", "171089");
        URL url = new URL("https://localhost/teso.php");
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        // Retrieve information from HTTPS: GET
        OutputStream os = conn.getOutputStream();
        String data = URLEncoder.encode("ano", "UTF-8") + "=" + URLEncoder.encode("seliga", "UTF-8");
        os.write(data.getBytes());
        os.flush();
        os.close();
        InputStream istream = conn.getInputStream();
        byte[] buff = new byte[1024];
        String s = "";
        while ((istream.read(buff)) > 0) {
            s += s + new String(buff);
        }
        System.out.println(s);
        istream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 31
Project: jgrith-master  File: Environment.java View source code
public static synchronized boolean initEnvironment() {
    if (!environmentInitialized) {
        EnvironmentVariableHelpers.loadEnvironmentVariablesToSystemProperties();
        HttpProxyManager.setDefaultHttpProxy();
        // make sure tmp dir exists
        String tmpdir = System.getProperty("java.io.tmpdir");
        if (tmpdir.startsWith("~")) {
            tmpdir = tmpdir.replaceFirst("~", System.getProperty("user.home"));
            System.setProperty("java.io.tmpdir", tmpdir);
        }
        File tmp = new File(tmpdir);
        if (!tmp.exists()) {
            myLogger.debug("Creating tmpdir: {}", tmpdir);
            tmp.mkdirs();
            if (!tmp.exists()) {
                myLogger.error("Could not create tmp dir {}.", tmpdir);
            }
        }
        java.util.logging.LogManager.getLogManager().reset();
        // LoggerFactory.getLogger("root").setLevel(Level.OFF);
        JythonHelpers.setJythonCachedir();
        final String debug = CommonGridProperties.getDefault().getGridProperty(CommonGridProperties.Property.DEBUG_UNCAUGHT_EXCEPTIONS);
        if ("true".equalsIgnoreCase(debug)) {
            Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler());
        }
        java.security.Security.addProvider(new DefaultGridSecurityProvider());
        java.security.Security.setProperty("ssl.TrustManagerFactory.algorithm", "TrustAllCertificates");
        try {
            BouncyCastleTool.initBouncyCastle();
        } catch (final Exception e) {
            myLogger.error(e.getLocalizedMessage(), e);
        }
        environmentInitialized = true;
        try {
            CertificateFiles.copyCACerts(false);
        } catch (Exception e) {
            myLogger.error("Problem copying root certificates.", e);
        }
        return true;
    } else {
        return false;
    }
}
Example 32
Project: openjdk-master  File: ProviderVersionCheck.java View source code
public static void main(String arg[]) throws Exception {
    boolean failure = false;
    for (Provider p : Security.getProviders()) {
        System.out.print(p.getName() + " ");
        if (p.getVersion() != 9.0d) {
            System.out.println("failed. " + "Version received was " + p.getVersion());
            failure = true;
        } else {
            System.out.println("passed.");
        }
    }
    if (failure) {
        throw new Exception("Provider(s) failed to have the expected " + "version value.");
    }
}
Example 33
Project: AcademicTorrents-Downloader-master  File: StaticSnark.java View source code
public static void main(String[] args) {
    try {
        // The GNU security provider is needed for SHA-1 MessageDigest
        // checking. So make sure it is available as a security provider.
        Provider gnu = (Provider) Class.forName("gnu.java.security.provider.Gnu").newInstance();
        Security.addProvider(gnu);
    } catch (Exception e) {
        System.err.println("Unable to load GNU security provider");
        System.exit(-1);
    }
    // And finally call the normal starting point.
    SnarkApplication.main(args);
}
Example 34
Project: android-backup-extractor-master  File: Main.java View source code
public static void main(String[] args) {
    Security.addProvider(new BouncyCastleProvider());
    if (args.length < 3) {
        usage();
        System.exit(1);
    }
    String mode = args[0];
    if (!"pack".equals(mode) && !"unpack".equals(mode) && !"pack-kk".equals(mode)) {
        usage();
        System.exit(1);
    }
    boolean unpack = "unpack".equals(mode);
    String backupFilename = unpack ? args[1] : args[2];
    String tarFilename = unpack ? args[2] : args[1];
    String password = null;
    if (args.length > 3) {
        password = args[3];
    }
    if (password == null) {
        /* if password is not given, try to read it from environment */
        password = System.getenv("ABE_PASSWD");
    }
    if (unpack) {
        AndroidBackup.extractAsTar(backupFilename, tarFilename, password);
    } else {
        boolean isKitKat = "pack-kk".equals(mode);
        AndroidBackup.packTar(tarFilename, backupFilename, password, isKitKat);
    }
}
Example 35
Project: android_frameworks_base-master  File: NetworkSecurityConfigProvider.java View source code
public static void install(Context context) {
    ApplicationConfig config = new ApplicationConfig(new ManifestConfigSource(context));
    ApplicationConfig.setDefaultInstance(config);
    int pos = Security.insertProviderAt(new NetworkSecurityConfigProvider(), 1);
    if (pos != 1) {
        throw new RuntimeException("Failed to install provider as highest priority provider." + " Provider was installed at position " + pos);
    }
    libcore.net.NetworkSecurityPolicy.setInstance(new ConfigNetworkSecurityPolicy(config));
}
Example 36
Project: AppWorkUtils-master  File: TrustProvider.java View source code
/**
     * Registers the Trustprovider
     */
public static void register() {
    if (Security.getProvider(PROVIDER_NAME) == null) {
        // saves old status to be able to restore it
        Security.insertProviderAt(new TrustProvider(), 2);
        origAlgorithm = System.getProperty("ssl.TrustManagerFactory.algorithm");
        Security.setProperty("ssl.TrustManagerFactory.algorithm", CryptServiceProvider.getAlgorithm());
    }
}
Example 37
Project: awsbigdata-master  File: Simulator.java View source code
public static void main(String[] args) throws SQLException {
    java.security.Security.setProperty("networkaddress.cache.ttl", "60");
    query = System.getProperty("kinesisapp.query");
    conn = DriverManager.getConnection(System.getProperty("kinesisapp.jdbcurl"), System.getProperty("kinesisapp.dbuser"), System.getProperty("kinesisapp.dbpassword"));
    conn.setAutoCommit(true);
    AmazonKinesisClient client = new AmazonKinesisClient();
    client.setEndpoint("https://kinesis.us-east-1.amazonaws.com");
    String stream = "test";
    int iteration = 100;
    int threashold = 1000;
    String data = new String("{\"user\":\"10125\",\"line\":\"aaa\",\"station\":\"bbb\",\"latitude\":35.");
    Random rand = new Random();
    try {
        long start = System.currentTimeMillis();
        String myKey = Long.toString(Thread.currentThread().getId());
        for (int i = 0; i < iteration; i++) {
            try {
                PutRecordRequest putRecordRequest = new PutRecordRequest();
                putRecordRequest.setStreamName(stream);
                putRecordRequest.setData(ByteBuffer.wrap((data + Integer.toString(rand.nextInt(19) + 52) + ",\"longitude\":139." + Integer.toString(rand.nextInt(39) + 51) + "}").getBytes()));
                putRecordRequest.setPartitionKey(myKey);
                PutRecordResult putRecordResult = client.putRecord(putRecordRequest);
            } catch (Exception iex) {
            }
        }
        System.out.println("Elapsed time(ms) for task " + Thread.currentThread().getId() + " : " + (System.currentTimeMillis() - start));
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
Example 38
Project: born-again-snark-master  File: StaticSnark.java View source code
public static void main(String[] args) {
    try {
        // The GNU security provider is needed for SHA-1 MessageDigest
        // checking. So make sure it is available as a security provider.
        Provider gnu = (Provider) Class.forName("gnu.java.security.provider.Gnu").newInstance();
        Security.addProvider(gnu);
    } catch (Exception e) {
        System.err.println("Unable to load GNU security provider");
        System.exit(-1);
    }
    // And finally call the normal starting point.
    SnarkApplication.main(args);
}
Example 39
Project: btpka3.github.com-master  File: DESTest.java View source code
public static void main(String[] args) throws InterruptedException, UnsupportedEncodingException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
    // 请注�����加入
    Security.addProvider(new BouncyCastleProvider());
    // 生��机秘钥
    KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
    SecretKey desKey = keygenerator.generateKey();
    // 生�加密器
    Cipher cipher = Cipher.getInstance("DES/ECB/PKCS7Padding");
    cipher.init(Cipher.ENCRYPT_MODE, desKey);
    // 准备明文数�
    String txt = "Hello World~";
    // 加密
    byte[] encData = cipher.doFinal(txt.getBytes("UTF-8"));
    System.out.println("ENC DATA : " + DatatypeConverter.printHexBinary(encData));
    // 解密
    cipher.init(Cipher.DECRYPT_MODE, desKey);
    byte[] decData = cipher.doFinal(encData);
    System.out.println("DEC DATA : " + new String(decData, "UTF-8"));
}
Example 40
Project: BungeeCord-master  File: BungeeCordLauncher.java View source code
public static void main(String[] args) throws Exception {
    Security.setProperty("networkaddress.cache.ttl", "30");
    Security.setProperty("networkaddress.cache.negative.ttl", "10");
    OptionParser parser = new OptionParser();
    parser.allowsUnrecognizedOptions();
    parser.acceptsAll(Arrays.asList("v", "version"));
    parser.acceptsAll(Arrays.asList("noconsole"));
    OptionSet options = parser.parse(args);
    if (options.has("version")) {
        System.out.println(Bootstrap.class.getPackage().getImplementationVersion());
        return;
    }
    if (BungeeCord.class.getPackage().getSpecificationVersion() != null && System.getProperty("IReallyKnowWhatIAmDoingISwear") == null) {
        Date buildDate = new SimpleDateFormat("yyyyMMdd").parse(BungeeCord.class.getPackage().getSpecificationVersion());
        Calendar deadline = Calendar.getInstance();
        deadline.add(Calendar.WEEK_OF_YEAR, -4);
        if (buildDate.before(deadline.getTime())) {
            System.err.println("*** Warning, this build is outdated ***");
            System.err.println("*** Please download a new build from http://ci.md-5.net/job/BungeeCord ***");
            System.err.println("*** You will get NO support regarding this build ***");
            System.err.println("*** Server will start in 10 seconds ***");
            Thread.sleep(TimeUnit.SECONDS.toMillis(10));
        }
    }
    BungeeCord bungee = new BungeeCord();
    ProxyServer.setInstance(bungee);
    bungee.getLogger().info("Enabled BungeeCord version " + bungee.getVersion());
    bungee.start();
    if (!options.has("noconsole")) {
        String line;
        while (bungee.isRunning && (line = bungee.getConsoleReader().readLine(">")) != null) {
            if (!bungee.getPluginManager().dispatchCommand(ConsoleCommandSender.getInstance(), line)) {
                bungee.getConsole().sendMessage(ChatColor.RED + "Command not found");
            }
        }
    }
}
Example 41
Project: cpush-apns-master  File: SecureSslContextFactory.java View source code
public static SSLContext getSSLContext(Credentials conf) {
    SSLContext clientContext = CLIENT_CONTEXT.get(conf);
    if (clientContext == null) {
        try {
            String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
            if (algorithm == null) {
                algorithm = "SunX509";
            }
            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            keyStore.load(new ByteArrayInputStream(conf.getCertification()), conf.getPassword().toCharArray());
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
            kmf.init(keyStore, conf.getPassword().toCharArray());
            clientContext = SSLContext.getInstance(PROTOCOL);
            clientContext.init(kmf.getKeyManagers(), new TrustManager[] { new X509TrustManager() {

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }

                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    throw new CertificateException("Client is not trusted.");
                }
            } }, null);
            CLIENT_CONTEXT.putIfAbsent(conf, clientContext);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return clientContext;
}
Example 42
Project: jdk7u-jdk-master  File: SecurityManagerClinit.java View source code
public static void main(String[] args) throws Throwable {
    String javaExe = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
    // A funky contrived security setup, just for bug repro purposes.
    java.security.Security.setProperty("package.access", "java.util");
    final Policy policy = new Policy(new FilePermission("<<ALL FILES>>", "execute"), new RuntimePermission("setSecurityManager"));
    Policy.setPolicy(policy);
    System.setSecurityManager(new SecurityManager());
    try {
        String[] cmd = { javaExe, "-version" };
        Process p = Runtime.getRuntime().exec(cmd);
        p.getOutputStream().close();
        p.getInputStream().close();
        p.getErrorStream().close();
        p.waitFor();
    } finally {
        System.setSecurityManager(null);
    }
}
Example 43
Project: jjwt-master  File: RuntimeEnvironment.java View source code
public static void enableBouncyCastleIfPossible() {
    if (bcLoaded.get()) {
        return;
    }
    try {
        Class clazz = Classes.forName(BC_PROVIDER_CLASS_NAME);
        //check to see if the user has already registered the BC provider:
        Provider[] providers = Security.getProviders();
        for (Provider provider : providers) {
            if (clazz.isInstance(provider)) {
                bcLoaded.set(true);
                return;
            }
        }
        //bc provider not enabled - add it:
        Security.addProvider((Provider) Classes.newInstance(clazz));
        bcLoaded.set(true);
    } catch (UnknownClassException e) {
    }
}
Example 44
Project: jmulticard-master  File: TestDoubleSign.java View source code
static void testDoubleSign() throws Exception {
    final Provider p = new DnieProvider(new SmartcardIoConnection());
    Security.addProvider(p);
    //$NON-NLS-1$
    final KeyStore ks = KeyStore.getInstance("DNI");
    ks.load(null, PASSWORD);
    final Enumeration<String> aliases = ks.aliases();
    while (aliases.hasMoreElements()) {
        System.out.println(aliases.nextElement());
    }
    //$NON-NLS-1$
    Signature signature = Signature.getInstance("SHA1withRSA");
    //$NON-NLS-1$
    signature.initSign((PrivateKey) ks.getKey("CertFirmaDigital", PASSWORD));
    //$NON-NLS-1$
    signature.update("Hola Mundo!!".getBytes());
    signature.sign();
    //$NON-NLS-1$
    System.out.println("Primera firma generada correctamente");
    //$NON-NLS-1$
    signature = Signature.getInstance("SHA1withRSA");
    //$NON-NLS-1$
    signature.initSign((PrivateKey) ks.getKey("CertFirmaDigital", PASSWORD));
    //$NON-NLS-1$
    signature.update("Hola Mundo 2!!".getBytes());
    signature.sign();
    //$NON-NLS-1$
    System.out.println("Segunda firma generada correctamente");
}
Example 45
Project: jnode-master  File: TestSecurityManager.java View source code
public static void main(String args[]) throws Exception {
    Class sc = SecurityManager.class;
    Class sc2 = Security.class;
    Class sc3 = java.security.Permission.class;
    Class sc4 = java.lang.StringBuffer.class;
    Class sc5 = java.io.PrintStream.class;
    System.setSecurityManager(new MySM());
    URLClassLoader cl = (URLClassLoader) TestSecurityManager.class.getClassLoader();
    URLClassLoader cl2 = new URLClassLoader(cl.getURLs());
    Class c = Class.forName("org.jnode.test.security.TestSecurityManager$mytest", true, cl2);
    c.newInstance();
}
Example 46
Project: keywhiz-master  File: CryptoFixtures.java View source code
/** @return a content cryptographer initialized with the testing derivation key. */
public static ContentCryptographer contentCryptographer() {
    if (cryptographer != null) {
        return cryptographer;
    }
    Provider provider = new BouncyCastleProvider();
    if (Security.getProvider(provider.getName()) == null) {
        Security.addProvider(provider);
    }
    SecretKey baseKey;
    char[] password = "CHANGE".toCharArray();
    try (InputStream in = Resources.getResource("derivation.jceks").openStream()) {
        KeyStore keyStore = KeyStore.getInstance("JCEKS");
        keyStore.load(in, password);
        baseKey = (SecretKey) keyStore.getKey("basekey", password);
    } catch (CertificateExceptionUnrecoverableKeyException | KeyStoreException | NoSuchAlgorithmException | IOException |  e) {
        throw Throwables.propagate(e);
    }
    cryptographer = new ContentCryptographer(baseKey, provider, provider, FakeRandom.create());
    return cryptographer;
}
Example 47
Project: ManagedRuntimeInitiative-master  File: TestPremaster.java View source code
public static void main(String[] args) throws Exception {
    Provider provider = Security.getProvider("SunJCE");
    KeyGenerator kg;
    kg = KeyGenerator.getInstance("SunTlsRsaPremasterSecret", provider);
    try {
        kg.generateKey();
        throw new Exception("no exception");
    } catch (IllegalStateException e) {
        System.out.println("OK: " + e);
    }
    test(kg, 3, 0);
    test(kg, 3, 1);
    test(kg, 3, 2);
    test(kg, 4, 0);
    System.out.println("Done.");
}
Example 48
Project: Network-Fundies-p3-master  File: StaticSnark.java View source code
public static void main(String[] args) {
    //        try {
    // The GNU security provider is needed for SHA-1 MessageDigest
    // checking. So make sure it is available as a security provider.
    //            Provider gnu = (Provider)Class.forName(
    //                "gnu.java.security.provider.Gnu").newInstance();
    //            Security.addProvider(gnu);
    //        } catch (Exception e) {
    //            System.err.println("Unable to load GNU security provider");
    //            System.exit(-1);
    //        }
    // And finally call the normal starting point.
    SnarkApplication.main(args);
}
Example 49
Project: OpenIDM-master  File: Activator.java View source code
@Override
public void start(BundleContext bundleContext) throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    // Set System properties
    if (System.getProperty("javax.net.ssl.keyStore") == null) {
        System.setProperty("javax.net.ssl.keyStore", Param.getKeystoreLocation());
        System.setProperty("javax.net.ssl.keyStorePassword", Param.getKeystorePassword(false));
        System.setProperty("javax.net.ssl.keyStoreType", Param.getKeystoreType());
    }
    if (System.getProperty("javax.net.ssl.trustStore") == null) {
        System.setProperty("javax.net.ssl.trustStore", Param.getTruststoreLocation());
        System.setProperty("javax.net.ssl.trustStorePassword", Param.getTruststorePassword(false));
        System.setProperty("javax.net.ssl.trustStoreType", Param.getTruststoreType());
    }
}
Example 50
Project: openjdk8-jdk-master  File: BadKdc4.java View source code
public static void main(String[] args) throws Exception {
    Security.setProperty("krb5.kdc.bad.policy", "");
    BadKdc.go("121212222222(32){1,2}121212222222(32){1,2}", "121212222222(32){1,2}121212222222(32){1,2}", // refresh
    "121212222222(32){1,2}121212222222(32){1,2}", // k3 off k2 on
    "121212(22){1,2}121212(22){1,2}", // k1 on
    "(12){2,4}");
}
Example 51
Project: oxalis-master  File: BCHelperTest.java View source code
@Test
public void simpleRegisterProvider() {
    if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) != null)
        Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
    Assert.assertNull(Security.getProvider(BouncyCastleProvider.PROVIDER_NAME));
    BCHelper.registerProvider();
    Provider provider = Security.getProvider(BouncyCastleProvider.PROVIDER_NAME);
    Assert.assertNotNull(provider);
    BCHelper.registerProvider();
    Assert.assertTrue(provider == Security.getProvider(BouncyCastleProvider.PROVIDER_NAME));
}
Example 52
Project: PF-CORE-master  File: TestDynDnsResolve.java View source code
public static void main(String[] args) throws InterruptedException {
    Security.setProperty("networkaddress.cache.ttl", "0");
    Security.setProperty("networkaddress.cache.ttl", "0");
    Security.setProperty("networkaddress.cache.negative.ttl", "0");
    System.setProperty("sun.net.inetaddr.ttl", "0");
    System.out.println("Cache is confirmed: " + Security.getProperty("networkaddress.cache.ttl"));
    for (int i = 0; i < 25000; i++) {
        try {
            System.out.println(Format.formatDateShort(new Date()) + ": " + InetAddress.getByName("tot-notebook.dyndns.org").getHostAddress());
        } catch (UnknownHostException uhe) {
            System.out.println("UHE");
        }
        Thread.sleep(1000);
    }
}
Example 53
Project: picketbox-keystore-master  File: SecurityActions.java View source code
static void addProvider(final Provider provider) {
    if (System.getSecurityManager() == null) {
        Security.addProvider(provider);
    } else {
        AccessController.doPrivileged(new PrivilegedAction<Void>() {

            @Override
            public Void run() {
                Security.addProvider(provider);
                return null;
            }
        });
    }
}
Example 54
Project: platform_frameworks_base-master  File: NetworkSecurityConfigProvider.java View source code
public static void install(Context context) {
    ApplicationConfig config = new ApplicationConfig(new ManifestConfigSource(context));
    ApplicationConfig.setDefaultInstance(config);
    int pos = Security.insertProviderAt(new NetworkSecurityConfigProvider(), 1);
    if (pos != 1) {
        throw new RuntimeException("Failed to install provider as highest priority provider." + " Provider was installed at position " + pos);
    }
    libcore.net.NetworkSecurityPolicy.setInstance(new ConfigNetworkSecurityPolicy(config));
}
Example 55
Project: pro-grade-master  File: SecurityActions.java View source code
/**
     * Returns a security property value using the specified <code>key</code>.
     * 
     * @param key
     * @see Security#getProperty(String)
     * @return
     */
static String getSecurityProperty(final String key) {
    final SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        return AccessController.doPrivileged(new PrivilegedAction<String>() {

            public String run() {
                return Security.getProperty(key);
            }
        });
    } else {
        return Security.getProperty(key);
    }
}
Example 56
Project: SAMLRaider-master  File: CloneCertificateChainTest.java View source code
@Before
public void setUp() throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    certificateTabController = new CertificateTabController(new CertificateTab());
    certificateChain = certificateTabController.importCertificateChain("src/test/resources/hsr_chain.pem");
    clonedCertificates = certificateTabController.cloneCertificateChain(certificateChain);
}
Example 57
Project: ssl_npn-master  File: DefaultSSLServSocketFac.java View source code
public static void main(String[] args) throws Exception {
    try {
        Security.setProperty("ssl.ServerSocketFactory.provider", "oops");
        ServerSocketFactory ssocketFactory = SSLServerSocketFactory.getDefault();
        SSLServerSocket sslServerSocket = (SSLServerSocket) ssocketFactory.createServerSocket();
    } catch (Exception e) {
        if (!(e.getCause() instanceof ClassNotFoundException)) {
            throw e;
        }
    }
}
Example 58
Project: syncany-master  File: ListAvailableCryptoPropertiesTest.java View source code
@Test
public void listCryptoSettingsAvailable() {
    logger.log(Level.INFO, "Listing security providers and properties:");
    for (Provider provider : Security.getProviders()) {
        logger.log(Level.INFO, "- Provider '" + provider.getName() + "' ");
        List<String> propertyNames = new ArrayList<String>();
        propertyNames.addAll(provider.stringPropertyNames());
        Collections.sort(propertyNames);
        for (String key : propertyNames) {
            logger.log(Level.INFO, "   " + provider.getName() + " / " + key + " = " + provider.getProperty(key));
        }
    }
}
Example 59
Project: syncany-plugin-dropbox-master  File: ListAvailableCryptoPropertiesTest.java View source code
@Test
public void listCryptoSettingsAvailable() {
    logger.log(Level.INFO, "Listing security providers and properties:");
    for (Provider provider : Security.getProviders()) {
        logger.log(Level.INFO, "- Provider '" + provider.getName() + "' ");
        List<String> propertyNames = new ArrayList<String>();
        propertyNames.addAll(provider.stringPropertyNames());
        Collections.sort(propertyNames);
        for (String key : propertyNames) {
            logger.log(Level.INFO, "   " + provider.getName() + " / " + key + " = " + provider.getProperty(key));
        }
    }
}
Example 60
Project: syncany-plugin-flickr-master  File: ListAvailableCryptoPropertiesTest.java View source code
@Test
public void listCryptoSettingsAvailable() {
    logger.log(Level.INFO, "Listing security providers and properties:");
    for (Provider provider : Security.getProviders()) {
        logger.log(Level.INFO, "- Provider '" + provider.getName() + "' ");
        List<String> propertyNames = new ArrayList<String>();
        propertyNames.addAll(provider.stringPropertyNames());
        Collections.sort(propertyNames);
        for (String key : propertyNames) {
            logger.log(Level.INFO, "   " + provider.getName() + " / " + key + " = " + provider.getProperty(key));
        }
    }
}
Example 61
Project: syncany-plugin-gui-master  File: ListAvailableCryptoPropertiesTest.java View source code
@Test
public void listCryptoSettingsAvailable() {
    logger.log(Level.INFO, "Listing security providers and properties:");
    for (Provider provider : Security.getProviders()) {
        logger.log(Level.INFO, "- Provider '" + provider.getName() + "' ");
        List<String> propertyNames = new ArrayList<String>();
        propertyNames.addAll(provider.stringPropertyNames());
        Collections.sort(propertyNames);
        for (String key : propertyNames) {
            logger.log(Level.INFO, "   " + provider.getName() + " / " + key + " = " + provider.getProperty(key));
        }
    }
}
Example 62
Project: syncany-plugin-s3-master  File: ListAvailableCryptoPropertiesTest.java View source code
@Test
public void listCryptoSettingsAvailable() {
    logger.log(Level.INFO, "Listing security providers and properties:");
    for (Provider provider : Security.getProviders()) {
        logger.log(Level.INFO, "- Provider '" + provider.getName() + "' ");
        List<String> propertyNames = new ArrayList<String>();
        propertyNames.addAll(provider.stringPropertyNames());
        Collections.sort(propertyNames);
        for (String key : propertyNames) {
            logger.log(Level.INFO, "   " + provider.getName() + " / " + key + " = " + provider.getProperty(key));
        }
    }
}
Example 63
Project: syncany-plugin-sftp-master  File: ListAvailableCryptoPropertiesTest.java View source code
@Test
public void listCryptoSettingsAvailable() {
    logger.log(Level.INFO, "Listing security providers and properties:");
    for (Provider provider : Security.getProviders()) {
        logger.log(Level.INFO, "- Provider '" + provider.getName() + "' ");
        List<String> propertyNames = new ArrayList<String>();
        propertyNames.addAll(provider.stringPropertyNames());
        Collections.sort(propertyNames);
        for (String key : propertyNames) {
            logger.log(Level.INFO, "   " + provider.getName() + " / " + key + " = " + provider.getProperty(key));
        }
    }
}
Example 64
Project: thundernetwork-master  File: ECDH.java View source code
/*
     * Quite some mess here to have all objects with the correct types...
     */
public static ECDHKeySet getSharedSecret(ECKey keyServer, ECKey keyClient) {
    try {
        Security.addProvider(new BouncyCastleProvider());
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC", "SunEC");
        parameters.init(new ECGenParameterSpec("secp256k1"));
        ECParameterSpec ecParameters = parameters.getParameterSpec(ECParameterSpec.class);
        ECPrivateKeySpec specPrivate = new ECPrivateKeySpec(keyServer.getPrivKey(), ecParameters);
        ECPublicKeySpec specPublic = new ECPublicKeySpec(new ECPoint(keyClient.getPubKeyPoint().getXCoord().toBigInteger(), keyClient.getPubKeyPoint().getYCoord().toBigInteger()), ecParameters);
        KeyFactory kf = KeyFactory.getInstance("EC");
        ECPrivateKey privateKey = (ECPrivateKey) kf.generatePrivate(specPrivate);
        ECPublicKey publicKey = (ECPublicKey) kf.generatePublic(specPublic);
        JCEECPrivateKey ecPrivKey = new JCEECPrivateKey(privateKey);
        JCEECPublicKey ecPubKey = new JCEECPublicKey(publicKey);
        new ECKey().getKeyCrypter();
        KeyAgreement aKeyAgree = KeyAgreement.getInstance("ECDH");
        aKeyAgree.init(ecPrivKey);
        aKeyAgree.doPhase(ecPubKey, true);
        return new ECDHKeySet(aKeyAgree.generateSecret(), keyServer.getPubKey(), keyClient.getPubKey());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
//		MessageDigest hash = MessageDigest.getInstance("SHA1", "BC");
//
//		return hash.digest();
}
Example 65
Project: uprove-master  File: ConfigImplTest.java View source code
public final void testNoSecurityPermissions() {
    // what if we don't have perms to look into Security properties?
    // first, prepare by setting odd values for things
    Security.setProperty("com.microsoft.uprove.securerandom.algorithm", "one");
    Security.setProperty("com.microsoft.uprove.securerandom.provider", "two");
    Security.setProperty("com.microsoft.uprove.messagedigest.provider", "three");
    Security.setProperty("com.microsoft.uprove.math.primeconfidencelevel", "22");
    // next, reset all config options
    ConfigImpl.setSecureRandomAlgorithm(null);
    ConfigImpl.setSecureRandomProvider(null);
    ConfigImpl.setMessageDigestProvider(null);
    ConfigImpl.setPrimeConfidenceLevel(0);
    // now make sure we get those odd values when we ask
    assertEquals("one", ConfigImpl.secureRandomAlgorithm());
    assertEquals("two", ConfigImpl.secureRandomProvider());
    assertEquals("three", ConfigImpl.messageDigestProvider());
    assertEquals(22, ConfigImpl.primeConfidenceLevel());
    // next, reset all config options again
    ConfigImpl.setSecureRandomAlgorithm(null);
    ConfigImpl.setSecureRandomProvider(null);
    ConfigImpl.setMessageDigestProvider(null);
    ConfigImpl.setPrimeConfidenceLevel(0);
    // now install a security manager so we won't have access to
    // the odd values
    System.setSecurityManager(new SecurityManager());
    // and make sure we get back the defaults when we ask
    assertEquals("SHA1PRNG", ConfigImpl.secureRandomAlgorithm());
    assertNull(ConfigImpl.secureRandomProvider());
    assertNull(ConfigImpl.messageDigestProvider());
    assertEquals(100, ConfigImpl.primeConfidenceLevel());
}
Example 66
Project: webbit-master  File: SslFactory.java View source code
public SSLContext getServerContext(String keyPass) throws WebbitException {
    try {
        // Set up key manager factory to use our key store
        String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
        if (algorithm == null)
            algorithm = "SunX509";
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
        kmf.init(ks, keyPass.toCharArray());
        // Initialize the SSLContext to work with our key managers.
        SSLContext sslContext = SSLContext.getInstance(PROTOCOL);
        sslContext.init(kmf.getKeyManagers(), null, null);
        return sslContext;
    } catch (Exception e) {
        throw new WebbitException(e);
    }
}
Example 67
Project: wildfly-elytron-master  File: DataSourceRule.java View source code
@Override
public void evaluate() throws Throwable {
    Security.addProvider(provider);
    dataSource = new JDBCDataSource();
    dataSource.setDatabase("mem:elytron-jdbc-realm-test");
    dataSource.setUser("sa");
    try {
        current.evaluate();
    } catch (Exception e) {
        throw e;
    } finally {
        Security.removeProvider(provider.getName());
    }
}
Example 68
Project: wildfly-security-master  File: DataSourceRule.java View source code
@Override
public void evaluate() throws Throwable {
    Security.addProvider(provider);
    dataSource = new JDBCDataSource();
    dataSource.setDatabase("mem:elytron-jdbc-realm-test");
    dataSource.setUser("sa");
    try {
        current.evaluate();
    } catch (Exception e) {
        throw e;
    } finally {
        Security.removeProvider(provider.getName());
    }
}
Example 69
Project: wycheproof-master  File: BasicTest.java View source code
/** List all algorithms known to the security manager. */
public void testListAllAlgorithms() {
    for (Provider p : Security.getProviders()) {
        System.out.println();
        System.out.println("Provider:" + p.getName());
        // Using a TreeSet here, because the elements are sorted.
        TreeSet<String> list = new TreeSet<String>();
        for (Object key : p.keySet()) {
            list.add((String) key);
        }
        for (String algorithm : list) {
            if (algorithm.startsWith("Alg.Alias.")) {
                continue;
            }
            System.out.println(algorithm);
        }
    }
}
Example 70
Project: Asynchronous-SSHD-master  File: SecurityUtils.java View source code
public void run() throws Exception {
    if (java.security.Security.getProvider(BOUNCY_CASTLE) == null) {
        LOG.info("Trying to register BouncyCastle as a JCE provider");
        java.security.Security.addProvider(new BouncyCastleProvider());
        MessageDigest.getInstance("MD5", BOUNCY_CASTLE);
        KeyAgreement.getInstance("DH", BOUNCY_CASTLE);
        LOG.info("Registration succeeded");
    } else {
        LOG.info("BouncyCastle already registered as a JCE provider");
    }
    securityProvider = BOUNCY_CASTLE;
}
Example 71
Project: bf-java-master  File: BillForwardClient.java View source code
public <TRequest, TResponse> TResponse requestUntyped(RequestMethod method, String url, TRequest obj, Type responseType) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException {
    url = String.format("%s/%s", apiUrl, url);
    String originalDNSCacheTTL = null;
    Boolean allowedToSetTTL = true;
    try {
        originalDNSCacheTTL = java.security.Security.getProperty(DNS_CACHE_TTL_PROPERTY_NAME);
        // disable DNS cache
        java.security.Security.setProperty(DNS_CACHE_TTL_PROPERTY_NAME, "0");
    } catch (SecurityException se) {
        allowedToSetTTL = false;
    }
    try {
        return _requestUntyped(responseType, method, url, obj, apiKey);
    } finally {
        if (allowedToSetTTL) {
            if (originalDNSCacheTTL == null) {
                // value unspecified by implementation
                // DNS_CACHE_TTL_PROPERTY_NAME of -1 = cache forever
                java.security.Security.setProperty(DNS_CACHE_TTL_PROPERTY_NAME, "-1");
            } else {
                java.security.Security.setProperty(DNS_CACHE_TTL_PROPERTY_NAME, originalDNSCacheTTL);
            }
        }
    }
}
Example 72
Project: fred-master  File: ECDHTest.java View source code
public static void main(String[] args) throws InvalidKeyException, IllegalStateException, NoSuchAlgorithmException {
    Security.addProvider(new BouncyCastleProvider());
    ECDH alice = new ECDH(Curves.P256);
    ECDH bob = new ECDH(Curves.P256);
    PublicKey bobP = bob.getPublicKey();
    PublicKey aliceP = alice.getPublicKey();
    System.out.println("Alice C: " + alice.curve);
    System.out.println("Bob   C: " + bob.curve);
    System.out.println("Alice P: " + toHex(aliceP.getEncoded()));
    System.out.println("Bob   P: " + toHex(bobP.getEncoded()));
    System.out.println("Alice S: " + toHex(alice.getAgreedSecret(bob.getPublicKey())));
    System.out.println("Bob   S: " + toHex(bob.getAgreedSecret(alice.getPublicKey())));
}
Example 73
Project: Plain-of-JARs-master  File: dumper.java View source code
public static void main(String[] args) throws Exception {
    //java.security.Security.setProperty("networkaddress.cache.negative.ttl" , "0");
    try {
        String version = "1.0.0";
        String program = "Dumper";
        System.out.println(program + " " + version);
        String domain = "homepage-baukasten.de";
        String ending = ".de.tl";
        Class.forName("org.h2.Driver");
        Runtime.getRuntime().addShutdownHook(new Thread() {

            @Override
            public void run() {
                try {
                    Connection conn = DriverManager.getConnection("jdbc:h2:./test;MODE=MySQL;MV_STORE=FALSE;MVCC=FALSE;MAX_COMPACT_TIME=2000", "sa", "");
                    conn.createStatement().execute("SHUTDOWN COMPACT");
                    conn.close();
                } catch (Exception e) {
                }
            }
        });
        Connection conn = DriverManager.getConnection("jdbc:h2:./test;MODE=MySQL;MV_STORE=FALSE;MVCC=FALSE;MAX_COMPACT_TIME=2000", "sa", "");
        conn.createStatement().execute("CREATE TABLE IF NOT EXISTS WEBSITES(ID BIGINT auto_increment, NAME VARCHAR)");
        conn.createStatement().execute("ALTER TABLE WEBSITES ADD CONSTRAINT IF NOT EXISTS NAME_UNIQUE UNIQUE(NAME)");
        conn.createStatement().execute("ALTER TABLE WEBSITES DROP COLUMN IF EXISTS ID");
        conn.createStatement().execute("ALTER TABLE WEBSITES ADD COLUMN IF NOT EXISTS ID BIGINT auto_increment BEFORE NAME");
        conn.createStatement().execute("SHUTDOWN COMPACT");
        conn.close();
        int dataset = 0;
        String padding = "";
        while (true) {
            try {
                //getPages("http://www.homepage-baukasten.de/forum/viewonline.php", "div.forum_main a.gen", conn);
                DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                Date date = new Date();
                int websites = getPages("http://www." + domain + "/forum/viewonline.php", "div.forum_main span.gen a", domain, ending);
                if (websites > 0) {
                    dataset++;
                    if (dataset < 10) {
                        padding = "0000";
                    } else if (dataset < 100) {
                        padding = "000";
                    } else if (dataset < 1000) {
                        padding = "00";
                    } else if (dataset < 10000) {
                        padding = "0";
                    } else {
                        padding = "";
                    }
                    // end of if-else
                    // end of if
                    System.out.println(padding + "" + dataset + "\t" + dateFormat.format(date) + "(" + System.currentTimeMillis() / 1000 + ")\tAdded " + websites + " website(s)");
                }
                // end of if
                Thread.sleep(1000 * 5);
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
            }
        }
    // end of while
    } catch (Exception e) {
        System.out.println(e);
    }
//conn.close();
}
Example 74
Project: scumd-master  File: SecurityUtils.java View source code
public void run() throws Exception {
    if (java.security.Security.getProvider(BOUNCY_CASTLE) == null) {
        LOG.info("Trying to register BouncyCastle as a JCE provider");
        java.security.Security.addProvider(new BouncyCastleProvider());
        MessageDigest.getInstance("MD5", BOUNCY_CASTLE);
        KeyAgreement.getInstance("DH", BOUNCY_CASTLE);
        LOG.info("Registration succeeded");
    } else {
        LOG.info("BouncyCastle already registered as a JCE provider");
    }
    securityProvider = BOUNCY_CASTLE;
}
Example 75
Project: wildfly-master  File: ControllerServlet.java View source code
public void init(ServletConfig config) throws ServletException {
    try {
        final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        final InputStream in = new BufferedInputStream(new FileInputStream("../jcetest.keystore"));
        try {
            keyStore.load(in, null);
        } finally {
            in.close();
        }
        final X509Certificate testCertificate = (X509Certificate) keyStore.getCertificate("test");
        // the three musketeers who are guarding the crown are hardcoded in jse.jar (JarVerifier)
        // sun.security.validator.SimpleValidator
        final Object validator = get("javax.crypto.JarVerifier", "providerValidator", Object.class);
        get(validator, "trustedX500Principals", Map.class).put(testCertificate.getIssuerX500Principal(), Arrays.asList(testCertificate));
    } catch (ClassNotFoundException e) {
        throw new ServletException("This requires being run on Oracle JDK 7.", e);
    } catch (Exception e) {
        throw new ServletException("Cannot install the certificate to the validator.", e);
    }
    java.security.Security.addProvider(new DummyProvider());
}
Example 76
Project: Android-Wallet-2-App-master  File: LinuxSecureRandom.java View source code
public static void init() {
    if (urandom == null) {
        try {
            File file = new File("/dev/urandom");
            if (file.exists()) {
                System.out.println("Opened /dev/urandom");
                // This stream is deliberately leaked.
                urandom = new FileInputStream(file);
                // Now override the default SecureRandom implementation with this one.
                Security.insertProviderAt(new LinuxSecureRandomProvider(), 1);
            } else {
                urandom = null;
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}
Example 77
Project: Assignments-master  File: XmlDSigKSTest.java View source code
@Test
public void XmlDSigRsaKS() throws Exception {
    (new File(DestDir)).mkdirs();
    super.initialize();
    String filename = "xfa.signed.ds.ks.pdf";
    String output = DestDir + filename;
    BouncyCastleProvider provider = new BouncyCastleProvider();
    Security.addProvider(provider);
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(new FileInputStream(KEYSTORE), PASSWORD);
    String alias = ks.aliases().nextElement();
    PrivateKey pk = (PrivateKey) ks.getKey(alias, PASSWORD);
    Certificate[] chain = ks.getCertificateChain(alias);
    signDsWithCertificate(Src, output, pk, chain, DigestAlgorithms.SHA1, provider.getName());
    String cmp = saveXmlFromResult(output);
    Assert.assertTrue("Verification", verifyXmlDSig(cmp));
    Assert.assertTrue(compareXmls(cmp, CmpDir + filename.replace(".pdf", ".xml")));
}
Example 78
Project: atricore-idbus-master  File: OCSPX509CertificateValidator.java View source code
public void validate(X509Certificate certificate) throws X509CertificateValidationException {
    try {
        if (_url != null) {
            log.debug("Using the OCSP server at: " + _url);
            Security.setProperty("ocsp.responderURLocsp.responderURL", _url);
        } else {
            log.debug("Using the OCSP server specified in the " + "Authority Info Access (AIA) extension " + "of the certificate");
        }
        // TODO STRONG-AUTH Move to system settings
        if (_httpProxyHost != null && _httpProxyPort != null) {
            System.setProperty("http.proxyHost", _httpProxyHost);
            System.setProperty("http.proxyPort", _httpProxyPort);
        } else {
            System.clearProperty("http.proxyHost");
            System.clearProperty("http.proxyPort");
        }
        // get certificate path
        CertPath cp = generateCertificatePath(certificate);
        // get trust anchors
        Set<TrustAnchor> trustedCertsSet = generateTrustAnchors();
        // init PKIX parameters
        PKIXParameters params = new PKIXParameters(trustedCertsSet);
        // init cert store
        Set<X509Certificate> certSet = new HashSet<X509Certificate>();
        if (_ocspCert == null) {
            _ocspCert = getCertificate(_ocspResponderCertificateAlias);
        }
        if (_ocspCert != null) {
            certSet.add(_ocspCert);
            CertStoreParameters storeParams = new CollectionCertStoreParameters(certSet);
            CertStore store = CertStore.getInstance("Collection", storeParams);
            params.addCertStore(store);
            Security.setProperty("ocsp.responderCertSubjectName", _ocspCert.getSubjectX500Principal().getName());
        }
        // activate certificate revocation checking
        params.setRevocationEnabled(true);
        // activate OCSP
        Security.setProperty("ocsp.enable", "true");
        // perform validation
        CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
        PKIXCertPathValidatorResult cpvResult = (PKIXCertPathValidatorResult) cpv.validate(cp, params);
        X509Certificate trustedCert = (X509Certificate) cpvResult.getTrustAnchor().getTrustedCert();
        if (trustedCert == null) {
            log.debug("Trsuted Cert = NULL");
        } else {
            log.debug("Trusted CA DN = " + trustedCert.getSubjectDN());
        }
    } catch (CertPathValidatorException e) {
        log.error(e, e);
        throw new X509CertificateValidationException(e);
    } catch (Exception e) {
        log.error(e, e);
        throw new X509CertificateValidationException(e);
    }
    log.debug("CERTIFICATE VALIDATION SUCCEEDED");
}
Example 79
Project: aws-java-sdk-master  File: CryptoRuntime.java View source code
public static synchronized void enableBouncyCastle() {
    if (isBouncyCastleAvailable()) {
        return;
    }
    try {
        @SuppressWarnings("unchecked") Class<Provider> c = (Class<Provider>) Class.forName(BC_PROVIDER_FQCN);
        Provider provider = c.newInstance();
        Security.addProvider(provider);
    } catch (Exception e) {
        LogFactory.getLog(CryptoRuntime.class).debug("Bouncy Castle not available", e);
    }
}
Example 80
Project: aws-sdk-android-master  File: CryptoRuntime.java View source code
public static void enableBouncyCastle() {
    try {
        @SuppressWarnings("unchecked") Class<Provider> c = (Class<Provider>) Class.forName(BC_PROVIDER_FQCN);
        Provider provider = c.newInstance();
        Security.addProvider(provider);
    } catch (Exception e) {
        LogFactory.getLog(CryptoRuntime.class).debug("Bouncy Castle not available", e);
    }
}
Example 81
Project: aws-sdk-java-master  File: CryptoRuntime.java View source code
public static synchronized void enableBouncyCastle() {
    if (isBouncyCastleAvailable()) {
        return;
    }
    try {
        @SuppressWarnings("unchecked") Class<Provider> c = (Class<Provider>) Class.forName(BC_PROVIDER_FQCN);
        Provider provider = c.newInstance();
        Security.addProvider(provider);
    } catch (Exception e) {
        LogFactory.getLog(CryptoRuntime.class).debug("Bouncy Castle not available", e);
    }
}
Example 82
Project: bitseal-master  File: SHA256.java View source code
/**
	 * Calculates the HmacSHA256 from the given key and data.
	 * 
	 * @param data - A byte[] containing the data.
	 * @param key - A byte[] containing the key.
	 * 
	 * @return A byte[] containing the HmacSHA256.
	 */
public static byte[] hmacSHA256(byte[] data, byte[] key) {
    Security.addProvider(new org.spongycastle.jce.provider.BouncyCastleProvider());
    try {
        Mac mac = Mac.getInstance("HmacSHA256", "SC");
        mac.init(new SecretKeySpec(key, "HmacSHA256"));
        return mac.doFinal(data);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("NoSuchAlgorithmException occurred in hmacSHA256.sha256hash160()", e);
    } catch (NoSuchProviderException e) {
        throw new RuntimeException("NoSuchProviderException occurred in hmacSHA256.sha256hash160()", e);
    } catch (InvalidKeyException e) {
        throw new RuntimeException("InvalidKeyException occurred in hmacSHA256.sha256hash160()", e);
    }
}
Example 83
Project: bugvm-master  File: SSLServerSocketFactory.java View source code
/**
     * Returns the default {@code SSLServerSocketFactory} instance. The default
     * implementation is defined by the security property
     * "ssl.ServerSocketFactory.provider".
     *
     * @return the default {@code SSLServerSocketFactory} instance.
     */
public static synchronized ServerSocketFactory getDefault() {
    if (defaultServerSocketFactory != null) {
        return defaultServerSocketFactory;
    }
    if (defaultName == null) {
        defaultName = Security.getProperty("ssl.ServerSocketFactory.provider");
        if (defaultName != null) {
            ClassLoader cl = Thread.currentThread().getContextClassLoader();
            if (cl == null) {
                cl = ClassLoader.getSystemClassLoader();
            }
            try {
                final Class<?> ssfc = Class.forName(defaultName, true, cl);
                defaultServerSocketFactory = (ServerSocketFactory) ssfc.newInstance();
            } catch (Exception e) {
            }
        }
    }
    if (defaultServerSocketFactory == null) {
        SSLContext context;
        try {
            context = SSLContext.getDefault();
        } catch (NoSuchAlgorithmException e) {
            context = null;
        }
        if (context != null) {
            defaultServerSocketFactory = context.getServerSocketFactory();
        }
    }
    if (defaultServerSocketFactory == null) {
        // Use internal dummy implementation
        defaultServerSocketFactory = new DefaultSSLServerSocketFactory("No ServerSocketFactory installed");
    }
    return defaultServerSocketFactory;
}
Example 84
Project: camel-master  File: SantuarioUtil.java View source code
public static void addSantuarioJSR105Provider() {
    AccessController.doPrivileged(new PrivilegedAction<Boolean>() {

        public Boolean run() {
            String providerName = "ApacheXMLDSig";
            Provider currentProvider = Security.getProvider(providerName);
            if (currentProvider == null) {
                Security.addProvider(new XMLDSigRI());
            }
            return true;
        }
    });
}
Example 85
Project: commons-eid-master  File: CMSTest.java View source code
@Test
public void testCMSSignature() throws Exception {
    Security.addProvider(new BeIDProvider());
    Security.addProvider(new BouncyCastleProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);
    PrivateKey privateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate certificate = (X509Certificate) keyStore.getCertificate("Authentication");
    CMSTypedData msg = new CMSProcessableByteArray("Hello world!".getBytes());
    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
    ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").build(privateKey);
    gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(sha1Signer, certificate));
    CMSSignedData sigData = gen.generate(msg, false);
}
Example 86
Project: conceal-master  File: CipherWriteBenchmark.java View source code
@Override
public void setUp() throws Exception {
    Random random = new Random();
    mData = new byte[size];
    random.nextBytes(mData);
    mNullOutputStream = new NullOutputStream();
    mHMAC = HMAC.getInstance();
    mNativeGCMCipherHelper = NativeGCMCipherHelper.getInstance();
    mAESCipher = AESCipher.getInstance();
    Security.addProvider(new BouncyCastleProvider());
    mBCGCMCipher = BouncyCastleGCMCipher.getInstance();
}
Example 87
Project: diqube-master  File: BouncyCastleUtil.java View source code
/**
   * @return The java security {@link Provider} of bouncycastle, if available. Make sure to add the dependency to the
   *         projects pom.
   * @throws BouncyCastleUnavailableException
   *           if BC is unavailable.
   */
public static Provider getProvider() throws BouncyCastleUnavailableException {
    Provider res = Security.getProvider(BC_PROVIDER_NAME);
    if (res == null) {
        synchronized (BouncyCastleUtil.class) {
            res = Security.getProvider(BC_PROVIDER_NAME);
            if (res == null) {
                // disable BC "EC MQV" (patent issues).
                System.setProperty("org.bouncycastle.ec.disable_mqv", "true");
                try {
                    @SuppressWarnings("unchecked") Class<? extends Provider> providerClass = (Class<? extends Provider>) Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider");
                    Provider bcProvider = providerClass.newInstance();
                    Security.addProvider(bcProvider);
                    res = Security.getProvider(BC_PROVIDER_NAME);
                } catch (ClassNotFoundExceptionInstantiationException | IllegalAccessException |  e) {
                    throw new BouncyCastleUnavailableException(e);
                }
            }
        }
    }
    return res;
}
Example 88
Project: docker-java-master  File: LocalDirectorySSLConfig.java View source code
@Override
public SSLContext getSSLContext() {
    boolean certificatesExist = CertificateUtils.verifyCertificatesExist(dockerCertPath);
    if (certificatesExist) {
        try {
            Security.addProvider(new BouncyCastleProvider());
            String caPemPath = dockerCertPath + File.separator + "ca.pem";
            String keyPemPath = dockerCertPath + File.separator + "key.pem";
            String certPemPath = dockerCertPath + File.separator + "cert.pem";
            String keypem = new String(Files.readAllBytes(Paths.get(keyPemPath)));
            String certpem = new String(Files.readAllBytes(Paths.get(certPemPath)));
            String capem = new String(Files.readAllBytes(Paths.get(caPemPath)));
            SslConfigurator sslConfig = SslConfigurator.newInstance(true);
            sslConfig.securityProtocol("TLSv1.2");
            sslConfig.keyStore(CertificateUtils.createKeyStore(keypem, certpem));
            sslConfig.keyStorePassword("docker");
            sslConfig.trustStore(CertificateUtils.createTrustStore(capem));
            return sslConfig.createSSLContext();
        } catch (Exception e) {
            throw new DockerClientException(e.getMessage(), e);
        }
    }
    return null;
}
Example 89
Project: eid-applet-master  File: ChannelBindingConfigServlet.java View source code
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Provider provider = null;
    if (null == Security.getProvider(BouncyCastleProvider.PROVIDER_NAME)) {
        provider = new BouncyCastleProvider();
        Security.addProvider(provider);
    }
    String serverCertificatePem = request.getParameter("serverCertificate");
    PEMReader pemReader = new PEMReader(new StringReader(serverCertificatePem));
    Object object = pemReader.readObject();
    pemReader.close();
    if (object instanceof X509Certificate) {
        X509Certificate serverCertificate = (X509Certificate) object;
        HttpSession httpSession = request.getSession();
        httpSession.setAttribute("test.be.fedict.eid.applet.model.ChannelBindingServiceBean.serverCertificate", serverCertificate);
    }
    response.sendRedirect("channel-binding.jsp");
    if (null != provider) {
        Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
    }
}
Example 90
Project: encryption-jvm-bootcamp-master  File: TestExampleBCPBEViaJCE.java View source code
@Test
public void test() throws Exception {
    Security.insertProviderAt(new BouncyCastleProvider(), 1);
    byte[] ciphertext = encrypt(PASSPHRASE, PLAINTEXT);
    String decryptedPlaintext = decrypt(PASSPHRASE, ciphertext);
    System.out.println("Decrypted plaintext: " + decryptedPlaintext);
    Assert.assertEquals(PLAINTEXT, decryptedPlaintext);
}
Example 91
Project: ExemplosDemoiselle-master  File: TesteLeituraAssinaturaPKCS7.java View source code
public static void main(String[] args) {
    String nomeArquivo = "/tmp/arquivo.txt.pkcs7.software";
    //		String nomeArquivo = "/tmp/arquivo.chain.enc.txt.pkcs7";
    //		String nomeArquivo = "/tmp/arquivo.chain.noenc.txt.pkcs7";
    //		String nomeArquivo = "/tmp/arquivo.nochain.enc.txt.pkcs7";
    //		String nomeArquivo = "/tmp/arquivo.nochain.noenc.txt.pkcs7";
    Security.addProvider(new BouncyCastleProvider());
    try {
        TabeliaoAssinaturaPKCS7 tabAssinatura = new TabeliaoAssinaturaPKCS7(new FileInputStream("/tmp/arquivo.txt"), new FileInputStream(nomeArquivo));
        TabeliaoCertificate tc = new TabeliaoCertificate(tabAssinatura.getCertificadoAssinante());
        System.out.println(tc.getCadeiaCertificados().size());
        TabeliaoResultadoValidacao trvCert = tc.valida();
        System.out.println("Carregando o certificado assinante");
        X509Certificate cert = tabAssinatura.getCertificadoAssinante();
        System.out.println(cert);
        TabeliaoResultadoValidacao trvAss = tabAssinatura.valida();
        System.out.println("*** Validação do certificado utilizado na assinatura: ");
        System.out.println(trvCert);
        System.out.println("*** Validação da assinatura: ");
        System.out.println(trvAss);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 92
Project: gobblin-master  File: GPGFileDecryptor.java View source code
public static InputStream decryptFile(InputStream inputStream, String passPhrase) throws IOException {
    if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
        Security.addProvider(new BouncyCastleProvider());
    }
    inputStream = PGPUtil.getDecoderStream(inputStream);
    JcaPGPObjectFactory pgpF = new JcaPGPObjectFactory(inputStream);
    PGPEncryptedDataList enc;
    Object pgpfObject = pgpF.nextObject();
    if (pgpfObject instanceof PGPEncryptedDataList) {
        enc = (PGPEncryptedDataList) pgpfObject;
    } else {
        enc = (PGPEncryptedDataList) pgpF.nextObject();
    }
    PGPPBEEncryptedData pbe = (PGPPBEEncryptedData) enc.get(0);
    InputStream clear;
    try {
        clear = pbe.getDataStream(new JcePBEDataDecryptorFactoryBuilder(new JcaPGPDigestCalculatorProviderBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME).build()).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(passPhrase.toCharArray()));
        JcaPGPObjectFactory pgpFact = new JcaPGPObjectFactory(clear);
        pgpfObject = pgpFact.nextObject();
        if (pgpfObject instanceof PGPCompressedData) {
            PGPCompressedData cData = (PGPCompressedData) pgpfObject;
            pgpFact = new JcaPGPObjectFactory(cData.getDataStream());
            pgpfObject = pgpFact.nextObject();
        }
        PGPLiteralData ld = (PGPLiteralData) pgpfObject;
        return ld.getInputStream();
    } catch (PGPException e) {
        throw new IOException(e);
    }
}
Example 93
Project: java_security-master  File: DESTest.java View source code
// 用bouncy castle实现:
public static void bcDES() {
    try {
        Security.addProvider(new BouncyCastleProvider());
        // 生�KEY
        KeyGenerator keyGenerator = KeyGenerator.getInstance("DES", "BC");
        keyGenerator.getProvider();
        keyGenerator.init(56);
        // 产生密钥
        SecretKey secretKey = keyGenerator.generateKey();
        // 获�密钥
        byte[] bytesKey = secretKey.getEncoded();
        // KEY转�
        DESKeySpec desKeySpec = new DESKeySpec(bytesKey);
        SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
        Key convertSecretKey = factory.generateSecret(desKeySpec);
        // 加密
        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, convertSecretKey);
        byte[] result = cipher.doFinal(src.getBytes());
        System.out.println("bc des encrypt:" + Hex.encodeHexString(result));
        // 解密
        cipher.init(Cipher.DECRYPT_MODE, convertSecretKey);
        result = cipher.doFinal(result);
        System.out.println("bc des decrypt:" + new String(result));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 94
Project: JBossAS51-master  File: JCASecurityInfo.java View source code
/**
    * Get the set of algorithms for a particular service
    * (Cipher,Signature,KeyFactory,SecretKeyFactory,AlgorithmParameters 
    *  MessageDigest,Mac)
    * @param serviceName
    * @return
    */
public String getJCAAlgorithms(String serviceName) {
    StringBuilder sb = new StringBuilder();
    Set<String> md2 = Security.getAlgorithms(serviceName);
    sb.append(serviceName).append(":algorithms=").append(md2.size()).append("[");
    for (String algo : md2) {
        sb.append(algo).append(DELIMITER);
    }
    sb.append("]");
    return sb.toString();
}
Example 95
Project: JBossAS_5_1_EDG-master  File: JCASecurityInfo.java View source code
/**
    * Get the set of algorithms for a particular service
    * (Cipher,Signature,KeyFactory,SecretKeyFactory,AlgorithmParameters 
    *  MessageDigest,Mac)
    * @param serviceName
    * @return
    */
public String getJCAAlgorithms(String serviceName) {
    StringBuilder sb = new StringBuilder();
    Set<String> md2 = Security.getAlgorithms(serviceName);
    sb.append(serviceName).append(":algorithms=").append(md2.size()).append("[");
    for (String algo : md2) {
        sb.append(algo).append(DELIMITER);
    }
    sb.append("]");
    return sb.toString();
}
Example 96
Project: JGlobus-master  File: SimpleMemoryCertStoreTest.java View source code
@BeforeClass
public static void loadBouncyCastleProvider() throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    CertificateFactory factory = CertificateFactory.getInstance("X.509", "BC");
    cert = (X509Certificate) factory.generateCertificate(new GlobusPathMatchingResourcePatternResolver().getResource("classpath:/validatorTest/usercert.pem").getInputStream());
    crl = (X509CRL) factory.generateCRL(new GlobusPathMatchingResourcePatternResolver().getResource("classpath:/validatorTest/ca2crl.r0").getInputStream());
}
Example 97
Project: minnal-master  File: HttpsConnector.java View source code
/**
	 * @return
	 */
protected SSLEngine createSslEngine() {
    logger.debug("Creating a SSL engine from the SSL context");
    String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
    if (algorithm == null) {
        algorithm = "SunX509";
        logger.trace("ssl.KeyManagerFactory.algorithm algorithm is not set. Defaulting to {}", algorithm);
    }
    SSLContext serverContext = null;
    SSLConfiguration configuration = getConnectorConfiguration().getSslConfiguration();
    InputStream stream = null;
    try {
        File file = new File(configuration.getKeyStoreFile());
        stream = new FileInputStream(file);
        KeyStore ks = KeyStore.getInstance(configuration.getKeystoreType());
        ks.load(stream, configuration.getKeyStorePassword().toCharArray());
        // Set up key manager factory to use our key store
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
        kmf.init(ks, configuration.getKeyPassword().toCharArray());
        // Initialize the SSLContext to work with our key managers.
        serverContext = SSLContext.getInstance(configuration.getProtocol());
        serverContext.init(kmf.getKeyManagers(), null, null);
    } catch (Exception e) {
        logger.error("Failed while initializing the ssl context", e);
        throw new MinnalException("Failed to initialize the ssl context", e);
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                logger.trace("Failed while closing the stream", e);
            }
        }
    }
    return serverContext.createSSLEngine();
}
Example 98
Project: MiscellaneousStudy-master  File: GetMail.java View source code
public static void main(String[] args) throws IOException, NoSuchProviderException, MessagingException {
    Properties properties = new Properties();
    properties.load(new InputStreamReader(ClassLoader.class.getResourceAsStream("/account.properties"), "UTF-8"));
    final String HOST = properties.getProperty("HOST");
    final String PORT = properties.getProperty("PORT");
    final String USER = properties.getProperty("USER");
    final String PASSWORD = properties.getProperty("PASSWORD");
    System.out.println(properties);
    Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
    Properties gmailProperties = new Properties();
    gmailProperties.put("mail.imap.starttls.enable", "true");
    gmailProperties.put("mail.imap.auth", "true");
    gmailProperties.put("mail.imap.socketFactory.port", PORT);
    gmailProperties.put("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    gmailProperties.put("mail.imap.socketFactory.fallback", "false");
    Session session = Session.getDefaultInstance(gmailProperties, null);
    Store store = session.getStore("imap");
    store.connect(HOST, USER, PASSWORD);
    Folder folder = store.getFolder(properties.getProperty("LABEL"));
    folder.open(Folder.READ_ONLY);
    for (Message message : folder.getMessages()) {
        System.out.printf("Subject: %s\n", message.getSubject());
        System.out.printf("Received Date: %s\n", message.getReceivedDate());
        System.out.printf("Content:\n%s\n", getText(message.getContent()));
    }
    folder.close(false);
}
Example 99
Project: mtools-master  File: InitServlet.java View source code
public void init() throws ServletException {
    try {
        //自定义log4j�置
        if (!FuncUtil.isEmpty(log4j)) {
            PropertyConfigurator.configure(SpringUtil.cfgPath(log4j));
        }
        log.info("�始化spring容器");
        log.info("SpringUtil init");
        ServletContext context = getServletContext();
        //		WebApplicationContext webAppContext = WebApplicationContextUtils
        //				.getWebApplicationContext(context);
        ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
        SpringUtil.initCxt(ctx);
        CoreDao dao = (CoreDao) SpringUtil.getAnoBean("dao");
        //		CoreDao daoExt = (CoreDao) SpringUtil.getAnoBean("daoExt");
        //		CoreDao daoExt = (CoreDao) SpringUtil.getBean("daoExt");
        List<String> values = dao.search("select 1 from dual", String.class, null);
        //		values = daoExt.search("select 1 from dual", String.class,
        //				null);
        //使用BouncyCastleProvideræ??供的安全策略 需è¦?引入bcprov-jdk16-1.46.jar
        Security.addProvider(new BouncyCastleProvider());
        log.info("加载系统�数�功");
    } catch (Exception e) {
        log.error("�始化�务应用�生异常", e);
        e.printStackTrace();
    }
}
Example 100
Project: MULE-master  File: SecurityUtils.java View source code
/**
   * Returns the default security provider that should be used in scenarios where ONE provider must be explicitly given. It will
   * get the first registered provider in order of preference, unless a system variable is defined with a provider name.
   *
   * <p>
   * <b>Note:</b> Use this method as a last resort for cases were a library always requires you to provide one. JCE already
   * provides an excellent provider selection algorithm, and many operations will automatically choose the best provider if you
   * don't force one in particular
   * </p>
   */
public static Provider getDefaultSecurityProvider() {
    String providerName = System.getProperty(MuleProperties.MULE_SECURITY_PROVIDER_PROPERTY);
    Provider provider = null;
    if (providerName == null) {
        if (!isFipsSecurityModel()) {
            provider = Security.getProvider(PREFERED_PROVIDER_NAME);
        }
        if (provider == null) {
            Provider[] providers = Security.getProviders();
            if (providers.length > 0) {
                provider = providers[0];
            }
        }
    } else {
        provider = Security.getProvider(providerName);
    }
    if (provider == null) {
        throw new IllegalStateException("Can't find a suitable security provider. " + (providerName == null ? "" : "Provider name " + providerName + " was not found."));
    }
    return provider;
}
Example 101
Project: nomulus-master  File: BackendServlet.java View source code
@Override
public void init() {
    Security.addProvider(new BouncyCastleProvider());
    try {
        metricReporter.startAsync().awaitRunning(10, TimeUnit.SECONDS);
        logger.info("Started up MetricReporter");
    } catch (TimeoutException timeoutException) {
        logger.severefmt("Failed to initialize MetricReporter: %s", timeoutException);
    }
}