下面列出了怎么用java.security.Security的API类实例代码及写法,或者点击链接到github查看源代码。
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);
}
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);
}
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
}
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();
}
@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());
}
@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());
}
@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());
}
}
/**
* 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);
}
}
/**
* 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);
}
/** 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);
}
}
}
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);
}
}
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);
}
}
}
}
}
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");
}
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();
}
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
);
}
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);
}
}
}
}
}
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);
}
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 Identities();
}
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 DNSIdentities();
}
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");
}
}
/**
* Creates an instance of the nifi sensitive property encryptor. Validates
* that the encryptor is actually working.
*
* @param niFiProperties properties
* @return encryptor
* @throws EncryptionException if any issues arise initializing or
* validating the encryptor
*/
public static StringEncryptor createEncryptor(final NiFiProperties niFiProperties) throws EncryptionException {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
final String sensitivePropAlgorithmVal = niFiProperties.getProperty(NF_SENSITIVE_PROPS_ALGORITHM);
final String sensitivePropProviderVal = niFiProperties.getProperty(NF_SENSITIVE_PROPS_PROVIDER);
final String sensitivePropValueNifiPropVar = niFiProperties.getProperty(NF_SENSITIVE_PROPS_KEY, DEFAULT_SENSITIVE_PROPS_KEY);
if (StringUtils.isBlank(sensitivePropAlgorithmVal)) {
throw new EncryptionException(NF_SENSITIVE_PROPS_ALGORITHM + "must bet set");
}
if (StringUtils.isBlank(sensitivePropProviderVal)) {
throw new EncryptionException(NF_SENSITIVE_PROPS_PROVIDER + "must bet set");
}
if (StringUtils.isBlank(sensitivePropValueNifiPropVar)) {
throw new EncryptionException(NF_SENSITIVE_PROPS_KEY + "must bet set");
}
final StringEncryptor nifiEncryptor;
try {
nifiEncryptor = new StringEncryptor(sensitivePropAlgorithmVal, sensitivePropProviderVal, sensitivePropValueNifiPropVar);
//test that we can infact encrypt and decrypt something
if (!nifiEncryptor.decrypt(nifiEncryptor.encrypt(TEST_PLAINTEXT)).equals(TEST_PLAINTEXT)) {
throw new EncryptionException("NiFi property encryptor does appear to be working - decrypt/encrypt return invalid results");
}
} catch (final EncryptionInitializationException | EncryptionOperationNotPossibleException ex) {
throw new EncryptionException("Cannot initialize sensitive property encryptor", ex);
}
return nifiEncryptor;
}
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");
if (debug)
System.setProperty("javax.net.debug", "all");
/*
* Start the tests.
*/
new RSAExport();
}
/**
* 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;
}
protected void startSMTP(String factory) {
wiser = new Wiser();
wiser.setPort(1587);
wiser.getServer().setAuthenticationHandlerFactory(new AuthenticationHandlerFactory() {
/*
* AUTH PLAIN handler which returns success on any string
*/
@Override
public List<String> getAuthenticationMechanisms() {
return Arrays.asList("PLAIN");
}
@Override
public AuthenticationHandler create() {
return new AuthenticationHandler() {
@Override
public String auth(final String clientInput) throws RejectException {
log.info(clientInput);
return null;
}
@Override
public Object getIdentity() {
return "username";
}
};
}
});
Security.setProperty("ssl.SocketFactory.provider", factory);
wiser.getServer().setEnableTLS(true);
wiser.start();
}
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");
}
}
public EncrypDES() throws NoSuchAlgorithmException, NoSuchPaddingException {
Security.addProvider(new com.sun.crypto.provider.SunJCE());
// 实例化支持DES算法的密钥生成器(算法名称命名需按规定,否则抛出异常)
keygen = KeyGenerator.getInstance("DES");
// 生成密钥
deskey = keygen.generateKey();
// 生成Cipher对象,指定其支持的DES算法
c = Cipher.getInstance("DES");
}
public static void main(String[] args)
throws Exception {
Security.setProperty("krb5.kdc.bad.policy", "tryLast");
BadKdc.go(
"121212222222(32){2,4}", // 1 2
"(32){2,4}", // 1 2
// refresh
"121212222222(32){2,4}", // 1 2
// k3 off k2 on
"323232121212(22){2,4}", // 1 3
// k1 on
"(22){2,4}" // 1 3
);
}
public static void main(String[] args)
throws Exception {
Security.setProperty("krb5.kdc.bad.policy", "tryLess:2,1000");
BadKdc.go(
"121212222222(32){1,2}11112121(32){1,2}", // 1 2
"11112121(32){1,2}11112121(32){1,2}", // 1 2
// refresh
"121212222222(32){1,2}11112121(32){1,2}", // 1 2
// k3 off k2 on
"1111(21){1,2}1111(22){1,2}", // 1
// k1 on
"(11){1,2}(12){1,2}" // empty
);
}
public static void main(String[] args) throws Exception {
try {
Provider[] providers1 = Security.getProviders();
System.out.println("Amount of providers1: " + providers1.length);
Provider[] providers2 = Security.getProviders(serviceAlgFilter);
System.out.println("Amount of providers2: " + providers2.length);
Map<String, String> filter = new HashMap<String, String>();
filter.put(serviceAlgFilter, "");
Provider[] providers3 = Security.getProviders(filter);
System.out.println("Amount of providers3: " + providers3.length);
Provider[] emptyProv1 = Security.getProviders(emptyServAlgFilter);
if (emptyProv1 != null) {
throw new RuntimeException("Empty Filter returned: " +
emptyProv1.length + " providers");
}
System.out.println("emptyProv1 is empty as expected");
Map<String, String> emptyFilter = new HashMap<String, String>();
emptyFilter.put(emptyServAlgFilter, "");
Provider[] emptyProv2 = Security.getProviders(emptyFilter);
if (emptyProv2 != null) {
throw new RuntimeException("Empty Filter returned: " +
emptyProv2.length + " providers");
}
System.out.println("emptyProv2 is empty as expected");
} catch(ExceptionInInitializerError e) {
e.printStackTrace(System.out);
throw new RuntimeException("Provider initialization error due to "
+ e.getCause());
}
System.out.println("Test passed");
}
/**
* Whirlpool加密
*
* @param data
* 待加密数据
*
* @return byte[] 消息摘要
*
* @throws Exception
*/
public static byte[] encodeWhirlpool(byte[] data) throws NoSuchAlgorithmException {
// 加入BouncyCastleProvider支持
Security.addProvider(new BouncyCastleProvider());
// 初始化MessageDigest
MessageDigest md = MessageDigest.getInstance("Whirlpool");
// 执行消息摘要
return md.digest(data);
}