當前位置: 首頁>>代碼示例>>Java>>正文


Java PrivateKey.getEncoded方法代碼示例

本文整理匯總了Java中java.security.PrivateKey.getEncoded方法的典型用法代碼示例。如果您正苦於以下問題:Java PrivateKey.getEncoded方法的具體用法?Java PrivateKey.getEncoded怎麽用?Java PrivateKey.getEncoded使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在java.security.PrivateKey的用法示例。


在下文中一共展示了PrivateKey.getEncoded方法的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: save

import java.security.PrivateKey; //導入方法依賴的package包/類
/**
 * Saves a key pair.
 *
 * @param keyPair the key pair to save
 * @throws IOException if the files cannot be written
 * @since 1.0.0
 */
public void save(KeyPair keyPair) throws IOException {
    LOGGER.info("Saving key pair");
    final PrivateKey privateKey = keyPair.getPrivate();
    final PublicKey publicKey = keyPair.getPublic();

    // Store Public Key
    final File publicKeyFile = getKeyPath(publicKey);
    publicKeyFile.getParentFile().mkdirs(); // make directories if they do not exist
    final X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey.getEncoded());
    try (FileOutputStream fos = new FileOutputStream(publicKeyFile)) {
        fos.write(x509EncodedKeySpec.getEncoded());
    }

    // Store Private Key.
    final File privateKeyFile = getKeyPath(privateKey);
    privateKeyFile.getParentFile().mkdirs(); // make directories if they do not exist
    final PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
    try (FileOutputStream fos = new FileOutputStream(privateKeyFile)) {
        fos.write(pkcs8EncodedKeySpec.getEncoded());
    }
}
 
開發者ID:stevespringett,項目名稱:Alpine,代碼行數:29,代碼來源:KeyManager.java

示例2: testKeyPairGeneration

import java.security.PrivateKey; //導入方法依賴的package包/類
@Test(groups = TEST_GROUP_UTILS, description = "Used to generate initial key testing pair")
public void testKeyPairGeneration() throws Exception {
    KeyPair keyPair = TokenUtils.generateKeyPair(2048);
    PrivateKey privateKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();
    // extract the encoded private key, this is an unencrypted PKCS#8 private key
    byte[] privateKeyEnc = privateKey.getEncoded();
    byte[] privateKeyPem = Base64.getEncoder().encode(privateKeyEnc);
    String privateKeyPemStr = new String(privateKeyPem);
    System.out.println("-----BEGIN RSA PRIVATE KEY-----");
    int column = 0;
    for(int n = 0; n < privateKeyPemStr.length(); n ++) {
        System.out.print(privateKeyPemStr.charAt(n));
        column ++;
        if(column == 64) {
            System.out.println();
            column = 0;
        }
    }
    System.out.println("\n-----END RSA PRIVATE KEY-----");

    byte[] publicKeyEnc = publicKey.getEncoded();
    byte[] publicKeyPem = Base64.getEncoder().encode(publicKeyEnc);
    String publicKeyPemStr = new String(publicKeyPem);
    System.out.println("-----BEGIN RSA PUBLIC KEY-----");
    column = 0;
    for(int n = 0; n < publicKeyPemStr.length(); n ++) {
        System.out.print(publicKeyPemStr.charAt(n));
        column ++;
        if(column == 64) {
            System.out.println();
            column = 0;
        }
    }
    System.out.println("\n-----END RSA PUBLIC KEY-----");
}
 
開發者ID:eclipse,項目名稱:microprofile-jwt-auth,代碼行數:37,代碼來源:TokenUtilsTest.java

示例3: getEncodedPrivate

