Java 类java.security.Security 实例源码

项目:jdk8u-jdk    文件:Encrypt.java   
public static void main(String[] args) throws Exception {
    Provider p = Security.getProvider("SunJCE");
    for (String alg : ALGORITHMS) {
        for (int keyStrength : KEY_STRENGTHS) {
            if (keyStrength > Cipher.getMaxAllowedKeyLength(alg)) {
                // skip this if this key length is larger than what's
                // configured in the JCE jurisdiction policy files
                continue;
            }
            for (int textLength : TEXT_LENGTHS) {
                for (int AADLength : AAD_LENGTHS) {
                    Encrypt test = new Encrypt(p, alg,
                            "GCM", "NoPadding", keyStrength, textLength,
                            AADLength);
                    Cipher cipher = test.createCipher(Cipher.ENCRYPT_MODE,
                            null);
                    AlgorithmParameters params = cipher.getParameters();
                    test.doTest(params);
                    System.out.println("Test " + alg + ":"
                            + keyStrength + ":" + textLength + ":"
                            + AADLength + " passed");
                }
            }
        }
    }
}
项目:openjdk-jdk10    文件:TextPKCS5PaddingTest.java   
public static void main(String[] args) throws Exception {
    Provider provider = Security.getProvider("SunJCE");
    if (provider == null) {
        throw new RuntimeException("SunJCE provider not exist");
    }
    // generate no-padding cipher with secret key
    Cipher c = Cipher.getInstance("DES/CBC/NoPadding", provider);
    KeyGenerator kgen = KeyGenerator.getInstance("DES", provider);
    SecretKey skey = kgen.generateKey();
    // this is the improperly padded plaintext

    c.init(Cipher.ENCRYPT_MODE, skey);
    // encrypt plaintext
    byte[] cipher = c.doFinal(PLAIN_TEXT);
    AlgorithmParameters params = c.getParameters();
    // generate cipher that enforces PKCS5 padding
    c = Cipher.getInstance("DES/CBC/PKCS5Padding", provider);
    c.init(Cipher.DECRYPT_MODE, skey, params);
    try {
        c.doFinal(cipher);
        throw new RuntimeException(
                "ERROR: Expected BadPaddingException not thrown");
    } catch (BadPaddingException expected) {
        out.println("Expected BadPaddingException thrown");
    }

}
项目:jdk8u-jdk    文件:DefaultSSLServSocketFac.java   
public static void main(String[] args) throws Exception {
    // reserve the security properties
    String reservedSSFacProvider =
        Security.getProperty("ssl.ServerSocketFactory.provider");

    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;
        }
        // get the expected exception
    } finally {
        // restore the security properties
        if (reservedSSFacProvider == null) {
            reservedSSFacProvider = "";
        }
        Security.setProperty("ssl.ServerSocketFactory.provider",
                                                reservedSSFacProvider);
    }
}
项目:boohee_v5.6    文件:b.java   
public static b a(String str) {
    HttpParams basicHttpParams = new BasicHttpParams();
    HttpProtocolParams.setVersion(basicHttpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUseExpectContinue(basicHttpParams, false);
    HttpConnectionParams.setStaleCheckingEnabled(basicHttpParams, false);
    HttpConnectionParams.setConnectionTimeout(basicHttpParams, 20000);
    HttpConnectionParams.setSoTimeout(basicHttpParams, 30000);
    HttpConnectionParams.setSocketBufferSize(basicHttpParams, 8192);
    HttpClientParams.setRedirecting(basicHttpParams, true);
    HttpClientParams.setAuthenticating(basicHttpParams, false);
    HttpProtocolParams.setUserAgent(basicHttpParams, str);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme(com.alipay.sdk.cons.b.a, SSLCertificateSocketFactory.getHttpSocketFactory(30000, null), WebSocket.DEFAULT_WSS_PORT));
    ClientConnectionManager threadSafeClientConnManager = new ThreadSafeClientConnManager(basicHttpParams, schemeRegistry);
    ConnManagerParams.setTimeout(basicHttpParams, 60000);
    ConnManagerParams.setMaxConnectionsPerRoute(basicHttpParams, new ConnPerRouteBean(10));
    ConnManagerParams.setMaxTotalConnections(basicHttpParams, 50);
    Security.setProperty("networkaddress.cache.ttl", "-1");
    HttpsURLConnection.setDefaultHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
    return new b(threadSafeClientConnManager, basicHttpParams);
}
项目:openjdk-jdk10    文件:TestKGParity.java   
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);
                }
            }
        }
    }
}
项目:nutz-pay    文件:CertUtil.java   
/**
 * 打jre中印算法提供者列表
 */
