java.security.Security Java Examples

The following examples show how to use java.security.Security. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CrossRealm.java    From hottub with GNU General Public License v2.0 7 votes vote down vote up
static void xRealmAuth() throws Exception {
    Security.setProperty("auth.login.defaultCallbackHandler", "CrossRealm");
    System.setProperty("java.security.auth.login.config", "jaas-localkdc.conf");
    System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");
    FileOutputStream fos = new FileOutputStream("jaas-localkdc.conf");
    fos.write(("com.sun.security.jgss.krb5.initiate {\n" +
            "    com.sun.security.auth.module.Krb5LoginModule\n" +
            "    required\n" +
            "    principal=dummy\n" +
            "    doNotPrompt=false\n" +
            "    useTicketCache=false\n" +
            "    ;\n" +
            "};").getBytes());
    fos.close();

    GSSManager m = GSSManager.getInstance();
    m.createContext(
            m.createName("[email protected]", GSSName.NT_HOSTBASED_SERVICE),
            GSSUtil.GSS_KRB5_MECH_OID,
            null,
            GSSContext.DEFAULT_LIFETIME).initSecContext(new byte[0], 0, 0);
}
 
Example #2
Source File: CrossRealm.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
static void xRealmAuth() throws Exception {
    Security.setProperty("auth.login.defaultCallbackHandler", "CrossRealm");
    System.setProperty("java.security.auth.login.config", "jaas-localkdc.conf");
    System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");
    FileOutputStream fos = new FileOutputStream("jaas-localkdc.conf");
    fos.write(("com.sun.security.jgss.krb5.initiate {\n" +
            "    com.sun.security.auth.module.Krb5LoginModule\n" +
            "    required\n" +
            "    principal=dummy\n" +
            "    doNotPrompt=false\n" +
            "    useTicketCache=false\n" +
            "    ;\n" +
            "};").getBytes());
    fos.close();

    GSSManager m = GSSManager.getInstance();
    m.createContext(
            m.createName("[email protected]", GSSName.NT_HOSTBASED_SERVICE),
            GSSUtil.GSS_KRB5_MECH_OID,
            null,
            GSSContext.DEFAULT_LIFETIME).initSecContext(new byte[0], 0, 0);
}
 
Example #3
Source File: ProviderList.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
public ProviderList(GSSCaller caller, boolean useNative) {
    this.caller = caller;
    Provider[] provList;
    if (useNative) {
        provList = new Provider[1];
        provList[0] = new SunNativeProvider();
    } else {
        provList = Security.getProviders();
    }

    for (int i = 0; i < provList.length; i++) {
        Provider prov = provList[i];
        try {
            addProviderAtEnd(prov, null);
        } catch (GSSException ge) {
            // Move on to the next provider
            GSSUtil.debug("Error in adding provider " +
                          prov.getName() + ": " + ge);
        }
    } // End of for loop
}
 
Example #4
Source File: BadKdc1.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args)
        throws Exception {

    // 5 sec is default timeout for tryLess
    if (BadKdc.getRatio() > 2.5) {
        Security.setProperty("krb5.kdc.bad.policy",
                "tryLess:1," + BadKdc.toReal(2000));
    } else {
        Security.setProperty("krb5.kdc.bad.policy", "tryLess");
    }

    BadKdc.go(
            "121212222222(32){1,2}1222(32){1,2}", // 1 2
            // The above line means try kdc1 for 2 seconds then kdc1
            // for 2 seconds... finally kdc3 for 2 seconds.
            "1222(32){1,2}1222(32){1,2}",    // 1 2
            // refresh
            "121212222222(32){1,2}1222(32){1,2}",  // 1 2
            // k3 off k2 on
            "(122212(22){1,2}|1222323232-)", // 1
            // k1 on
            "(12(12){1,2}|122232-)"  // empty
    );
}
 
