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


Java KeyStore.PrivateKeyEntry方法代码示例

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


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

示例1: encrypt

import java.security.KeyStore; //导入方法依赖的package包/类
/**
 * Encrypt the secret with RSA.
 *
 * @param secret the secret.
 * @return the encrypted secret.
 * @throws Exception
 */
public String encrypt(String secret) throws Exception {
    KeyStore keyStore = KeyStore.getInstance(ANDROID_KEY_STORE);
    keyStore.load(null);
    KeyStore.PrivateKeyEntry privateKeyEntry =
        (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias, null);

    Cipher inputCipher = Cipher.getInstance(RSA_ALGORITHM);
    inputCipher.init(Cipher.ENCRYPT_MODE, privateKeyEntry.getCertificate().getPublicKey());

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, inputCipher);
    cipherOutputStream.write(secret.getBytes());
    cipherOutputStream.close();

    return Base64.encodeToString(outputStream.toByteArray(), Base64.DEFAULT);
}
 
开发者ID:drakeet,项目名称:rebase-android,代码行数:24,代码来源:BlackBox.java

示例2: createJWT

import java.security.KeyStore; //导入方法依赖的package包/类
public String createJWT(String username, Set<String> groups)
    throws GeneralSecurityException, IOException {
  // Create and Base64 encode the header portion of the JWT
  JsonObject headerObj =
      Json.createObjectBuilder()
          .add("alg", "RS256") /* Algorithm used */
          .add("typ", "JWT") /* Type of token */
          // .add("kid", "default") /* Hint about which key to use to sign, but the signature is
          // invalid when I include this. */
          .build();
  String headerEnc = Base64Utility.encode(headerObj.toString().getBytes(), true);

  // Create and Base64 encode the claims portion of the JWT
  JsonObject claimsObj =
      Json.createObjectBuilder()
          .add("exp", (System.currentTimeMillis() / 1000) + 300) /* Expire time */
          .add("iat", (System.currentTimeMillis() / 1000)) /* Issued time */
          .add("aud", "acmeGifts") /* Audience */
          .add("jti", Long.toHexString(System.nanoTime())) /* Unique value */
          .add("sub", username) /* Subject */
          .add("upn", username) /* Subject again */
          .add("iss", JWT_ISSUER) /* Issuer */
          .add("groups", getGroupArray(groups)) /* Group list */
          .build();
  String claimsEnc = Base64Utility.encode(claimsObj.toString().getBytes(), true);
  String headerClaimsEnc = headerEnc + "." + claimsEnc;

  // Open the keystore that the server will use to validate the JWT
  KeyStore ks = KeyStore.getInstance("JCEKS");
  InputStream ksStream = this.getClass().getResourceAsStream("/keystore.jceks");
  char[] password = new String("secret").toCharArray();
  ks.load(ksStream, password);

  // Get the private key to use to sign the JWT.  Normally we would not do this but
  // we are pretending to be the user service here.
  KeyStore.ProtectionParameter keyPassword = new KeyStore.PasswordProtection(password);
  KeyStore.PrivateKeyEntry privateKeyEntry =
      (KeyStore.PrivateKeyEntry) ks.getEntry("default", keyPassword);
  PrivateKey privateKey = privateKeyEntry.getPrivateKey();

  // Sign the JWT
  Signature sig = Signature.getInstance(JWT_ALGORITHM);
  sig.initSign(privateKey);
  sig.update(headerClaimsEnc.getBytes());
  String sigEnc = Base64Utility.encode(sig.sign(), true);

  // Lets just check......
  String jwtEnc = headerClaimsEnc + "." + sigEnc;
  java.security.cert.Certificate cert = ks.getCertificate("default");
  PublicKey publicKey = cert.getPublicKey();
  validateJWT("Bearer " + jwtEnc, publicKey);

  // Return the complete JWT (header, claims, signature).
  return jwtEnc;
}
 
开发者ID:OpenLiberty,项目名称:sample-acmegifts,代码行数:56,代码来源:JWTVerifier.java