private static void printProviders() {
    log.info("Providers List:");
    Provider[] providers = Security.getProviders();
    for (int i = 0; i < providers.length; i++) {
        log.info(i + 1 + "." + providers[i].getName());
    }
}
项目:jdk8u-jdk    文件:CheckDefaults.java   
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");
}
项目:jdk8u-jdk    文件:LoginNoPass.java   
public static void main(String[] args) throws Exception {

        new OneKDC(null) {
            protected byte[] processAsReq(byte[] in) throws Exception {
                kdcTouched = true;
                return super.processAsReq(in);
            }
        }.writeJAASConf();
        Security.setProperty("auth.login.defaultCallbackHandler",
                "LoginNoPass$CallbackForClient");
        System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");

        try {
            Context c;
            c = Context.fromJAAS("client");
            c.startAsClient(OneKDC.SERVER, GSSUtil.GSS_KRB5_MECH_OID);
            c.take(new byte[0]);
        } catch (Exception e) {
            e.printStackTrace(System.out);
            // OK
        }
        if (kdcTouched) {
            throw new Exception("Failed");
        }
    }
项目:jdk8u-jdk    文件:ShortRSAKeyGCM.java   
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 ShortRSAKeyGCM();
}
项目:ipack    文件:PEMReader.java   
static byte[] crypt(
    boolean encrypt,
    String provider,
    byte[] bytes,
    char[] password,
    String dekAlgName,
    byte[] iv)
    throws IOException
{
    Provider prov = null;
    if (provider != null)
    {
        prov = Security.getProvider(provider);
        if (prov == null)
        {
            throw new EncryptionException("cannot find provider: " + provider);
        }
    }

    return crypt(encrypt, prov, bytes, password, dekAlgName, iv);
}
项目:ipack    文件:Main.java   
public static void main(final String... args) throws IOException {
    if (args.length == 0) {
        System.out.println(USAGE);
        return;
    }

    Security.addProvider(new BouncyCastleProvider());

    try {
        execute(args);
    } catch (final RuntimeException e) {
        System.err.println(e.toString());
        e.printStackTrace(System.out);
        System.err.println(e.getMessage());
        System.exit(1);
    }
}
项目:openjdk-jdk10    文件:RmiBootstrapTest.java   
/**
 * Calls run(args[]).
 * exit(1) if the test fails.
 **/