Example #5
Source File: CICODESFuncTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    Provider provider = Security.getProvider("SunJCE");
    if (provider == null) {
        throw new RuntimeException("SunJCE provider does not exist.");
    }
    for (String algorithm : ALGORITHMS) {
        for (String mode : MODES) {
            // We only test noPadding and pkcs5padding for CFB72, OFB20, ECB
            // PCBC and CBC. Otherwise test noPadding only.
            int padKinds = 1;
            if (mode.equalsIgnoreCase("CFB72")
                    || mode.equalsIgnoreCase("OFB20")
                    || mode.equalsIgnoreCase("ECB")
                    || mode.equalsIgnoreCase("PCBC")
                    || mode.equalsIgnoreCase("CBC")) {
                padKinds = PADDINGS.length;
            }
            // PKCS5padding is meaningful only for ECB, CBC, PCBC
            for (int k = 0; k < padKinds; k++) {
                for (ReadModel readMode : ReadModel.values()) {
                    runTest(provider, algorithm, mode, PADDINGS[k], readMode);
                }
            }
        }
    }
}
 
Example #6
Source File: ShortRSAKey512.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    // reset the security property to make sure that the algorithms
    // and keys used in this test are not disabled.
    Security.setProperty("jdk.certpath.disabledAlgorithms", "MD2");
    Security.setProperty("jdk.tls.disabledAlgorithms",
            "SSLv3, RC4, DH keySize < 768");

    if (debug)
        System.setProperty("javax.net.debug", "all");

    /*
     * Get the customized arguments.
     */
    parseArguments(args);

    /*
     * Start the tests.
     */
    new ShortRSAKey512();
}
 
Example #7
Source File: TestKGParity.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
private void run() throws Exception {
    Provider[] providers = Security.getProviders();
    for (Provider p : providers) {
        String prvName = p.getName();
        if (prvName.startsWith("SunJCE")
                || prvName.startsWith("SunPKCS11-")) {
            for (String algorithm : ALGORITHM_ARR) {
                if (!runTest(p, algorithm)) {
                    throw new RuntimeException(
                            "Test failed with provider/algorithm:"
                                    + p.getName() + "/" + algorithm);
                } else {
                    out.println("Test passed with provider/algorithm:"
                            + p.getName() + "/" + algorithm);
                }
            }
        }
    }
}
 
Example #8
Source File: CheckDefaults.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private void runTest(String[] args) {
    if (!KeyStore.getDefaultType().
            equalsIgnoreCase(DEFAULT_KEY_STORE_TYPE)) {
        throw new RuntimeException(String.format("Default keystore type "
                + "Expected '%s' . Actual: '%s' ", DEFAULT_KEY_STORE_TYPE,
                KeyStore.getDefaultType()));
    }
    for (String ksDefaultType : KEY_STORE_TYPES) {
        Security.setProperty("keystore.type", ksDefaultType);
        if (!KeyStore.getDefaultType().equals(ksDefaultType)) {
            throw new RuntimeException(String.format(
                    "Keystore default type value: '%s' cannot be set up via"
                    + " keystore.type "
                    + "security property, Actual: '%s'",
                    ksDefaultType, KeyStore.getDefaultType()));
        }
    }
    out.println("Test Passed");
}
 
Example #9
Source File: JSSERenegotiate.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    // reset the security property to make sure that the cipher suites
    // used in this test are not disabled
    Security.setProperty("jdk.tls.disabledAlgorithms", "");

    String keyFilename =
        System.getProperty("test.src", "./") + "/" + pathToStores +
            "/" + keyStoreFile;
    String trustFilename =
        System.getProperty("test.src", "./") + "/" + pathToStores +
            "/" + trustStoreFile;

    System.setProperty("javax.net.ssl.keyStore", keyFilename);
    System.setProperty("javax.net.ssl.keyStorePassword", passwd);
    System.setProperty("javax.net.ssl.trustStore", trustFilename);
    System.setProperty("javax.net.ssl.trustStorePassword", passwd);

    if (debug)
        System.setProperty("javax.net.debug", "all");

    /*
     * Start the tests.
     */
    new JSSERenegotiate();
}
 
