本文整理汇总了Java中java.security.KeyStore类的典型用法代码示例。如果您正苦于以下问题:Java KeyStore类的具体用法?Java KeyStore怎么用?Java KeyStore使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
KeyStore类属于java.security包,在下文中一共展示了KeyStore类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: createNewKey
import java.security.KeyStore; //导入依赖的package包/类
/**
* Create a new key in the Keystore
*/
private void createNewKey(){
try {
final KeyStore keyStore = KeyStore.getInstance(AndroidKeyStore);
keyStore.load(null);
final KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, AndroidKeyStore);
// Build one key to be used for encrypting and decrypting the file
keyGenerator.init(
new KeyGenParameterSpec.Builder(ALIAS,
KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.build());
keyGenerator.generateKey();
Log.i(TAG, "Key created in Keystore");
}catch (KeyStoreException | InvalidAlgorithmParameterException | NoSuchProviderException | NoSuchAlgorithmException | CertificateException | IOException kS){
Log.e(TAG, kS.getMessage());
}
}
示例2: if
import java.security.KeyStore; //导入依赖的package包/类
private static ServerSocketFactory getServerSocketFactory
(boolean useSSL) throws Exception {
if (useSSL) {
SSLServerSocketFactory ssf = null;
// set up key manager to do server authentication
SSLContext ctx;
KeyManagerFactory kmf;
KeyStore ks;
char[] passphrase = passwd.toCharArray();
ctx = SSLContext.getInstance("TLS");
kmf = KeyManagerFactory.getInstance("SunX509");
ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream(System.getProperty(
"javax.net.ssl.keyStore")), passphrase);
kmf.init(ks, passphrase);
ctx.init(kmf.getKeyManagers(), null, null);
ssf = ctx.getServerSocketFactory();
return ssf;
} else {
return ServerSocketFactory.getDefault();
}
}
示例3: testLoginJwtValidity
import java.security.KeyStore; //导入依赖的package包/类
/**
* Tests the JWT we get back from the auth service is valid. We test the JWT to make sure it was
* signed correctly.
*
* <p>We do not validate other things, like the issued at time, expired time, etc.
*
* <p>The test case has access to the keystore that the server should have used to sign the JWT.
*/
@Test
public void testLoginJwtValidity() throws Exception {
// Get the JWT from the auth service.
Response response = processRequest(authServiceURL, "GET", null, null);
assertEquals(
"HTTP response code should have been " + Status.OK.getStatusCode() + ".",
Status.OK.getStatusCode(),
response.getStatus());
String authHeader = response.getHeaderString("Authorization");
// Open the keystore that the server should have used to sign the JWT.
KeyStore ks = KeyStore.getInstance("JCEKS");
InputStream ksStream = this.getClass().getResourceAsStream("/keystore.jceks");
char[] password = new String("secret").toCharArray();
ks.load(ksStream, password);
java.security.cert.Certificate cert = ks.getCertificate("default");
PublicKey publicKey = cert.getPublicKey();
// Make sure it's valid. Use the server's public key to check.
new JWTVerifier().validateJWT(authHeader, publicKey);
}
示例4: getSSLSocketFactory
import java.security.KeyStore; //导入依赖的package包/类
/**
* 获得SSLSocektFactory
*
* @param password 密码
* @param keyStorePath 密钥库路径
* @param trustStorePath 信任库路径
* @return SSLSocketFactory
* @throws Exception
*/
private static SSLSocketFactory getSSLSocketFactory(String password, String keyStorePath, String trustStorePath)
throws Exception {
// 实例化密钥库
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
// 获得密钥库
KeyStore keyStore = getKeyStore(keyStorePath, password);
// 初始化密钥工厂
keyManagerFactory.init(keyStore, password.toCharArray());
// 实例化信任库
TrustManagerFactory trustManagerFactory = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
// 获得信任库
KeyStore trustStore = getKeyStore(trustStorePath, password);
// 初始化信任库
trustManagerFactory.init(trustStore);
// 实例化SSL上下文
SSLContext ctx = SSLContext.getInstance(PROTOCOL);
// 初始化SSL上下文
ctx.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
// 获得SSLSocketFactory
return ctx.getSocketFactory();
}
示例5: getKeyStore
import java.security.KeyStore; //导入依赖的package包/类
/**
* Returns a standard keystore which holds the respective credentials (private key and certificate chain).
*
* @param keyStoreIS The input stream of the keystore
* @param keyStorePassword The password which protects the keystore
* @param keyStoreType The type of the keystore, either "jks" or "pkcs12"
* @return The respective keystore
*/
private static KeyStore getKeyStore(InputStream keyStoreIS, String keyStorePassword, String keyStoreType) {
KeyStore keyStore = null;
try {
keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(keyStoreIS, keyStorePassword.toCharArray());
keyStoreIS.close();
return keyStore;
} catch (KeyStoreException | NoSuchAlgorithmException | CertificateException |
IOException | NullPointerException e) {
getLogger().error(e.getClass().getSimpleName() + " occurred while trying to load keystore", e);
}
return null;
}
示例6: init
import java.security.KeyStore; //导入依赖的package包/类
public DefaultX509TrustManager init() throws IOException {
try {
final TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
factory.init(KeyStore.getInstance(KeyStore.getDefaultType()));
final TrustManager[] trustmanagers = factory.getTrustManagers();
if(trustmanagers.length == 0) {
throw new NoSuchAlgorithmException("SunX509 trust manager not supported");
}
system = (javax.net.ssl.X509TrustManager) trustmanagers[0];
}
catch(NoSuchAlgorithmException | KeyStoreException e) {
log.error(String.format("Initialization of trust store failed. %s", e.getMessage()));
throw new IOException(e);
}
return this;
}
示例7: createRequest
import java.security.KeyStore; //导入依赖的package包/类
/**
* 创建Http/Https请求对象
* @author Rocye
* @param url 请求地址
* @param method 请求方式:GET/POST
* @param certPath 证书路径
* @param certPass 证书密码
* @param useCert 是否需要证书
* @return Https连接
* @throws Exception 任何异常
* @version 2017.11.14
*/
private HttpsURLConnection createRequest(String url, String method, String certPath, String certPass, boolean useCert) throws Exception{
URL realUrl = new URL(url);
HttpsURLConnection connection = (HttpsURLConnection)realUrl.openConnection();
//设置证书
if(useCert){
KeyStore clientStore = KeyStore.getInstance("PKCS12");
InputStream inputStream = new FileInputStream(certPath);
clientStore.load(inputStream, certPass.toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(clientStore, certPass.toCharArray());
KeyManager[] kms = kmf.getKeyManagers();
SSLContext sslContext = SSLContext.getInstance("TLSv1");
sslContext.init(kms, null, new SecureRandom());
connection.setSSLSocketFactory(sslContext.getSocketFactory());
}
// 设置通用的请求属性
connection.setRequestProperty("Accept", "*/*");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setConnectTimeout(this.connectTimeout);
connection.setReadTimeout(this.readTimeout);
if("POST".equals(method)){
// 发送POST请求必须设置如下两行
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false); // 忽略缓存
connection.setRequestMethod("POST");
}
return connection;
}
示例8: PKIXParameters
import java.security.KeyStore; //导入依赖的package包/类
/**
* Creates an instance of {@code PKIXParameters} that
* populates the set of most-trusted CAs from the trusted
* certificate entries contained in the specified {@code KeyStore}.
* Only keystore entries that contain trusted {@code X509Certificates}
* are considered; all other certificate types are ignored.
*
* @param keystore a {@code KeyStore} from which the set of
* most-trusted CAs will be populated
* @throws KeyStoreException if the keystore has not been initialized
* @throws InvalidAlgorithmParameterException if the keystore does
* not contain at least one trusted certificate entry
* @throws NullPointerException if the keystore is {@code null}
*/
public PKIXParameters(KeyStore keystore)
throws KeyStoreException, InvalidAlgorithmParameterException
{
if (keystore == null)
throw new NullPointerException("the keystore parameter must be " +
"non-null");
Set<TrustAnchor> hashSet = new HashSet<TrustAnchor>();
Enumeration<String> aliases = keystore.aliases();
while (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
if (keystore.isCertificateEntry(alias)) {
Certificate cert = keystore.getCertificate(alias);
if (cert instanceof X509Certificate)
hashSet.add(new TrustAnchor((X509Certificate)cert, null));
}
}
setTrustAnchors(hashSet);
this.unmodInitialPolicies = Collections.<String>emptySet();
this.certPathCheckers = new ArrayList<PKIXCertPathChecker>();
this.certStores = new ArrayList<CertStore>();
}
示例9: compareKeyStore
import java.security.KeyStore; //导入依赖的package包/类
private void compareKeyStore(KeyStore a, KeyStore b, String inKeyPass,
String outKeyPass, int keyStoreSize) throws Exception {
if (a.size() != keyStoreSize || b.size() != keyStoreSize) {
throw new RuntimeException("size not match or size not equal to "
+ keyStoreSize);
}
Enumeration<String> eA = a.aliases();
while (eA.hasMoreElements()) {
String aliasA = eA.nextElement();
if (!b.containsAlias(aliasA)) {
throw new RuntimeException("alias not match for alias:"
+ aliasA);
}
compareKeyEntry(a, b, inKeyPass, outKeyPass, aliasA);
}
}
示例10: verifyCRL
import java.security.KeyStore; //导入依赖的package包/类
private static String verifyCRL(KeyStore ks, CRL crl)
throws Exception {
X509CRLImpl xcrl = (X509CRLImpl)crl;
X500Principal issuer = xcrl.getIssuerX500Principal();
for (String s: e2i(ks.aliases())) {
Certificate cert = ks.getCertificate(s);
if (cert instanceof X509Certificate) {
X509Certificate xcert = (X509Certificate)cert;
if (xcert.getSubjectX500Principal().equals(issuer)) {
try {
((X509CRLImpl)crl).verify(cert.getPublicKey());
return s;
} catch (Exception e) {
}
}
}
}
return null;
}
示例11: initCipher
import java.security.KeyStore; //导入依赖的package包/类
/**
* Initialize the {@link Cipher} instance with the created key in the {@link #createKey()}
* method.
*
* @return {@code true} if initialization is successful, {@code false} if the lock screen has
* been disabled or reset after the key was generated, or if a fingerprint got enrolled after
* the key was generated.
*/
private boolean initCipher() {
try {
if (mKeyStore == null) {
mKeyStore = KeyStore.getInstance("AndroidKeyStore");
}
createKey();
mKeyStore.load(null);
SecretKey key = (SecretKey) mKeyStore.getKey(KEY_NAME, null);
mCipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
mCipher.init(Cipher.ENCRYPT_MODE, key);
return true;
} catch (NoSuchPaddingException | KeyStoreException | CertificateException | UnrecoverableKeyException | IOException
| NoSuchAlgorithmException | InvalidKeyException e) {
return false;
}
}
示例12: getTrustedSigner
import java.security.KeyStore; //导入依赖的package包/类
/**
* Locates a signer for a given certificate from a given keystore and
* returns the signer's certificate.
* @param cert the certificate whose signer is searched, not null
* @param ks the keystore to search with, not null
* @return <code>cert</code> itself if it's already inside <code>ks</code>,
* or a certificate inside <code>ks</code> who signs <code>cert</code>,
* or null otherwise.
*/
private static Certificate getTrustedSigner(Certificate cert, KeyStore ks)
throws Exception {
if (ks.getCertificateAlias(cert) != null) {
return cert;
}
for (Enumeration<String> aliases = ks.aliases();
aliases.hasMoreElements(); ) {
String name = aliases.nextElement();
Certificate trustedCert = ks.getCertificate(name);
if (trustedCert != null) {
try {
cert.verify(trustedCert.getPublicKey());
return trustedCert;
} catch (Exception e) {
// Not verified, skip to the next one
}
}
}
return null;
}
示例13: makeSSLSocketFactory
import java.security.KeyStore; //导入依赖的package包/类
/**
* Creates an SSLSocketFactory for HTTPS. Pass a KeyStore resource with your
* certificate and passphrase
*/
public static SSLServerSocketFactory makeSSLSocketFactory(String keyAndTrustStoreClasspathPath, char[] passphrase) throws IOException {
try {
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream keystoreStream = NanoHTTPD.class.getResourceAsStream(keyAndTrustStoreClasspathPath);
if (keystoreStream == null) {
throw new IOException("Unable to load keystore from classpath: " + keyAndTrustStoreClasspathPath);
}
keystore.load(keystoreStream, passphrase);
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keystore, passphrase);
return makeSSLSocketFactory(keystore, keyManagerFactory);
} catch (Exception e) {
throw new IOException(e.getMessage());
}
}
示例14: dumpTrustedCerts
import java.security.KeyStore; //导入依赖的package包/类
public void dumpTrustedCerts() {
try {
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory
.getDefaultAlgorithm());
tmf.init((KeyStore) null);
X509TrustManager xtm = (X509TrustManager) tmf.getTrustManagers()[0];
StringBuffer buff = new StringBuffer();
for (X509Certificate cert : xtm.getAcceptedIssuers()) {
String certStr = "S:" + cert.getSubjectDN().getName() + "\nI:"
+ cert.getIssuerDN().getName();
Log.d(TAG, certStr);
buff.append(certStr + "\n\n");
}
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
}
示例15: TrustStoreController
import java.security.KeyStore; //导入依赖的package包/类
/**
* This Initializes the TrustStoreController.
*/
public TrustStoreController(Dialog ownerDialog, File trustStoreFile, String trustStorePassword, boolean edit) {
this.ownerDialog = ownerDialog;
try {
trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
if (trustStoreFile != null && trustStorePassword != null) {
if(edit){
openTrustStore(trustStoreFile, trustStorePassword);
} else {
createTrustStore(trustStoreFile, trustStorePassword);
}
}
} catch (KeyStoreException e) {
e.printStackTrace();
}
}