public static void main(String args[]) throws Exception {
    Security.setProperty("jdk.tls.disabledAlgorithms", "");

    try {
        MAX_GET_FREE_PORT_TRIES = Integer.parseInt(System.getProperty("test.getfreeport.max.tries", "10"));
    } catch (NumberFormatException ex) {
    }

    RmiBootstrapTest manager = new RmiBootstrapTest();
    try {
        manager.run(args);
    } catch (RuntimeException r) {
        System.out.println("Test Failed: "+ r.getMessage());
        System.exit(1);
    } catch (Throwable t) {
        System.out.println("Test Failed: "+ t);
        t.printStackTrace();
        System.exit(2);
    }
    System.out.println("**** Test  RmiBootstrap Passed ****");
}
项目:jdk8u-jdk    文件:DHEKeySizing.java   
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", "");

    if (args.length != 4) {
        System.out.println(
            "Usage: java DHEKeySizing cipher-suite " +
            "exportable(true|false)\n" +
            "    size-of-server-hello-record size-of-client-key-exchange");
        throw new Exception("Incorrect usage!");
    }

    (new DHEKeySizing()).test(args[0],
            Boolean.parseBoolean(args[1]),
            Integer.parseInt(args[2]),
            Integer.parseInt(args[3]));
    System.out.println("Test Passed.");
}
项目:jdk8u-jdk    文件:TestPremaster.java   
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);
    }

    int[] protocolVersions = {0x0300, 0x0301, 0x0302, 0x0400};
    for (int clientVersion : protocolVersions) {
        for (int serverVersion : protocolVersions) {
            test(kg, clientVersion, serverVersion);
            if (serverVersion >= clientVersion) {
                break;
            }
        }
    }

    System.out.println("Done.");
}
项目:openjdk-jdk10    文件:TestCACerts.java   
@Override
public void main(Provider p) throws Exception {

    /*
     * Use Solaris SPARC 11.2 or later to avoid an intermittent failure
     * when running SunPKCS11-Solaris (8044554)
     */
    if (p.getName().equals("SunPKCS11-Solaris") &&
        props.getProperty("os.name").equals("SunOS") &&
        props.getProperty("os.arch").equals("sparcv9") &&
        props.getProperty("os.version").compareTo("5.11") <= 0 &&
        getDistro().compareTo("11.2") < 0) {

        System.out.println("SunPKCS11-Solaris provider requires " +
            "Solaris SPARC 11.2 or later, skipping");
        return;
    }

    long start = System.currentTimeMillis();
    Providers.setAt(p, 1);
    try {
        String PROVIDER = p.getName();
        String javaHome = props.getProperty("java.home");
        String caCerts = javaHome + SEP + "lib" + SEP + "security" + SEP + "cacerts";
        KeyStore ks;
        try (InputStream in = new FileInputStream(caCerts)) {
            ks = KeyStore.getInstance(KeyStore.getDefaultType());
            ks.load(in, null);
        }
        for (Enumeration e = ks.aliases(); e.hasMoreElements(); ) {
            String alias = (String)e.nextElement();
            if (ks.isCertificateEntry(alias)) {
                System.out.println("* Testing " + alias + "...");
                X509Certificate cert = (X509Certificate)ks.getCertificate(alias);
                PublicKey key = cert.getPublicKey();
                String alg = key.getAlgorithm();
                if (alg.equals("RSA")) {
                    System.out.println("Signature algorithm: " + cert.getSigAlgName());
                    cert.verify(key, PROVIDER);
                } else {
                    System.out.println("Skipping cert with key: " + alg);
                }
            } else {
                System.out.println("Skipping alias " + alias);
            }
        }
        long stop = System.currentTimeMillis();
        System.out.println("All tests passed (" + (stop - start) + " ms).");
     } finally {
        Security.removeProvider(p.getName());
     }
}
项目:message-broker    文件:AuthenticationManager.java   
/**
 * Register security provider mechanisms
 */
private void registerSaslServers() {
    // create PLAIN SaslServer builder
    PlainSaslServerBuilder plainSaslServerBuilder = new PlainSaslServerBuilder();
    saslMechanisms.put(plainSaslServerBuilder.getMechanismName(), plainSaslServerBuilder);
    // Register given Sasl Server factories
    if (Security
            .insertProviderAt(new BrokerSecurityProvider(BrokerSecurityConstants.PROVIDER_NAME, saslMechanisms), 1)
            == -1) {
        LOGGER.error("Unable to load AMQ security authentication providers.");
    } else {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("AMQ security authentication mechanisms providers successfully registered.");
        }
    }
}
项目:tomcat7    文件:SecurityConfig.java   
/**
 * Set the proper security property
 * @param properties the package.* property.
 */
private final void setSecurityProperty(String properties, String packageList){
    if (System.getSecurityManager() != null){
        String definition = Security.getProperty(properties);
        if( definition != null && definition.length() > 0 ){
            if (packageList.length() > 0) {
                definition = definition + ',' + packageList;
            }
        } else {
            definition = packageList;
        }

        Security.setProperty(properties, definition);
    }
}
项目:ats-framework    文件:SslUtils.java   
/**
 * Registers Bouncy Castle as first security provider before any other providers 
 * coming with the java runtime.
 * </br>ATS calls this method internally when it is supposed to be needed.
 * 
 * </br></br><b>Note:</b> This is a static operation. All working threads will be affected. 
 * The method itself is not thread-safe.
 * 
 * </br></br><b>Note:</b> It does not duplicate if already available.
 */
public static void registerBCProvider() {

    boolean needToInsert = true;
    boolean needToRemove = false;

    Provider bcProvider = new BouncyCastleProvider();
    Provider[] providers = Security.getProviders();

    for (int i = 0; i < providers.length; i++) {
        if (providers[i].getName().equalsIgnoreCase(bcProvider.getName())) {
            if (i == 0) {
                needToInsert = false;
            } else {
                needToRemove = true;
            }
            break;
        }
    }

    if (needToInsert) {
        if (needToRemove) {
            Security.removeProvider(bcProvider.getName());
        }
        Security.insertProviderAt(bcProvider, 1);

        log.info("Bouncy Castle security provider is registered as first in the list of available providers");
    }
}
项目:ats-framework    文件:SslUtils.java   
/**
 * Unregisters Bouncy Castle security provider
 */