Example #10
Source File: TestJSSE.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
public static void server(String testProtocol, String testCipher,
        int testPort,
        String... exception) throws Exception {
    String expectedException = exception.length >= 1
            ? exception[0] : null;
    out.println(" This is Server");
    out.println(" Testing Protocol: " + testProtocol);
    out.println(" Testing Cipher: " + testCipher);
    out.println(" Testing Port: " + testPort);
    Provider p = new sun.security.ec.SunEC();
    Security.insertProviderAt(p, 1);
    try {
        CipherTestUtils.main(new JSSEFactory(null, testPort,
                testProtocol, testCipher, "Server JSSE"),
                "Server", expectedException);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #11
Source File: BasicTest.java    From wycheproof with Apache License 2.0 6 votes vote down vote up
/** List all algorithms known to the security manager. */
@Test
public void testListAllAlgorithms() {
  for (Provider p : Security.getProviders()) {
    System.out.println();
    System.out.println("Provider: " + p.getName() + " " + p.getVersion());
    // 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 #12
Source File: EdDSATest.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void ed25519() throws GeneralSecurityException {

	Security.addProvider(DSSSecurityProvider.getSecurityProvider());

	KeyPairGenerator kpg = KeyPairGenerator.getInstance("Ed25519", DSSSecurityProvider.getSecurityProviderName());
	KeyPair kp = kpg.generateKeyPair();
	assertNotNull(kp);

	PublicKey publicKey = kp.getPublic();
	assertNotNull(publicKey);
	assertEquals("Ed25519", publicKey.getAlgorithm());
	assertEquals(EncryptionAlgorithm.ED25519, EncryptionAlgorithm.forKey(publicKey));

	PrivateKey privateKey = kp.getPrivate();
	assertNotNull(privateKey);
	assertEquals("Ed25519", privateKey.getAlgorithm());
}
 
Example #13
Source File: ElytronCSKeyStoreProviderFactory.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void init(Config.Scope config) {
    super.init(config);

    this.credentialStoreLocation = config.get(CS_LOCATION);
    if (this.credentialStoreLocation == null) {
        logger.debug("ElytronCSKeyStoreProviderFactory not properly configured - missing store location");
        return;
    }
    if (!Files.exists(Paths.get(this.credentialStoreLocation))) {
        throw new VaultNotFoundException("The " + this.credentialStoreLocation + " file doesn't exist");
    }

    this.credentialStoreSecret = config.get(CS_SECRET);
    if (this.credentialStoreSecret == null) {
        logger.debug("ElytronCSKeyStoreProviderFactory not properly configured - missing store secret");
        return;
    }
    this.credentialStoreType = config.get(CS_KEYSTORE_TYPE, JCEKS);

    // install the elytron credential store provider.
    Security.addProvider(WildFlyElytronCredentialStoreProvider.getInstance());
}
 
Example #14
Source File: TlsHelperTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testOutputToFileTwoCertsAsPem() throws IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    File folder = tempFolder.newFolder("splitKeystoreOutputDir");

    KeyStore keyStore = setupKeystore();
    HashMap<String, Certificate> certs = TlsHelper.extractCerts(keyStore);
    TlsHelper.outputCertsAsPem(certs, folder,".crt");

    assertEquals(folder.listFiles().length, 2);

    for(File file : folder.listFiles()) {
        X509Certificate certFromFile = loadCertificate(file);
        assertTrue(certs.containsValue(certFromFile));
        X509Certificate originalCert = (X509Certificate) certs.get(file.getName().split("\\.")[0]);
        assertTrue(originalCert.equals(certFromFile));
        assertArrayEquals(originalCert.getSignature(), certFromFile.getSignature());
    }
}
 
Example #15
Source File: NonSymmetricCryptographyTest.java    From crypto with Apache License 2.0 6 votes vote down vote up
/**
 * ELGAMAL算法只支持公钥加密私钥解密
 */
@Test
public void testELGAMALCryptoByBouncyCastle(){
    BouncyCastleProvider bouncyCastleProvider = new BouncyCastleProvider();
    Security.addProvider(bouncyCastleProvider);
    Configuration configuration = new Configuration();
    configuration.setKeyAlgorithm(Algorithms.ELGAMAL).setCipherAlgorithm(Algorithms.ELGAMAL_ECB_PKCS1PADDING).setKeySize(512);
    NonSymmetricCryptography nonSymmetricCryptography = new NonSymmetricCryptography(configuration);
    Map<String,Key> keyMap = nonSymmetricCryptography.initKey();
    String privateKey = nonSymmetricCryptography.encodeKey(nonSymmetricCryptography.getPrivateKey(keyMap));
    String publicKey = nonSymmetricCryptography.encodeKey(nonSymmetricCryptography.getPublicKey(keyMap));
    System.out.println("ELGAMAL私钥:" + privateKey);
    System.out.println("ELGAMAL公钥:" + publicKey);
    System.out.println("加密前数据:" + data);
    // 公钥加密私钥解密
    String encryptData = nonSymmetricCryptography.encryptByPublicKey(data, nonSymmetricCryptography.decodeKey(publicKey));
    System.out.println("公钥加密后数据:" + encryptData);
    String decryptData = nonSymmetricCryptography.decryptByPrivateKey(encryptData, nonSymmetricCryptography.decodeKey(privateKey));
    System.out.println("私钥解密后数据:" + decryptData);
}
 
Example #16
Source File: GPGFileEncryptor.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * Taking in an input {@link OutputStream} and a passPhrase, return an {@link OutputStream} that can be used to output
 * encrypted output to the input {@link OutputStream}.
 * @param outputStream the output stream to hold the ciphertext {@link OutputStream}
 * @param passPhrase pass phrase
 * @param cipher the symmetric cipher to use for encryption. If null or empty then a default cipher is used.
 * @return {@link OutputStream} to write content to for encryption
 * @throws IOException
 */
public OutputStream encryptFile(OutputStream outputStream, String passPhrase, String cipher) throws IOException {
  try {
    if (Security.getProvider(PROVIDER_NAME) == null) {
      Security.addProvider(new BouncyCastleProvider());
    }

    PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(
        new JcePGPDataEncryptorBuilder(symmetricKeyAlgorithmNameToTag(cipher))
            .setSecureRandom(new SecureRandom())
            .setProvider(PROVIDER_NAME));
    cPk.addMethod(new JcePBEKeyEncryptionMethodGenerator(passPhrase.toCharArray()).setProvider(PROVIDER_NAME));

    OutputStream cOut = cPk.open(outputStream, new byte[BUFFER_SIZE]);

    PGPLiteralDataGenerator literalGen = new PGPLiteralDataGenerator();
    OutputStream _literalOut =
        literalGen.open(cOut, PGPLiteralDataGenerator.BINARY, PAYLOAD_NAME, new Date(), new byte[BUFFER_SIZE]);

    return new ClosingWrapperOutputStream(_literalOut, cOut, outputStream);
  } catch (PGPException e) {
    throw new IOException(e);
  }
}
 
Example #17
Source File: ClientJSSEServerJSSE.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // reset security properties to make sure that the algorithms
    // and keys used in this test are not disabled.
    Security.setProperty("jdk.tls.disabledAlgorithms", "");
    Security.setProperty("jdk.certpath.disabledAlgorithms", "");

    CipherTest.main(new JSSEFactory(), args);
}
 
Example #18
Source File: CriticalSubjectAltName.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // MD5 is used in this test case, don't disable MD5 algorithm.
    Security.setProperty("jdk.certpath.disabledAlgorithms",
            "MD2, RSA keySize < 1024");
    Security.setProperty("jdk.tls.disabledAlgorithms",
            "SSLv3, RC4, DH keySize < 768");

    String keyFilename =
        System.getProperty("test.src", "./") + "/" + pathToStores +
            "/" + keyStoreFile;
    String trustFilename =
        System.getProperty("test.src", "./") + "/" + pathToStores +
            "/" + trustStoreFile;

    System.setProperty("javax.net.ssl.keyStore", keyFilename);
    System.setProperty("javax.net.ssl.keyStorePassword", passwd);
    System.setProperty("javax.net.ssl.trustStore", trustFilename);
    System.setProperty("javax.net.ssl.trustStorePassword", passwd);

    if (debug)
        System.setProperty("javax.net.debug", "all");

    /*
     * Start the tests.
     */
    new CriticalSubjectAltName();
}
 
Example #19
Source File: GenerationTests.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void removePKCS11Provider() throws Exception {
    secondChanceGranted = true;
    Security.removeProvider("SunPKCS11-Solaris");
    System.out.println("Second chance granted. Provider list: "
            + Arrays.toString(Security.getProviders()));
    setup();
}
 
Example #20
Source File: PKCS11KeyStoreKeyingDataProvider.java    From xades4j with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * The provider name is used as a key to search for installed providers. If a
 * provider exists with the same name, it will be used even if it relies on a
 * different native library.
 * @param nativeLibraryPath the path for the native library of the specific PKCS#11 provider
 * @param providerName this string is concatenated with the prefix SunPKCS11- to produce this provider instance's name
 * @param slotId the id of the slot that this provider instance is to be associated with (can be {@code null})
 * @param certificateSelector the selector of signing certificate
 * @param keyStorePasswordProvider the provider of the keystore loading password (can be {@code null})
 * @param entryPasswordProvider the provider of entry passwords (may be {@code null})
 * @param returnFullChain indicates if the full certificate chain should be returned, if available
 * @throws KeyStoreException
 */
public PKCS11KeyStoreKeyingDataProvider(
        final String nativeLibraryPath,
        final String providerName,
        final Integer slotId,
        SigningCertSelector certificateSelector,
        KeyStorePasswordProvider keyStorePasswordProvider,
        KeyEntryPasswordProvider entryPasswordProvider,
        boolean returnFullChain) throws KeyStoreException
{
    super(new KeyStoreBuilderCreator()
    {
        @Override
        public Builder getBuilder(ProtectionParameter loadProtection)
        {
            Provider p = getInstalledProvider(providerName);
            if (p == null)
            {
                StringBuilder config = new StringBuilder("name = ").append(providerName);
                config.append(System.getProperty("line.separator"));
                config.append("library = ").append(nativeLibraryPath);
                if(slotId != null)
                {
                    config.append(System.getProperty("line.separator"));
                    config.append("slot = ").append(slotId);
                }
                ByteArrayInputStream configStream = new ByteArrayInputStream(config.toString().getBytes());
                p = createPkcs11Provider(configStream);
                Security.addProvider(p);
            }

            return KeyStore.Builder.newInstance("PKCS11", p, loadProtection);
        }
    }, certificateSelector, keyStorePasswordProvider, entryPasswordProvider, returnFullChain);
}
 
Example #21
Source File: BuildEEBasicConstraints.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // reset the security property to make sure that the algorithms
    // and keys used in this test are not disabled.
    Security.setProperty("jdk.certpath.disabledAlgorithms", "MD2");

    X509Certificate rootCert = CertUtils.getCertFromFile("anchor.cer");
    TrustAnchor anchor = new TrustAnchor
        (rootCert.getSubjectX500Principal(), rootCert.getPublicKey(), null);
    X509CertSelector sel = new X509CertSelector();
    sel.setBasicConstraints(-2);
    PKIXBuilderParameters params = new PKIXBuilderParameters
        (Collections.singleton(anchor), sel);
    params.setRevocationEnabled(false);
    X509Certificate eeCert = CertUtils.getCertFromFile("ee.cer");
    X509Certificate caCert = CertUtils.getCertFromFile("ca.cer");
    ArrayList<X509Certificate> certs = new ArrayList<X509Certificate>();
    certs.add(caCert);
    certs.add(eeCert);
    CollectionCertStoreParameters ccsp =
        new CollectionCertStoreParameters(certs);
    CertStore cs = CertStore.getInstance("Collection", ccsp);
    params.addCertStore(cs);
    PKIXCertPathBuilderResult res = CertUtils.build(params);
    CertPath cp = res.getCertPath();
    // check that first certificate is an EE cert
    List<? extends Certificate> certList = cp.getCertificates();
    X509Certificate cert = (X509Certificate) certList.get(0);
    if (cert.getBasicConstraints() != -1) {
        throw new Exception("Target certificate is not an EE certificate");
    }
}
 
