本文整理汇总了Java中java.security.Security类的典型用法代码示例。如果您正苦于以下问题:Java Security类的具体用法?Java Security怎么用?Java Security使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Security类属于java.security包,在下文中一共展示了Security类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: main
import java.security.Security; //导入依赖的package包/类
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);
}
}
示例2: main
import java.security.Security; //导入依赖的package包/类
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");
}
}
}
}
}
示例3: main
import java.security.Security; //导入依赖的package包/类
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");
}
}
示例4: xRealmAuth
import java.security.Security; //导入依赖的package包/类
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);
}
示例5: main
import java.security.Security; //导入依赖的package包/类
@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());
}
}
示例6: a
import java.security.Security; //导入依赖的package包/类
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);
}
示例7: run
import java.security.Security; //导入依赖的package包/类
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);
}
}
}
}
}
示例8: printProviders
import java.security.Security; //导入依赖的package包/类
/**
* 打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());
}
}
示例9: runTest
import java.security.Security; //导入依赖的package包/类
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");
}
示例10: main
import java.security.Security; //导入依赖的package包/类
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");
}
}
示例11: main
import java.security.Security; //导入依赖的package包/类
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();
}
示例12: crypt
import java.security.Security; //导入依赖的package包/类
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);
}
示例13: main
import java.security.Security; //导入依赖的package包/类
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);
}
}
示例14: main
import java.security.Security; //导入依赖的package包/类
/**
* 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 ****");
}
示例15: main
import java.security.Security; //导入依赖的package包/类
public static void main(String[] args) throws Exception {
TestJCAProvider d = new TestJCAProvider();
// Add dynamically the desired provider
Security.addProvider(new PaillierProvider());
/////////////////////////////////////////////////////////////////////
KeyPairGenerator kpg = KeyPairGenerator.getInstance("Paillier");
kpg.initialize(32);
KeyPair keyPair = kpg.generateKeyPair();
PublicKey pubKey = keyPair.getPublic();
PrivateKey privKey = keyPair.getPrivate();
final Cipher cipher = Cipher.getInstance("Paillier");
final Cipher cipherHP = Cipher.getInstance("PaillierHP");
System.out.println("The Paillier public key through Generator is \n"+keyPair.toString());
System.out.println("The Paillier public key is \n"+keyPair.getPublic().toString());
System.out.println("The Paillier private key is \n"+keyPair.getPrivate().toString());
String plainText = "101";
String plaintext1 = "101";
// get the n
String delims = "[,]";
String[] keyComponents = pubKey.toString().split(delims);
String keyComponent = "";
for (String keyComponent2 : keyComponents) {
if (keyComponent2.startsWith("n")) {
keyComponent = keyComponent2.substring(2);// ignoring 'n:' or 'r:'
}
}
BigInteger n = new BigInteger(keyComponent);
BigInteger first = new BigInteger(plainText);
BigInteger second = new BigInteger(plaintext1);
BigInteger n2 = n.multiply(n);
// encrypt
BigInteger codedBytes = d.encrypt(first.toByteArray(), pubKey,cipherHP);
BigInteger codedBytes12 = d.encrypt(second.toByteArray(), pubKey,cipherHP);
//product
BigInteger product = codedBytes.multiply(codedBytes12);
// product mod n^2
BigInteger tallyProduct = product.mod(n2);
System.out.println(" Product mod n^2: "+tallyProduct);
d.decrypt(tallyProduct.toByteArray(), privKey,cipherHP);
d.decrypt(codedBytes.toByteArray(),privKey,cipherHP);
d.decrypt(codedBytes12.toByteArray(),privKey,cipherHP);
//////////////////////////////BLOCK EXAMPLE/////////////////////////////////
String plainTextBlock = "This Provider working correctly and its safe 10000000000000000011000000000000000001";
System.out.println("This is the message which will be encrypted: " + plainTextBlock);
// encrypt
byte[] codedBytesBlock = d.encryptBlock(plainTextBlock.getBytes(), pubKey,cipher);
String codedMessageBlock = new String(codedBytesBlock);
String codedMessageBlockInHEX = formatingHexRepresentation(codedBytesBlock);
System.out.println("\n" + "ENCRYPTED : \n" + codedMessageBlock);
System.out.println("\n" + "ENCRYPTED in HEX: \n" + codedMessageBlockInHEX);
// decrypt
byte[] encodedBytesBlock = d.decryptBlock(codedMessageBlock, privKey,cipher);
String encodedMessageBlock = new String(encodedBytesBlock);
System.out.println("\n" + "DECRYPTED: \n" + encodedMessageBlock);
}