public static void unregisterBCProvider() {

    final String bcProviderName = new BouncyCastleProvider().getName();
    Provider[] providers = Security.getProviders();

    for (int i = 0; i < providers.length; i++) {
        if (providers[i].getName().equalsIgnoreCase(bcProviderName)) {
            Security.removeProvider(bcProviderName);
            log.info("Bouncy Castle security provider is unregistered from the list of available providers");
            return;
        }
    }
}
项目:MQTT-Essentials-A-Lightweight-IoT-Protocol    文件:SecurityHelper.java   
public static SSLSocketFactory createSocketFactory(
    final String caCertificateFileName, 
    final String clientCertificateFileName, 
    final String clientKeyFileName) throws Exception
{
    // Creates a TLS socket factory with the given 
    // CA certificate file, client certificate, client key
    // In this case, we are working without a client key password
    final String clientKeyPassword = "";
    try
    {
        Security.addProvider(new BouncyCastleProvider());
        final KeyManager[] keyManagers = createKeyManagerFactory(clientCertificateFileName, clientKeyFileName, clientKeyPassword).getKeyManagers();
        final TrustManager[] trustManagers = createTrustManagerFactory(caCertificateFileName).getTrustManagers();

        // Create the TLS socket factory for the desired TLS version
        final SSLContext context = SSLContext.getInstance(TLS_VERSION);

        context.init(keyManagers, trustManagers, new SecureRandom());
        //context.init(keyManagers, trustManagers, null);

        return context.getSocketFactory();          
    }
    catch (Exception e)
    {
        throw new Exception("I cannot create the TLS socket factory.", e);
    }       
}
项目:openjdk-jdk10    文件:TestEC.java   
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", "");

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

    ProvidersSnapshot snapshot = ProvidersSnapshot.create();
    try {
        main0(args);
    } finally {
        snapshot.restore();
    }
}
项目:jdk8u-jdk    文件:SelfIssuedCert.java   
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");

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


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

    /*
     * Start the tests.
     */
    new SelfIssuedCert();
}
项目:openjdk-jdk10    文件:RevocationChecker.java   
private static RevocationProperties getRevocationProperties() {
    return AccessController.doPrivileged(
        new PrivilegedAction<RevocationProperties>() {
            public RevocationProperties run() {
                RevocationProperties rp = new RevocationProperties();
                String onlyEE = Security.getProperty(
                    "com.sun.security.onlyCheckRevocationOfEECert");
                rp.onlyEE = onlyEE != null
                            && onlyEE.equalsIgnoreCase("true");
                String ocspEnabled = Security.getProperty("ocsp.enable");
                rp.ocspEnabled = ocspEnabled != null
                                 && ocspEnabled.equalsIgnoreCase("true");
                rp.ocspUrl = Security.getProperty("ocsp.responderURL");
                rp.ocspSubject
                    = Security.getProperty("ocsp.responderCertSubjectName");
                rp.ocspIssuer
                    = Security.getProperty("ocsp.responderCertIssuerName");
                rp.ocspSerial
                    = Security.getProperty("ocsp.responderCertSerialNumber");
                rp.crlDPEnabled
                    = Boolean.getBoolean("com.sun.security.enableCRLDP");
                return rp;
            }
        }
    );
}
项目:openjdk-jdk10    文件:FailoverToCRL.java   
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");

    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);

    // Activate OCSP
    Security.setProperty("ocsp.enable", "true");
    System.setProperty("com.sun.security.enableCRLDP", "true");

    // Ensure that the ocsp.responderURL property is not set.
    if (Security.getProperty("ocsp.responderURL") != null) {
        throw new
            Exception("The ocsp.responderURL property must not be set");
    }

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

    try {
        validator.validate(path, params);
    } catch (CertPathValidatorException cpve) {
        if (cpve.getReason() != BasicReason.REVOKED) {
            throw new Exception(
                "unexpected exception, should be a REVOKED CPVE", cpve);
        }
    }
}
项目:openjdk-jdk10    文件:Providers.java   
public static void setAt(Provider p, int pos) throws Exception {
    if (Security.getProvider(p.getName()) != null) {
        Security.removeProvider(p.getName());
    }
    if (Security.insertProviderAt(p, pos) == -1) {
        throw new Exception("cannot setAt");
    }
}
项目:lams    文件:SecurityConfig.java   
/**
 * Set the proper security property
 * @param properties the package.* property.
 */