Example #22
Source File: NameConstraintsWithRID.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) throws Exception {
    CertPath path = generateCertificatePath();
    Set<TrustAnchor> anchors = generateTrustAnchors();

    PKIXParameters params = new PKIXParameters(anchors);

    // disable certificate revocation checking
    params.setRevocationEnabled(false);

    // set the validation time
    params.setDate(new Date(109, 5, 8));   // 2009-05-01

    // disable OCSP checker
    Security.setProperty("ocsp.enable", "false");

    // disable CRL checker
    System.setProperty("com.sun.security.enableCRLDP", "false");

    CertPathValidator validator = CertPathValidator.getInstance("PKIX");

    try {
        validator.validate(path, params);
        throw new Exception(
            "the subjectAltName is excluded by NameConstraints, " +
            "should thrown CertPathValidatorException");
    } catch (CertPathValidatorException uoe) {
        // that is the expected exception.
    }
}
 
Example #23
Source File: TestPolicy.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // reset the security property to make sure that the algorithms
    // and keys used in this test are not disabled.
    Security.setProperty("jdk.certpath.disabledAlgorithms", "MD2");

    factory = CertificateFactory.getInstance("X.509");

    X509Certificate anchor = loadCertificate("anchor.cer");
    X509Certificate ca = loadCertificate("ca.cer");
    X509Certificate ee = loadCertificate("ee.cer");

    for (int i = 0; i < TEST_CASES.length; i++) {
        TestCase testCase = TEST_CASES[i];
        System.out.println("*** Running test: " + testCase);
        CertPathValidator validator = CertPathValidator.getInstance("PKIX");

        PKIXParameters params = new PKIXParameters(Collections.singleton(new TrustAnchor(anchor, null)));
        params.setRevocationEnabled(false);
        params.setInitialPolicies(testCase.initialPolicies);

        CertPath path = factory.generateCertPath(Arrays.asList(new X509Certificate[] {ee, ca}));

        PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult)validator.validate(path, params);

        PolicyNode tree = result.getPolicyTree();
        System.out.println(tree);

        String resultTree = toString(tree);
        if (resultTree.equals(testCase.resultTree) == false) {
            System.out.println("Mismatch");
            System.out.println("Should: " + testCase.resultTree);
            System.out.println("Is:     " + resultTree);
            throw new Exception("Test failed: " + testCase);
        }
    }
}
 
