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


Java KeyStore.containsAlias方法代码示例

本文整理汇总了Java中java.security.KeyStore.containsAlias方法的典型用法代码示例。如果您正苦于以下问题:Java KeyStore.containsAlias方法的具体用法?Java KeyStore.containsAlias怎么用?Java KeyStore.containsAlias使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.security.KeyStore的用法示例。


在下文中一共展示了KeyStore.containsAlias方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: createKeys

import java.security.KeyStore; //导入方法依赖的package包/类
/**
 * Creates a public and private key and stores it using the AndroidKeyStore,
 * so that only this application will be able to access the keys.
 */
@SuppressWarnings("deprecation")
public void createKeys() throws Exception {
    KeyStore keyStore = KeyStore.getInstance(ANDROID_KEY_STORE);
    keyStore.load(null);
    if (keyStore.containsAlias(alias)) {
        Log.d(TAG, "[containsAlias]");
        return;
    }

    Calendar start = Calendar.getInstance();
    Calendar end = Calendar.getInstance();
    end.add(Calendar.YEAR, 30);
    KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
        .setAlias(alias)
        .setSubject(new X500Principal("CN=" + alias))
        .setSerialNumber(BigInteger.TEN)
        .setStartDate(start.getTime())
        .setEndDate(end.getTime())
        .build();
    KeyPairGenerator generator = KeyPairGenerator.getInstance(TYPE_RSA, ANDROID_KEY_STORE);
    generator.initialize(spec);
    KeyPair keyPair = generator.generateKeyPair();
    Log.d(TAG, "Public Key is: " + keyPair.getPublic().toString());
}
 
开发者ID:drakeet,项目名称:rebase-android,代码行数:29,代码来源:BlackBox.java

示例2: renameKey

import java.security.KeyStore; //导入方法依赖的package包/类
public static String renameKey( String keystorePath, String storePass, String oldKeyName, String newKeyName, String keyPass)
    throws Exception
{
    char[] keyPw = null;

    try {
        KeyStore ks = loadKeyStore(keystorePath, storePass);
        if (ks instanceof JksKeyStore) newKeyName = newKeyName.toLowerCase();

        if (ks.containsAlias(newKeyName)) throw new KeyNameConflictException();

        keyPw = PasswordObfuscator.getInstance().decodeAliasPassword( keystorePath, oldKeyName, keyPass);
        Key key = ks.getKey(oldKeyName, keyPw);
        Certificate cert = ks.getCertificate( oldKeyName);

        ks.setKeyEntry(newKeyName, key, keyPw, new Certificate[] { cert});
        ks.deleteEntry( oldKeyName);

        writeKeyStore(ks, keystorePath, storePass);
        return newKeyName;
    }
    finally {
        PasswordObfuscator.flush(keyPw);
    }
}
 
开发者ID:tranleduy2000,项目名称:javaide,代码行数:26,代码来源:KeyStoreFileManager.java

示例3: isSigningKey

import java.security.KeyStore; //导入方法依赖的package包/类
/**
 * JBMR2+ If Key with the default alias exists, returns true, else false.
 * on pre-JBMR2 returns true always.
 */
public static boolean isSigningKey(String alias) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        try {
            KeyStore keyStore =
                    KeyStore.getInstance(SecurityConstants.KEYSTORE_PROVIDER_ANDROID_KEYSTORE);
            keyStore.load(null);
            return keyStore.containsAlias(alias);
        } catch (Exception e) {
            Log.e(TAG, e.getMessage(), e);
            return false;
        }
    } else {
        return false;
    }
}
 
开发者ID:ronghao,项目名称:CacheManage,代码行数:20,代码来源:KeyStoreHelper.java

示例4: SecretKeyWrapper

import java.security.KeyStore; //导入方法依赖的package包/类
/**
 * Create a wrapper using the public/private key pair with the given alias.
 * If no pair with that alias exists, it will be generated.
 */
@SuppressLint("GetInstance")
public SecretKeyWrapper(Context context, String alias)
        throws GeneralSecurityException, IOException {
    mCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

    final KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
    keyStore.load(null);

    if (!keyStore.containsAlias(alias)) {
        generateKeyPair(context, alias);
    }

    // Even if we just generated the key, always read it back to ensure we
    // can read it successfully.
    final KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(
            alias, null);
    mPair = new KeyPair(entry.getCertificate().getPublicKey(), entry.getPrivateKey());
}
 