private final void setSecurityProperty(String properties, String packageList){
    if (System.getSecurityManager() != null){
        String definition = Security.getProperty(properties);
        if( definition != null && definition.length() > 0 ){
            definition += ",";
        }

        Security.setProperty(properties,
            // FIX ME package "javax." was removed to prevent HotSpot
            // fatal internal errors
            definition + packageList);      
    }
}
项目:lazycat    文件:SecurityConfig.java   
/**
 * Set the proper security property
 * 
 * @param properties
 *            the package.* property.
 */
private final void setSecurityProperty(String properties, String packageList) {
    if (System.getSecurityManager() != null) {
        String definition = Security.getProperty(properties);
        if (definition != null && definition.length() > 0) {
            if (packageList.length() > 0) {
                definition = definition + ',' + packageList;
            }
        } else {
            definition = packageList;
        }

        Security.setProperty(properties, definition);
    }
}
项目:jdk8u-jdk    文件:ProviderVersionCheck.java   
public static void main(String arg[]) throws Exception{

        boolean failure = false;

        for (Provider p: Security.getProviders()) {
            System.out.print(p.getName() + " ");
            if (p.getVersion() != 1.8d) {
                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.");
        }
    }
项目:OpenJSharp    文件:GetBooleanSecurityPropertyAction.java   
/**
 * Determines the boolean value of the security property whose name was
 * specified in the constructor.
 *
 * @return the <code>Boolean</code> value of the security property.
 */
public Boolean run() {
    boolean b = false;
    try {
        String value = Security.getProperty(theProp);
        b = (value != null) && value.equalsIgnoreCase("true");
    } catch (NullPointerException e) {}
    return b;
}
项目:OpenJSharp    文件:TrustManagerFactory.java   
/**
 * Obtains the default TrustManagerFactory algorithm name.
 *
 * <p>The default TrustManager can be changed at runtime by setting
 * the value of the {@code ssl.TrustManagerFactory.algorithm}
 * security property to the desired algorithm name.
 *
 * @see java.security.Security security properties
 * @return the default algorithm name as specified by the
 * {@code ssl.TrustManagerFactory.algorithm} security property, or an
 * implementation-specific default if no such property exists.
 */
public final static String getDefaultAlgorithm() {
    String type;
    type = AccessController.doPrivileged(new PrivilegedAction<String>() {
        @Override
        public String run() {
            return Security.getProperty(
                "ssl.TrustManagerFactory.algorithm");
        }
    });
    if (type == null) {
        type = "SunX509";
    }
    return type;
}
项目:jdk8u-jdk    文件:IPIdentities.java   
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");

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

    /*
     * Start the tests.
     */
    new IPIdentities();
}
项目:openjdk-jdk10    文件:SecurityProviderModularTest.java   
/**
 * Create new provider entry through java.security file extension.
 * New provider entry will be the last entry inside the JRE.
 */