Example #24
Source File: Application.java    From guardedbox with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Main method. Invokes the Spring-Boot run method.
 *
 * @param args Arguments. They are passed to the Spring-Boot run method.
 */
public static void main(
        final String[] args) {

    // Add BouncyCastle Security Provider.
    Security.addProvider(new BouncyCastleProvider());

    // Run Spring-Boot.
    SpringApplication.run(Application.class, args);

}
 
Example #25
Source File: DGCImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Initialize the dgcFilter from the security properties or system property; if any
 * @return an ObjectInputFilter, or null
 */
private static ObjectInputFilter initDgcFilter() {
    ObjectInputFilter filter = null;
    String props = System.getProperty(DGC_FILTER_PROPNAME);
    if (props == null) {
        props = Security.getProperty(DGC_FILTER_PROPNAME);
    }
    if (props != null) {
        filter = ObjectInputFilter.Config.createFilter(props);
        if (dgcLog.isLoggable(Log.BRIEF)) {
            dgcLog.log(Log.BRIEF, "dgcFilter = " + filter);
        }
    }
    return filter;
}
 
Example #26
Source File: TestEC.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public static void main0(String[] args) throws Exception {
    Provider p = Security.getProvider("SunEC");

    if (p == null) {
        throw new NoSuchProviderException("Can't get SunEC provider");
    }

    System.out.println("Running tests with " + p.getName() +
        " provider...\n");
    long start = System.currentTimeMillis();

    /*
     * The entry point used for each test is its instance method
     * called main (not its static method called main).
     */
    new TestECDH().main(p);
    new TestECDSA().main(p);
    new TestCurves().main(p);
    new TestKeyFactory().main(p);
    new TestECGenSpec().main(p);
    new ReadPKCS12().main(p);
    new ReadCertificates().main(p);

    // ClientJSSEServerJSSE fails on Solaris 11 when both SunEC and
    // SunPKCS11-Solaris providers are enabled.
    // Workaround:
    // Security.removeProvider("SunPKCS11-Solaris");
    new ClientJSSEServerJSSE().main(p);

    long stop = System.currentTimeMillis();
    System.out.println("\nCompleted tests with " + p.getName() +
        " provider (" + ((stop - start) / 1000.0) + " seconds).");
}
 