开发者ID:privacyidea,项目名称:privacyidea-authenticator,代码行数:23,代码来源:SecretKeyWrapper.java

示例5: 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

示例6: encryptData

import java.security.KeyStore; //导入方法依赖的package包/类
/**
 * Encrypt given bytes and persist contents to File with given filename.
 * @param input - byte[] to encrypt
 * @param fileName - String name of the encrypted file
 * @return String representing encrypted file or null if encryption fails.
 * @throws Exception - Throws Exceptions related to encryption
 */
private String encryptData(final byte [] input,  final String fileName) throws Exception{

  String encryptedDataFilePath;

  final KeyStore keyStore = KeyStore.getInstance(AndroidKeyStore);
  keyStore.load(null);

  // Does the key need to be created?
  if (!keyStore.containsAlias(ALIAS)){
    createNewKey();
  }
  final SecretKey key = (SecretKey) keyStore.getKey(ALIAS, null);

  final Cipher c = Cipher.getInstance(CIPHER_TYPE);
  c.init(Cipher.ENCRYPT_MODE, key);

  // Persist the GCMParamterSpec bytes to file for later use
  GCMParameterSpec spec = c.getParameters().getParameterSpec(GCMParameterSpec.class);
   final FileOutputStream fos = new FileOutputStream(getFilePath(Constants.IV_FILE));
  fos.write(spec.getIV());
  Log.i(TAG, "IV Length is " + spec.getIV().length+ " tag length is " + spec.getTLen());
  fos.close();

  encryptedDataFilePath = getFilePath(fileName);

  final CipherOutputStream cipherOutputStream =
      new CipherOutputStream(
          new FileOutputStream(encryptedDataFilePath), c);
  cipherOutputStream.write(input);
  cipherOutputStream.close();

  return encryptedDataFilePath;
}
 
开发者ID:Esri,项目名称:mapbook-android,代码行数:41,代码来源:CredentialCryptographer.java

示例7: checkAlias