private static void createJavaSecurityFileExtn(boolean useName) {
    int insertAt = Security.getProviders().length + 1;
    String provider = (useName ? "TestProvider" : P_TYPE);
    try {
        Files.write(SEC_FILE, String.format("security.provider.%s=%s",
                insertAt, provider).getBytes("UTF-8"));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    System.out.printf("Security property file created at: %s with value:"
            + " %s%n", SEC_FILE, provider);
}
项目:Myst    文件:MPCTestClient.java   
static void prepareECCurve(MPCGlobals mpcParams) {
    mpcParams.p = new BigInteger(Util.bytesToHex(SecP256r1.p), 16);
    mpcParams.a = new BigInteger(Util.bytesToHex(SecP256r1.a), 16);
    mpcParams.b = new BigInteger(Util.bytesToHex(SecP256r1.b), 16);
    mpcParams.curve = new ECCurve.Fp(mpcParams.p, mpcParams.a, mpcParams.b);
    mpcParams.G = Util.ECPointDeSerialization(mpcGlobals.curve, SecP256r1.G, 0);
    mpcParams.n = new BigInteger(Util.bytesToHex(SecP256r1.r), 16); // also noted as r
    mpcParams.ecSpec = new ECParameterSpec(mpcParams.curve, mpcParams.G, mpcParams.n);
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
}
项目:openjdk-jdk10    文件:OneKDC.java   
/**
 * Creates the KDC and starts it.
 * @param etype Encryption type, null if not specified
 * @throws java.lang.Exception if there's anything wrong
 */
public OneKDC(String etype) throws Exception {
    super(REALM, KDCHOST, 0, true);
    addPrincipal(USER, PASS);
    addPrincipal(USER2, PASS2);
    addPrincipalRandKey("krbtgt/" + REALM);
    addPrincipalRandKey(SERVER);
    addPrincipalRandKey(BACKEND);

    String extraConfig = "";
    if (etype != null) {
        extraConfig += "default_tkt_enctypes=" + etype
                + "\ndefault_tgs_enctypes=" + etype;
        if (etype.startsWith("des")) {
            extraConfig += "\nallow_weak_crypto = true";
        }
    }
    KDC.saveConfig(KRB5_CONF, this,
            "forwardable = true",
            "default_keytab_name = " + KTAB,
            extraConfig);
    System.setProperty("java.security.krb5.conf", KRB5_CONF);
    // Whatever krb5.conf had been loaded before, we reload ours now.
    Config.refresh();

    writeKtab(KTAB);
    Security.setProperty("auth.login.defaultCallbackHandler",
            "OneKDC$CallbackForClient");
}
项目:jdk8u-jdk    文件:DisableRevocation.java   
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");

    CertPathBuilder builder = CertPathBuilder.getInstance("PKIX");

    X509CertSelector selector = generateSelector(args[0]);

    Set<TrustAnchor> anchors = generateTrustAnchors();
    CertStore certs = generateCertificateStore();


    PKIXBuilderParameters params =
            new PKIXBuilderParameters(anchors, selector);
    params.addCertStore(certs);
    params.setRevocationEnabled(false);
    params.setDate(new Date(109, 7, 1));   // 2009-07-01
    Security.setProperty("ocsp.enable", "false");
    System.setProperty("com.sun.security.enableCRLDP", "false");

    PKIXCertPathBuilderResult result =
            (PKIXCertPathBuilderResult)builder.build(params);

    if (!match(args[0], result.getCertPath().getCertificates().get(0))) {
        throw new Exception("unexpected certificate");
    }
}
项目:openjdk-jdk10    文件:S4U2selfAsServerGSS.java   
public static void main(String[] args) throws Exception {
    Oid mech;
    if (args[0].equals("spnego")) {
        mech = GSSUtil.GSS_SPNEGO_MECH_OID;
    } else if (args[0].contains("krb5")) {
        mech = GSSUtil.GSS_KRB5_MECH_OID;
    } else {
        throw new Exception("Unknown mech");
    }

    OneKDC kdc = new OneKDC(null);
    kdc.writeJAASConf();
    kdc.setOption(KDC.Option.PREAUTH_REQUIRED, false);
    Map<String,List<String>> map = new HashMap<>();
    map.put(OneKDC.SERVER + "@" + OneKDC.REALM, Arrays.asList(
            new String[]{OneKDC.SERVER + "@" + OneKDC.REALM}));
    kdc.setOption(KDC.Option.ALLOW_S4U2PROXY, map);
    kdc.setOption(KDC.Option.ALLOW_S4U2SELF, Arrays.asList(
            new String[]{OneKDC.SERVER + "@" + OneKDC.REALM}));

    Context s, b;
    System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");
    System.setProperty("java.security.auth.login.config", OneKDC.JAAS_CONF);
    File f = new File(OneKDC.JAAS_CONF);
    FileOutputStream fos = new FileOutputStream(f);
    fos.write((
            "com.sun.security.jgss.krb5.accept {\n" +
            "    com.sun.security.auth.module.Krb5LoginModule required\n" +
            "    principal=\"" + OneKDC.SERVER + "\"\n" +
            "    useKeyTab=true\n" +
            "    storeKey=true;\n};\n"
            ).getBytes());
    fos.close();
    Security.setProperty("auth.login.defaultCallbackHandler", "OneKDC$CallbackForClient");
    s = Context.fromThinAir();
    b = Context.fromThinAir();
    s.startAsServer(mech);

    Context p = s.impersonate(OneKDC.USER);

    p.startAsClient(OneKDC.SERVER, mech);
    b.startAsServer(mech);
    Context.handshake(p, b);

    String n1 = p.x().getSrcName().toString().split("@")[0];
    String n2 = b.x().getSrcName().toString().split("@")[0];
    if (!n1.equals(OneKDC.USER) || !n2.equals(OneKDC.USER)) {
        throw new Exception("Delegation failed");
    }
}
项目:jdk8u-jdk    文件:KeyManagerFactory.java   
/**
 * Obtains the default KeyManagerFactory algorithm name.
 *
 * <p>The default algorithm can be changed at runtime by setting
 * the value of the {@code ssl.KeyManagerFactory.algorithm}
 * security property to the desired algorithm name.
 *
 * @see java.security.Security security properties
 * @return the default algorithm name as specified by the
 *          {@code ssl.KeyManagerFactory.algorithm} security property, or an
 *          implementation-specific default if no such property exists.
 */