Example #27
Source File: ToolSHA2.java    From protools with Apache License 2.0 5 votes vote down vote up
/**
 * SHA-224加密
 *
 * @param data
 *         待加密数据
 *
 * @return byte[] 消息摘要
 *
 * @throws Exception
 */
public static byte[] encodeSHA224(byte[] data) throws NoSuchAlgorithmException {
    // 加入BouncyCastleProvider支持
    Security.addProvider(new BouncyCastleProvider());

    // 初始化MessageDigest
    MessageDigest md = MessageDigest.getInstance("SHA-224");

    // 执行消息摘要
    return md.digest(data);
}
 
Example #28
Source File: CircularCRLTwoLevel.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) throws Exception {
    CertPath path = generateCertificatePath();
    Set<TrustAnchor> anchors = generateTrustAnchors();
    CertStore crls = generateCertificateStore();

    PKIXParameters params = new PKIXParameters(anchors);

    // add the CRL store
    params.addCertStore(crls);

    // Activate certificate revocation checking
    params.setRevocationEnabled(true);

    // set the validation time
    params.setDate(new Date(109, 5, 1));   // 2009-05-01

    // disable OCSP checker
    Security.setProperty("ocsp.enable", "false");

    // enable CRL checker
    System.setProperty("com.sun.security.enableCRLDP", "true");

    CertPathValidator validator = CertPathValidator.getInstance("PKIX");

    try {
        validator.validate(path, params);
    } catch (CertPathValidatorException cpve) {
        if (cpve.getReason() != BasicReason.REVOKED) {
            throw new Exception(
                "unexpect exception, should be a REVOKED CPVE", cpve);
        }
    }
}
 