import java.security.KeyStore; //导入方法依赖的package包/类
private void checkAlias(KeyStore obj, int range) throws KeyStoreException {
    for (int k = 0; k < range; k++) {
        if (!obj.containsAlias(ALIAS_HEAD + k)) {
            throw new RuntimeException("ERROR: alias (" + k
                    + ") should exist");
        }
    }
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:9,代码来源:TestKeyStoreBasic.java

示例8: getOrCreatePublicKey

import java.security.KeyStore; //导入方法依赖的package包/类
private PublicKey getOrCreatePublicKey(String alias) throws GeneralSecurityException, IOException {
  KeyStore keyStore = KeyStore.getInstance(getKeyStore());
  keyStore.load(null);

  if (!keyStore.containsAlias(alias) || keyStore.getCertificate(alias) == null) {
    Log.i(Constants.TAG, "no existing asymmetric keys for alias");

    Calendar start = Calendar.getInstance();
    Calendar end = Calendar.getInstance();
    end.add(Calendar.YEAR, 50);
    KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(getContext())
        .setAlias(alias)
        .setSubject(new X500Principal("CN=" + alias))
        .setSerialNumber(BigInteger.ONE)
        .setStartDate(start.getTime())
        .setEndDate(end.getTime())
        .build();

    KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", getKeyStore());
    generator.initialize(spec);
    generator.generateKeyPair();

    Log.i(Constants.TAG, "created new asymmetric keys for alias");
  }

  return keyStore.getCertificate(alias).getPublicKey();
}
 
开发者ID:pradeep1991singh,项目名称:react-native-secure-key-store,代码行数:28,代码来源:RNSecureKeyStoreModule.java

示例9: containsKey

import java.security.KeyStore; //导入方法依赖的package包/类
public static boolean containsKey( String keystorePath, String storePass, String keyName)
    throws Exception
{
    KeyStore ks = loadKeyStore(keystorePath, storePass);
    return ks.containsAlias( keyName);
}
 
开发者ID:tranleduy2000,项目名称:javaide,代码行数:7,代码来源:KeyStoreFileManager.java

示例10: recoverEntry

import java.security.KeyStore; //导入方法依赖的package包/类
/**
 * Recovers entry associated with given alias.
 *
 * @return an array of objects, where the 1st element in the array is the
 * recovered entry, and the 2nd element is the password used to
 * recover it (null if no password).
 */
private Pair<Entry,char[]> recoverEntry(KeyStore ks,
                        String alias,
                        char[] pstore,
                        char[] pkey) throws Exception {

    if (ks.containsAlias(alias) == false) {
        MessageFormat form = new MessageFormat
            (rb.getString("Alias.alias.does.not.exist"));
        Object[] source = {alias};
        throw new Exception(form.format(source));
    }

    PasswordProtection pp = null;
    Entry entry;

    try {
        // First attempt to access entry without key password
        // (PKCS11 entry or trusted certificate entry, for example)

        entry = ks.getEntry(alias, pp);
        pkey = null;
    } catch (UnrecoverableEntryException une) {

        if(P11KEYSTORE.equalsIgnoreCase(ks.getType()) ||
            KeyStoreUtil.isWindowsKeyStore(ks.getType())) {
            // should not happen, but a possibility
            throw une;
        }

        // entry is protected

        if (pkey != null) {

            // try provided key password

            pp = new PasswordProtection(pkey);
            entry = ks.getEntry(alias, pp);

        } else {

            // try store pass

            try {
                pp = new PasswordProtection(pstore);
                entry = ks.getEntry(alias, pp);
                pkey = pstore;
            } catch (UnrecoverableEntryException une2) {
                if (P12KEYSTORE.equalsIgnoreCase(ks.getType())) {

                    // P12 keystore currently does not support separate
                    // store and entry passwords

                    throw une2;
                } else {

                    // prompt for entry password

                    pkey = getKeyPasswd(alias, null, null);
                    pp = new PasswordProtection(pkey);
                    entry = ks.getEntry(alias, pp);
                }
            }
        }
    }

    return Pair.of(entry, pkey);
}
 
开发者ID:SunburstApps,项目名称:OpenJSharp,代码行数:75,代码来源:Main.java

示例11: testKeyStore

import java.security.KeyStore; //导入方法依赖的package包/类
private void testKeyStore(KeyStore inputKeyStore, char[] keypass)
        throws KeyStoreException, UnrecoverableKeyException,
        NoSuchAlgorithmException {
    out.println("========== Key Store ==========");
    out.println("getProvider : " + inputKeyStore.getProvider());
    out.println("getType : " + inputKeyStore.getType());
    out.println("getDefaultType : " + KeyStore.getDefaultType());

    int idx = 0;
    Enumeration<String> e = inputKeyStore.aliases();
    String alias;
    while (e.hasMoreElements()) {
        alias = e.nextElement();
        if (!inputKeyStore.containsAlias(alias)) {
            throw new RuntimeException("Alias not found");
        }
        out.println("Alias " + idx + " : " + alias);
        out.println("getCreationDate : "
                + inputKeyStore.getCreationDate(alias));
        X509Certificate cert = (X509Certificate) inputKeyStore
                .getCertificate(alias);
        out.println("getCertificate : " + cert.getSubjectDN());
        String retAlias = inputKeyStore.getCertificateAlias(cert);
        if (!retAlias.equals(alias)) {
            throw new RuntimeException("Alias mismatch, actually "
                    + retAlias + ", expected " + alias);
        }
        out.println("getCertificateAlias : " + retAlias);
        Certificate[] certs = inputKeyStore.getCertificateChain(alias);
        int i = 0;
        for (Certificate certification : certs) {
            out.println("getCertificateChain " + i
                    + ((X509Certificate) certification).getSubjectDN());
            i++;
        }
        if (inputKeyStore.isCertificateEntry(alias)) {
            throw new RuntimeException(
                    "inputKeystore should not be certEntry because this"
                            + " keystore only contain key pair entries.");
        }
        if (!inputKeyStore.isKeyEntry(alias)) {
            throw new RuntimeException("Entry type unknown.");
        }
        idx++;
    }
    int size = inputKeyStore.size();
    if (idx != size) {
        throw new RuntimeException("Size not match, actually " + idx
                + ", expected " + size);
    }
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:52,代码来源:WriteP12Test.java

示例12: readTest

import java.security.KeyStore; //导入方法依赖的package包/类
private void readTest(String inKeyStore) throws Exception {

        KeyStore inputKeyStore;

        // Initialize KeyStore
        String dir = System.getProperty("test.src", ".");
        String keystorePath = dir + File.separator + "certs" + File.separator
                + "readP12";
        inputKeyStore = KeyStore
                .getInstance(IN_KETYSTORE_TYPE, IN_KEYSTORE_PRV);
        // KeyStore have encoded by Base64.getMimeEncoder().encode(),need decode
        // first.
        byte[] input = Files.readAllBytes(Paths.get(keystorePath, inKeyStore));
        ByteArrayInputStream arrayIn = new ByteArrayInputStream(Base64
                .getMimeDecoder().decode(input));
        inputKeyStore.load(arrayIn, IN_STORE_PASS.toCharArray());
        out.println("Initialize KeyStore : " + inKeyStore + " success");

        out.println("getProvider : " + inputKeyStore.getProvider());
        out.println("getType : " + inputKeyStore.getType());
        out.println("getDefaultType : " + KeyStore.getDefaultType());

        int idx = 0;
        Enumeration<String> e = inputKeyStore.aliases();
        String alias;
        while (e.hasMoreElements()) {
            alias = e.nextElement();
            out.println("Alias " + idx + " : " + alias);
            if (inputKeyStore.containsAlias(alias) == false) {
                throw new RuntimeException("Alias not found");
            }

            out.println("getCreationDate : "
                    + inputKeyStore.getCreationDate(alias));

            X509Certificate cert = (X509Certificate) inputKeyStore
                    .getCertificate(alias);
            out.println("getCertificate : " + cert.getSubjectDN());
            String retAlias = inputKeyStore.getCertificateAlias(cert);
            if (!retAlias.equals(alias)) {
                throw new RuntimeException("Alias mismatch");
            }
            out.println("getCertificateAlias : " + retAlias);

            Certificate[] certs = inputKeyStore.getCertificateChain(alias);
            for (int i = 0; i < certs.length; i++) {
                out.println("getCertificateChain " + i + " : "
                        + ((X509Certificate) certs[i]).getSubjectDN());
            }

            boolean isCertEntry = inputKeyStore.isCertificateEntry(alias);
            // test KeyStore only contain key pair entries.
            if (isCertEntry == true) {
                throw new RuntimeException(
                        "inputKeystore should not be certEntry because test keystore only contain key pair entries.");
            }

            boolean isKeyEntry = inputKeyStore.isKeyEntry(alias);
            if (isKeyEntry) {
                Key key = inputKeyStore.getKey(alias,
                        IN_STORE_PASS.toCharArray());
                out.println("Key : " + key.toString());
            } else {
                throw new RuntimeException("Entry type unknown\n");
            }
            idx++;
        }

        int size = inputKeyStore.size();
        if (idx != size) {
            throw new RuntimeException("Size not match");
        }

    }
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:75,代码来源:ReadP12Test.java

示例13: readTest

import java.security.KeyStore; //导入方法依赖的package包/类
private void readTest(String inKeyStore) throws Exception {

        KeyStore inputKeyStore;

        // Initialize KeyStore
        String dir = System.getProperty("test.src", ".");
        String keystorePath = dir + File.separator + "certs" + File.separator
                + "readP12";
        inputKeyStore = KeyStore.getInstance(IN_KEYSTORE_TYPE);
        // KeyStore have encoded by Base64.getMimeEncoder().encode(),need decode
        // first.
        byte[] input = Files.readAllBytes(Paths.get(keystorePath, inKeyStore));
        ByteArrayInputStream arrayIn = new ByteArrayInputStream(Base64
                .getMimeDecoder().decode(input));
        inputKeyStore.load(arrayIn, IN_STORE_PASS.toCharArray());
        out.println("Initialize KeyStore : " + inKeyStore + " success");

        out.println("getProvider : " + inputKeyStore.getProvider());
        out.println("getType : " + inputKeyStore.getType());
        out.println("getDefaultType : " + KeyStore.getDefaultType());

        int idx = 0;
        Enumeration<String> e = inputKeyStore.aliases();
        String alias;
        while (e.hasMoreElements()) {
            alias = e.nextElement();
            out.println("Alias " + idx + " : " + alias);
            if (inputKeyStore.containsAlias(alias) == false) {
                throw new RuntimeException("Alias not found");
            }

            out.println("getCreationDate : "
                    + inputKeyStore.getCreationDate(alias));

            X509Certificate cert = (X509Certificate) inputKeyStore
                    .getCertificate(alias);
            out.println("getCertificate : " + cert.getSubjectDN());
            String retAlias = inputKeyStore.getCertificateAlias(cert);
            if (!retAlias.equals(alias)) {
                throw new RuntimeException("Alias mismatch");
            }
            out.println("getCertificateAlias : " + retAlias);

            Certificate[] certs = inputKeyStore.getCertificateChain(alias);
            for (int i = 0; i < certs.length; i++) {
                out.println("getCertificateChain " + i + " : "
                        + ((X509Certificate) certs[i]).getSubjectDN());
            }

            boolean isCertEntry = inputKeyStore.isCertificateEntry(alias);
            // test KeyStore only contain key pair entries.
            if (isCertEntry == true) {
                throw new RuntimeException(
                        "inputKeystore should not be certEntry because test keystore only contain key pair entries.");
            }

            boolean isKeyEntry = inputKeyStore.isKeyEntry(alias);
            if (isKeyEntry) {
                Key key = inputKeyStore.getKey(alias,
                        IN_STORE_PASS.toCharArray());
                out.println("Key : " + key.toString());
            } else {
                throw new RuntimeException("Entry type unknown\n");
            }
            idx++;
        }

        int size = inputKeyStore.size();
        if (idx != size) {
            throw new RuntimeException("Size not match");
        }

    }
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:74,代码来源:ReadP12Test.java

示例14: addCertToKeyStore

import java.security.KeyStore; //导入方法依赖的package包/类
protected void
addCertToKeyStore(
	String								alias,
	Key									public_key,
	java.security.cert.Certificate[] 	certChain )

	throws Exception
{
	try{
		this_mon.enter();

		KeyStore key_store = loadKeyStore();

		if( key_store.containsAlias( alias )){

			key_store.deleteEntry( alias );
		}

		key_store.setKeyEntry( alias, public_key, SESecurityManager.SSL_PASSWORD.toCharArray(), certChain );

		FileOutputStream	out = null;

		try{
			out = new FileOutputStream(keystore_name);

			key_store.store(out, SESecurityManager.SSL_PASSWORD.toCharArray());

		}catch( Throwable e ){

			Debug.printStackTrace( e );

		}finally{

			if ( out != null ){

				out.close();
			}
		}
	}finally{

		this_mon.exit();
	}
}
 
开发者ID:BiglySoftware,项目名称:BiglyBT,代码行数:44,代码来源:SESecurityManagerImpl.java

示例15: addCertToTrustStore

import java.security.KeyStore; //导入方法依赖的package包/类
protected SSLSocketFactory
addCertToTrustStore(
	String							alias,
	java.security.cert.Certificate	cert,
	boolean							update_https_factory )

	throws Exception
{
	try{
		this_mon.enter();

		KeyStore keystore = getTrustStore();

		if ( cert != null ){

			if ( keystore.containsAlias( alias )){

				keystore.deleteEntry( alias );
			}

			keystore.setCertificateEntry(alias, cert);

			FileOutputStream	out = null;

			try{
				out = new FileOutputStream(truststore_name);

				keystore.store(out, SESecurityManager.SSL_PASSWORD.toCharArray());

			}finally{

				if ( out != null ){

					out.close();
				}
			}
		}

			// pick up the changed trust store

		TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

		tmf.init(keystore);

		SSLContext ctx = SSLContext.getInstance("SSL");

		ctx.init(null, tmf.getTrustManagers(), null);

		SSLSocketFactory	factory = ctx.getSocketFactory();

		if ( update_https_factory ){

			HttpsURLConnection.setDefaultSSLSocketFactory( factory );
		}

		return( factory );
	}finally{

		this_mon.exit();
	}
}
 
开发者ID:BiglySoftware,项目名称:BiglyBT,代码行数:62,代码来源:SESecurityManagerImpl.java


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