public final static String getDefaultAlgorithm() {
    String type;
    type = AccessController.doPrivileged(new PrivilegedAction<String>() {
        @Override
        public String run() {
            return Security.getProperty(
                "ssl.KeyManagerFactory.algorithm");
        }
    });
    if (type == null) {
        type = "SunX509";
    }
    return type;
}
项目:openjdk-jdk10    文件:UseSystemClassLoader.java   
public static void main(String[] args) throws Exception {

        Type t = Type.valueOf(args[0]);

        // We can't use the jtreg java.security.policy option to specify
        // the policy file because that causes the default JDK policy provider
        // to be set and once set, we cannot change it. So, instead we use the
        // policy.url security property.
        File file = new File(System.getProperty("test.src"), "test.policy");
        URL policyURL = file.toURI().toURL();
        Security.setProperty("policy.url.1", policyURL.toString());

        switch (t) {
            case CUSTOM:
                // Set policy.provider to our custom policy provider
                Security.setProperty("policy.provider", "CustomPolicy");
                break;
            case NOT_AVAIL:
                // Set policy.provider to a non-existent policy provider
                Security.setProperty("policy.provider", "NonExistentPolicy");
                break;
            case DEFAULT:
                // Don't set policy.provider (leave default)
                break;
            case NOT_SET:
                // Set policy.provider to empty string
                Security.setProperty("policy.provider", "");
                break;
        }

        System.setSecurityManager(new SecurityManager());
        Policy p = Policy.getPolicy();
        switch (t) {
            case CUSTOM:
                // check that the custom policy provider has been set
                if (!(p instanceof CustomPolicy)) {
                    throw new Exception("CustomPolicy was not set");
                }
                break;
            case NOT_AVAIL:
            case DEFAULT:
            case NOT_SET:
                // check that the default policy provider has been set
                if (!(p instanceof sun.security.provider.PolicyFile)) {
                    throw new Exception("default provider was not set");
                }
                break;
        }
    }
项目:springboot-shiro-cas-mybatis    文件:WsFederationHelper.java   
private Credential getEncryptionCredential(final WsFederationConfiguration config) {
    try {
        // This will need to contain the private keypair in PEM format
        final BufferedReader br = new BufferedReader(new InputStreamReader(config.getEncryptionPrivateKey().getInputStream()));
        Security.addProvider(new BouncyCastleProvider());
        final PEMParser pemParser = new PEMParser(br);

        final Object privateKeyPemObject = pemParser.readObject();
        final JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider(new BouncyCastleProvider());

        final KeyPair kp;
        if (privateKeyPemObject instanceof PEMEncryptedKeyPair) {
            final PEMEncryptedKeyPair ckp = (PEMEncryptedKeyPair) privateKeyPemObject;
            final PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder()
                    .build(config.getEncryptionPrivateKeyPassword().toCharArray());
            kp = converter.getKeyPair(ckp.decryptKeyPair(decProv));
        } else {
            kp = converter.getKeyPair((PEMKeyPair) privateKeyPemObject);
        }

        final X509CertParser certParser = new X509CertParser();
        // This is the certificate shared with ADFS in DER format, i.e certificate.crt
        certParser.engineInit(config.getEncryptionCertificate().getInputStream());
        final X509CertificateObject cert = (X509CertificateObject) certParser.engineRead();
        return new BasicX509Credential(cert, kp.getPrivate());
    } catch (final Exception e) {
        throw Throwables.propagate(e);
    }
}