Example #29
Source File: Platform.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
/**
 * Select the first recognized security provider according to the preference order returned by
 * {@link Security#getProviders}. If a recognized provider is not found then warn but continue.
 */
private static Provider getAndroidSecurityProvider() {
  Provider[] providers = Security.getProviders();
  for (Provider availableProvider : providers) {
    for (String providerClassName : ANDROID_SECURITY_PROVIDERS) {
      if (providerClassName.equals(availableProvider.getClass().getName())) {
        logger.log(Level.FINE, "Found registered provider {0}", providerClassName);
        return availableProvider;
      }
    }
  }
  logger.log(Level.WARNING, "Unable to find Conscrypt");
  return null;
}
 
Example #30
Source File: Teku.java    From teku with Apache License 2.0 5 votes vote down vote up
public static void main(final String... args) {
  Thread.setDefaultUncaughtExceptionHandler(new TekuDefaultExceptionHandler());
  Security.addProvider(new BouncyCastleProvider());
  final PrintWriter outputWriter = new PrintWriter(System.out, true, UTF_8);
  final PrintWriter errorWriter = new PrintWriter(System.err, true, UTF_8);
  final int result =
      new BeaconNodeCommand(outputWriter, errorWriter, System.getenv(), Teku::start).parse(args);
  if (result != 0) {
    System.exit(result);
  }
}