import java.security.PrivateKey; //導入方法依賴的package包/類
public static byte[] getEncodedPrivate(PrivateKey pk, String secret) throws Exception {
	final byte[] encoded = pk.getEncoded();
	if (secret == null || secret.length() == 0) {
		return encoded;
	}
	return encrypt(pk.getEncoded(), secret);
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:8,代碼來源:PubkeyUtils.java

示例4: protect

import java.security.PrivateKey; //導入方法依賴的package包/類
/**
 * Protects the given cleartext private key, using the password provided at
 * construction time.
 */
byte[] protect(PrivateKey key)
    throws Exception
{
    // create a random salt (8 bytes)
    byte[] salt = new byte[8];
    SunJCE.getRandom().nextBytes(salt);

    // create PBE parameters from salt and iteration count
    PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, 20);

    // create PBE key from password
    PBEKeySpec pbeKeySpec = new PBEKeySpec(this.password);
    SecretKey sKey = new PBEKey(pbeKeySpec, "PBEWithMD5AndTripleDES");
    pbeKeySpec.clearPassword();

    // encrypt private key
    PBEWithMD5AndTripleDESCipher cipher;
    cipher = new PBEWithMD5AndTripleDESCipher();
    cipher.engineInit(Cipher.ENCRYPT_MODE, sKey, pbeSpec, null);
    byte[] plain = key.getEncoded();
    byte[] encrKey = cipher.engineDoFinal(plain, 0, plain.length);

    // wrap encrypted private key in EncryptedPrivateKeyInfo
    // (as defined in PKCS#8)
    AlgorithmParameters pbeParams =
        AlgorithmParameters.getInstance("PBE", SunJCE.getInstance());
    pbeParams.init(pbeSpec);

    AlgorithmId encrAlg = new AlgorithmId
        (new ObjectIdentifier(PBE_WITH_MD5_AND_DES3_CBC_OID), pbeParams);
    return new EncryptedPrivateKeyInfo(encrAlg,encrKey).getEncoded();
}
 
開發者ID:SunburstApps,項目名稱:OpenJSharp,代碼行數:37,代碼來源:KeyProtector.java

示例5: Curve25519KeyAgreement

import java.security.PrivateKey; //導入方法依賴的package包/類
public Curve25519KeyAgreement(PrivateKey key) throws InvalidKeyException {
    if (!(key instanceof Curve25519PrivateKey)) {
        throw new InvalidKeyException(ALGORITHM
                + " key agreement requires "
                + Curve25519PrivateKey.class.getSimpleName() + " for initialization");
    }
    mPrivateKey = key.getEncoded();
}
 
開發者ID:Alezhka,項目名稱:JWaves,代碼行數:9,代碼來源:Curve25519KeyAgreement.java

示例6: getPEMPrivateKeyFromDER

import java.security.PrivateKey; //導入方法依賴的package包/類
private static String getPEMPrivateKeyFromDER(PrivateKey privateKey) {
	String begin = "-----BEGIN PRIVATE KEY-----";
	String end = "-----END PRIVATE KEY-----";
	PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
	String key = Base64.getEncoder().encodeToString(pkcs8EncodedKeySpec.getEncoded());
	return begin + "\n" + key + "\n" + end;
}
 
開發者ID:gahana,項目名稱:edge-jwt-sample,代碼行數:8,代碼來源:JWTValidatorTest.java

示例7: testPrivate

