当前位置: 首页>>代码示例>>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;未经允许,请勿转载。