示例3: engineEntryInstanceOf

import java.security.KeyStore; //导入方法依赖的package包/类
/**
 * Determines if the keystore {@code Entry} for the specified
 * {@code alias} is an instance or subclass of the specified
 * {@code entryClass}.
 *
 * @param alias the alias name
 * @param entryClass the entry class
 *
 * @return true if the keystore {@code Entry} for the specified
 *          {@code alias} is an instance or subclass of the
 *          specified {@code entryClass}, false otherwise
 *
 * @since 1.5
 */
@Override
public boolean
    engineEntryInstanceOf(String alias,
                          Class<? extends KeyStore.Entry> entryClass)
{
    if (entryClass == KeyStore.TrustedCertificateEntry.class) {
        return engineIsCertificateEntry(alias);
    }

    Entry entry = entries.get(alias.toLowerCase(Locale.ENGLISH));
    if (entryClass == KeyStore.PrivateKeyEntry.class) {
        return (entry != null && entry instanceof PrivateKeyEntry);
    }
    if (entryClass == KeyStore.SecretKeyEntry.class) {
        return (entry != null && entry instanceof SecretKeyEntry);
    }
    return false;
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:33,代码来源:PKCS12KeyStore.java

示例4: runTest

import java.security.KeyStore; //导入方法依赖的package包/类
private void runTest() throws IOException, KeyStoreException,
        NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException {
    KeyStore ks = Utils.loadKeyStore(KEYSTORE_PATH,
            Utils.KeyStoreType.pkcs12, PASSWORD);
    Key key = ks.getKey(ALIAS, PASSWORD);
    Certificate cert = ks
            .getCertificate(ALIAS);
    KeyStore.Entry entry = new KeyStore.PrivateKeyEntry(
            (PrivateKey) key,
            new Certificate[]{cert});
    if (!entry.getAttributes().isEmpty()) {
        throw new RuntimeException("Entry's attributes set "
                + "must be empty");
    }
    out.println("Test Passed");
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:18,代码来源:MetadataEmptyTest.java

示例5: buildCredential

import java.security.KeyStore; //导入方法依赖的package包/类
/**
 * Build a credential instance from the key store entry.
 * 
 * @param keyStoreEntry the key store entry to process
 * @param entityID the entityID to include in the credential
 * @param usage the usage type to include in the credential
 * @return the new credential instance, appropriate to the type of key store entry being processed
 * @throws SecurityException throw if there is a problem building a credential from the key store entry
 */
protected Credential buildCredential(KeyStore.Entry keyStoreEntry, String entityID, UsageType usage)
        throws SecurityException {

    log.debug("Building credential from keystore entry for entityID {}, usage type {}", entityID, usage);

    Credential credential = null;
    if (keyStoreEntry instanceof KeyStore.PrivateKeyEntry) {
        credential = processPrivateKeyEntry((KeyStore.PrivateKeyEntry) keyStoreEntry, entityID, keystoreUsage);
    } else if (keyStoreEntry instanceof KeyStore.TrustedCertificateEntry) {
        credential = processTrustedCertificateEntry((KeyStore.TrustedCertificateEntry) keyStoreEntry, entityID,
                keystoreUsage);
    } else if (keyStoreEntry instanceof KeyStore.SecretKeyEntry) {
        credential = processSecretKeyEntry((KeyStore.SecretKeyEntry) keyStoreEntry, entityID, keystoreUsage);
    } else {
        throw new SecurityException("KeyStore entry was of an unsupported type: "
                + keyStoreEntry.getClass().getName());
    }
    return credential;
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:29,代码来源:KeyStoreCredentialResolver.java

示例6: processPrivateKeyEntry

import java.security.KeyStore; //导入方法依赖的package包/类
/**
 * Build an X509Credential from a keystore private key entry.
 * 
 * @param privateKeyEntry the entry being processed
 * @param entityID the entityID to set
 * @param usage the usage type to set
 * @return new X509Credential instance
 */
protected X509Credential processPrivateKeyEntry(KeyStore.PrivateKeyEntry privateKeyEntry, String entityID,
        UsageType usage) {

    log.debug("Processing PrivateKeyEntry from keystore");

    BasicX509Credential credential = new BasicX509Credential();
    credential.setEntityId(entityID);
    credential.setUsageType(usage);

    credential.setPrivateKey(privateKeyEntry.getPrivateKey());

    credential.setEntityCertificate((X509Certificate) privateKeyEntry.getCertificate());
    credential.setEntityCertificateChain(Arrays.asList((X509Certificate[]) privateKeyEntry.getCertificateChain()));

    return credential;
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:25,代码来源:KeyStoreCredentialResolver.java

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

示例8: check

import java.security.KeyStore; //导入方法依赖的package包/类
private static void check(String encodedBlob) throws Exception {
    byte[] blob = new byte[encodedBlob.length() * 2];
    for (int i = 0; i < blob.length; ) {
        final char ch = encodedBlob.charAt(i / 2);
        blob[i++] = (byte) (ch >> 8);
        blob[i++] = (byte) ch;
    }
    KeyStore store = KeyStore.getInstance("PKCS12");
    store.load(new ByteArrayInputStream(blob), new char[0]);
    if (!store.aliases().nextElement().equals("test"))
        throw new Exception("test alias not found");
    KeyStore.PrivateKeyEntry e =
        (KeyStore.PrivateKeyEntry) store.getEntry("test",
                new KeyStore.PasswordProtection(new char[0]));
    X509Certificate cert = (X509Certificate) e.getCertificateChain()[0];
    if (!cert.getSubjectDN().toString().equals("CN=Test Key"))
        throw new Exception("invalid certificate subject DN");
    RSAPrivateCrtKey key = (RSAPrivateCrtKey) e.getPrivateKey();
    if (!key.getPublicExponent().equals(BigInteger.valueOf(65537)))
        throw new Exception("invalid public exponent");
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:22,代码来源:Bug6415637.java

示例9: storeAttrs

import java.security.KeyStore; //导入方法依赖的package包/类
private void storeAttrs() throws UnrecoverableEntryException,
        GeneralSecurityException, NoSuchAlgorithmException,
        KeyStoreException, IOException {
    KeyStore ksIn = Utils.loadKeyStore(KEYSTORE_PATH,
            Utils.KeyStoreType.pkcs12, PASSWORD);
    KeyStore ksAttr = KeyStore
            .getInstance(Utils.KeyStoreType.pkcs12.name());
    ksAttr.load(null);
    Key key = ksIn.getKey(ALIAS, PASSWORD);
    Certificate cert = ksIn.getCertificate(ALIAS);
    Set<KeyStore.Entry.Attribute> attrs =
            new HashSet<>(Arrays.asList(ATTR_SET));
    KeyStore.Entry e = new KeyStore.PrivateKeyEntry((PrivateKey) key,
            new Certificate[]{cert}, attrs);
    ksAttr.setEntry(ALIAS, e, new KeyStore.PasswordProtection(
            KEY_PASSWORD));

    out.println("Attributes before store:");
    e.getAttributes().stream().forEach((attr) -> {
        out.println(attr.getName() + ", '" + attr.getValue() + "'");
    });
    Utils.saveKeyStore(ksAttr, WORKING_DIRECTORY + File.separator
            + KESTORE_NEW, PASSWORD);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:25,代码来源:MetadataStoreLoadTest.java

示例10: onPostExecute

import java.security.KeyStore; //导入方法依赖的package包/类
@Override
protected void onPostExecute(final KeyStore.PrivateKeyEntry pke) {
    super.onPostExecute(pke);

    if (pke != null) {
        try {
            // Ejecutamos la tarea de firma
            new SignTask(
                    context,
                    pke,
                    context.getExtraParams(),
                    progDailog
            ).execute(canResult.getIlp());
            return;
        }
        catch (Exception e) {
            Log.e("com.mifirma", "Error inicializando DNIe NFC: " + e);
        }
    }
    if(progDailog != null){
        progDailog.dismiss();
    }
    if(DniDialog.getInstance() != null){
        DniDialog.getInstance().dismiss();
    }
    canResult = null;
    Toast.makeText(context, "Ha sido imposible usar el DNI NFC, inténtelo de nuevo.", Toast.LENGTH_LONG).show();
}
 
开发者ID:MiFirma,项目名称:mi-firma-android,代码行数:29,代码来源:KeyStoreLoadTask.java

示例11: getPrivateKey

import java.security.KeyStore; //导入方法依赖的package包/类
/**
 * Fetches the private key matching the given alias from the defined key
 * store.
 *
 * @param path absolute path of the key store file
 * @param storePassword password of the key store
 * @param privateKeyAlias alias of the private key in the key store
 * @param keyPassword password of the private key
 * @return private key with the given alias
 */
public static PrivateKey getPrivateKey(String path, String storePassword, String privateKeyAlias, String keyPassword) {
    try (FileInputStream fis = new java.io.FileInputStream(path)) {
        KeyStore keyStore = KeyStore.getInstance("jks");
        keyStore.load(fis, storePassword.toCharArray());
        KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(privateKeyAlias,
                new KeyStore.PasswordProtection(keyPassword.toCharArray()));
        return pkEntry.getPrivateKey();
    } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException
        | UnrecoverableEntryException ex) {
        LOGGER.error(ex.getMessage(), ex);
        throw new XRd4JRuntimeException(ex.getMessage());
    }
}
 
开发者ID:vrk-kpa,项目名称:xrd4j,代码行数:24,代码来源:CryptoHelper.java

示例12: onReceive

import java.security.KeyStore; //导入方法依赖的package包/类
@Override
public void onReceive(Context context, Intent intent) {

    KeyStore.PrivateKeyEntry privateKeyEntry = DataBase.getPrivateKeyEntry(DataBase.getAlias(context));
    if (null == privateKeyEntry) return;

    //We listen to two intents.  The new outgoing call only tells us of an outgoing call.  We use it to get the number.
    if (intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL")) {
        savedNumber = intent.getExtras().getString("android.intent.extra.PHONE_NUMBER");
    }
    else if (NotificationManagerCompat.getEnabledListenerPackages(context.getApplicationContext()).contains(context.getPackageName())) {
        String stateStr = intent.getExtras().getString(TelephonyManager.EXTRA_STATE);
        String number = intent.getExtras().getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
        int state = 0;
        if(stateStr.equals(TelephonyManager.EXTRA_STATE_IDLE)){
            state = TelephonyManager.CALL_STATE_IDLE;
        }
        else if(stateStr.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)){
            state = TelephonyManager.CALL_STATE_OFFHOOK;
        }
        else if(stateStr.equals(TelephonyManager.EXTRA_STATE_RINGING)){
            state = TelephonyManager.CALL_STATE_RINGING;
        }


        onCallStateChanged(context, state, number, intent);
    }
}
 
开发者ID:ceanyd,项目名称:react-native-caller-id-android,代码行数:29,代码来源:MainService.java

示例13: getPrivateKeyEntry

import java.security.KeyStore; //导入方法依赖的package包/类
public static KeyStore.PrivateKeyEntry getPrivateKeyEntry (String alias) {
    KeyStore.PrivateKeyEntry privateKeyEntry = null;
    try {
        KeyStore keystore = KeyStore.getInstance(keyStoreInstance);
        keystore.load(null);

        privateKeyEntry = (KeyStore.PrivateKeyEntry) keystore.getEntry(alias, null);
    } catch (Exception e) {
        Log.e(TAG, Log.getStackTraceString(e));
    }
    return privateKeyEntry;
}
 
开发者ID:ceanyd,项目名称:react-native-caller-id-android,代码行数:13,代码来源:DataBase.java

示例14: copy

import java.security.KeyStore; //导入方法依赖的package包/类
private static int copy(int testnum) throws Exception {

        if (ks == null) {
            ks = KeyStore.getInstance(KS_TYPE, provider);
            ks.load(null, tokenPwd);
        }

        KeyFactory kf = KeyFactory.getInstance("RSA", provider);
        PrivateKey pkSession = (PrivateKey)kf.translateKey(pk3);
        System.out.println("pkSession = " + pkSession);
        ks.setKeyEntry("pkSession", pkSession, null, chain3);

        KeyStore.PrivateKeyEntry pke =
                (KeyStore.PrivateKeyEntry)ks.getEntry("pkSession", null);
        System.out.println("pkSession = " + pke.getPrivateKey());
        Certificate[] chain = pke.getCertificateChain();
        if (chain.length != chain3.length) {
            throw new SecurityException("received chain not correct length");
        }
        for (int i = 0; i < chain.length; i++) {
            if (!chain[i].equals(chain3[i])) {
                throw new SecurityException("received chain not equal");
            }
        }

        System.out.println("test " + testnum++ + " passed");

        return testnum;
    }
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:30,代码来源:Basic.java

示例15: engineSetEntry

import java.security.KeyStore; //导入方法依赖的package包/类
/**
 * Saves a <code>KeyStore.Entry</code> under the specified alias.
 * The specified protection parameter is used to protect the
 * <code>Entry</code>.
 *
 * <p> If an entry already exists for the specified alias,
 * it is overridden.
 *
 * @param alias save the <code>KeyStore.Entry</code> under this alias
 * @param entry the <code>Entry</code> to save
 * @param protParam the <code>ProtectionParameter</code>
 *          used to protect the <code>Entry</code>,
 *          which may be <code>null</code>
 *
 * @exception KeyStoreException if this operation fails
 *
 * @since 1.5
 */
@Override
public synchronized void engineSetEntry(String alias, KeyStore.Entry entry,
    KeyStore.ProtectionParameter protParam) throws KeyStoreException {

    // get password
    if (protParam != null &&
        !(protParam instanceof KeyStore.PasswordProtection)) {
        throw new KeyStoreException("unsupported protection parameter");
    }
    KeyStore.PasswordProtection pProtect = null;
    if (protParam != null) {
        pProtect = (KeyStore.PasswordProtection)protParam;
    }

    // set entry
    if (entry instanceof KeyStore.TrustedCertificateEntry) {
        if (protParam != null && pProtect.getPassword() != null) {
            // pre-1.5 style setCertificateEntry did not allow password
            throw new KeyStoreException
                ("trusted certificate entries are not password-protected");
        } else {
            KeyStore.TrustedCertificateEntry tce =
                    (KeyStore.TrustedCertificateEntry)entry;
            setCertEntry(alias, tce.getTrustedCertificate(),
                tce.getAttributes());

            return;
        }
    } else if (entry instanceof KeyStore.PrivateKeyEntry) {
        if (pProtect == null || pProtect.getPassword() == null) {
            // pre-1.5 style setKeyEntry required password
            throw new KeyStoreException
                ("non-null password required to create PrivateKeyEntry");
        } else {
            KeyStore.PrivateKeyEntry pke = (KeyStore.PrivateKeyEntry)entry;
            setKeyEntry(alias, pke.getPrivateKey(), pProtect,
                pke.getCertificateChain(), pke.getAttributes());

            return;
        }
    } else if (entry instanceof KeyStore.SecretKeyEntry) {
        if (pProtect == null || pProtect.getPassword() == null) {
            // pre-1.5 style setKeyEntry required password
            throw new KeyStoreException
                ("non-null password required to create SecretKeyEntry");
        } else {
            KeyStore.SecretKeyEntry ske = (KeyStore.SecretKeyEntry)entry;
            setKeyEntry(alias, ske.getSecretKey(), pProtect,
                (Certificate[])null, ske.getAttributes());

            return;
        }
    }

    throw new KeyStoreException
            ("unsupported entry type: " + entry.getClass().getName());
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:76,代码来源:PKCS12KeyStore.java


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