import java.security.PrivateKey; //導入方法依賴的package包/類
private static void testPrivate(KeyFactory kf, PrivateKey key) throws Exception {
    System.out.println("Testing private key...");
    PrivateKey key2 = (PrivateKey)kf.translateKey(key);
    KeySpec keySpec = kf.getKeySpec(key, ECPrivateKeySpec.class);
    PrivateKey key3 = kf.generatePrivate(keySpec);
    KeySpec pkcs8Spec = kf.getKeySpec(key, PKCS8EncodedKeySpec.class);
    PrivateKey key4 = kf.generatePrivate(pkcs8Spec);
    KeySpec pkcs8Spec2 = new PKCS8EncodedKeySpec(key.getEncoded());
    PrivateKey key5 = kf.generatePrivate(pkcs8Spec2);
    testKey(key, key);
    testKey(key, key2);
    testKey(key, key3);
    testKey(key, key4);
    testKey(key, key5);
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:16,代碼來源:TestKeyFactory.java

示例8: LocalSignatureKeyContainer

import java.security.PrivateKey; //導入方法依賴的package包/類
/**
 * Create the signature key container that can sign using the given key.
 *
 * @param privateKey
 *          Private key to use for signing.
 * @param signingKeyId
 *          Identifier for the signing key.
 */
private LocalSignatureKeyContainer(PrivateKey privateKey, byte[] signingKeyId) {
  checkArgument(privateKey != null, "private key is null");
  checkArgument(signingKeyId != null, "signingKeyId is null");
  checkArgument(signingKeyId.length != 0, "signingKeyId is empty");

  try {
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
    KeyFactory keyFactory = KeyFactory.getInstance(privateKey.getAlgorithm());
    this.signingKey = new PrivateKeyWithId(keyFactory.generatePrivate(keySpec), signingKeyId.clone());
  } catch (InvalidKeySpecException | NoSuchAlgorithmException e) { // Won't be thrown, as we having a working algorithm and key spec.
    throw new IllegalStateException(e);
  }
}
 
開發者ID:mit-ll,項目名稱:PACE,代碼行數:22,代碼來源:LocalSignatureKeyContainer.java

示例9: exportPEM

import java.security.PrivateKey; //導入方法依賴的package包/類
public static String exportPEM(PrivateKey key, String secret) throws NoSuchAlgorithmException, InvalidParameterSpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, InvalidKeySpecException, IllegalBlockSizeException, IOException {
	StringBuilder sb = new StringBuilder();

	byte[] data = key.getEncoded();

	sb.append(PKCS8_START);
	sb.append('\n');

	if (secret != null) {
		byte[] salt = new byte[8];
		SecureRandom random = new SecureRandom();
		random.nextBytes(salt);

		PBEParameterSpec defParams = new PBEParameterSpec(salt, 1);
		AlgorithmParameters params = AlgorithmParameters.getInstance(key.getAlgorithm());

		params.init(defParams);

		PBEKeySpec pbeSpec = new PBEKeySpec(secret.toCharArray());

		SecretKeyFactory keyFact = SecretKeyFactory.getInstance(key.getAlgorithm());
		Cipher cipher = Cipher.getInstance(key.getAlgorithm());
		cipher.init(Cipher.WRAP_MODE, keyFact.generateSecret(pbeSpec), params);

		byte[] wrappedKey = cipher.wrap(key);

		EncryptedPrivateKeyInfo pinfo = new EncryptedPrivateKeyInfo(params, wrappedKey);

		data = pinfo.getEncoded();

		sb.append("Proc-Type: 4,ENCRYPTED\n");
		sb.append("DEK-Info: DES-EDE3-CBC,");
		sb.append(encodeHex(salt));
		sb.append("\n\n");
	}

	int i = sb.length();
	sb.append(Base64.encode(data));
	for (i += 63; i < sb.length(); i += 64) {
		sb.insert(i, "\n");
	}

	sb.append('\n');
	sb.append(PKCS8_END);
	sb.append('\n');

	return sb.toString();
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:49,代碼來源:PubkeyUtils.java

示例10: engineInitSign

import java.security.PrivateKey; //導入方法依賴的package包/類
@Override
protected void engineInitSign(PrivateKey privateKey)
    throws InvalidKeyException {

    int    ret;
    byte[] encodedKey;

    if (this.keyType == KeyType.WC_RSA &&
            !(privateKey instanceof RSAPrivateKey)) {
        throw new InvalidKeyException("Key is not of type RSAPrivateKey");

    } else if (this.keyType == KeyType.WC_ECDSA &&
            !(privateKey instanceof ECPrivateKey)) {
        throw new InvalidKeyException("Key is not of type ECPrivateKey");
    }

    /* get encoded key, returns PKCS#8 formatted private key */
    encodedKey = privateKey.getEncoded();
    if (encodedKey == null)
        throw new InvalidKeyException("Key does not support encoding");

    /* initialize native struct */
    switch (keyType) {
        case WC_RSA:
            if (this.rsa != null)
                this.rsa.releaseNativeStruct();
            this.rsa = new Rsa();
            break;
        case WC_ECDSA:
            if (this.ecc != null)
                this.ecc.releaseNativeStruct();
            this.ecc = new Ecc();
            break;
    }

    wolfCryptInitPrivateKey(privateKey, encodedKey);

    /* init hash object */
    switch (this.digestType) {
        case WC_MD5:
            this.md5.init();
            break;

        case WC_SHA1:
            this.sha.init();
            break;

        case WC_SHA256:
            this.sha256.init();
            break;

        case WC_SHA384:
            this.sha384.init();
            break;

        case WC_SHA512:
            this.sha512.init();
            break;
    }

    if (debug.DEBUG)
        log("init sign with PrivateKey");
}
 
開發者ID:wolfSSL,項目名稱:wolfcrypt-jni,代碼行數:64,代碼來源:WolfCryptSignature.java


注:本文中的java.security.PrivateKey.getEncoded方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。