当前位置: 首页>>代码示例>>Java>>正文


Java KeyStore类代码示例

本文整理汇总了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());
  }
}
 
开发者ID:Esri,项目名称:mapbook-android,代码行数:25,代码来源:CredentialCryptographer.java

示例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();
    }
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:26,代码来源:ClientHelloRead.java

示例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);
}
 
开发者ID:OpenLiberty,项目名称:sample-acmegifts,代码行数:30,代码来源:AuthResourceTest.java

示例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();

}
 
开发者ID:iBase4J,项目名称:iBase4J-Common,代码行数:33,代码来源:HTTPSPKCSCoder.java

示例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;
}
 
开发者ID:V2GClarity,项目名称:RISE-V2G,代码行数:24,代码来源:SecurityUtils.java

示例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;
}
 
开发者ID:iterate-ch,项目名称:cyberduck,代码行数:17,代码来源:DefaultX509TrustManager.java

示例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;
  }
 
开发者ID:rocye,项目名称:wx-idk,代码行数:44,代码来源:HttpsRequestTools.java

示例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>();
}
 
开发者ID:SunburstApps,项目名称:OpenJSharp,代码行数:36,代码来源:PKIXParameters.java

示例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);
    }
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:20,代码来源:ConvertP12Test.java

示例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;
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:20,代码来源:Main.java

示例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;
    }
}
 
开发者ID:sfilmak,项目名称:MakiLite,代码行数:25,代码来源:FingerprintUiHelper.java

示例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;
}
 
开发者ID:SunburstApps,项目名称:OpenJSharp,代码行数:30,代码来源:Main.java

示例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());
    }
}
 
开发者ID:Webtrekk,项目名称:webtrekk-android-sdk,代码行数:22,代码来源:NanoHTTPD.java

示例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);
	}
}
 
开发者ID:CactusSoft,项目名称:zabbkit-android,代码行数:18,代码来源:SSLManager.java

示例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();
	}
}
 
开发者ID:EnFlexIT,项目名称:AgentWorkbench,代码行数:19,代码来源:TrustStoreController.java


注:本文中的java.security.KeyStore类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。