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


Java PublicKey.getEncoded方法代码示例

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


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

示例1: save

import java.security.PublicKey; //导入方法依赖的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: encodePublicKey

import java.security.PublicKey; //导入方法依赖的package包/类
private static byte[] encodePublicKey(PublicKey publicKey)
        throws InvalidKeyException, NoSuchAlgorithmException {
    byte[] encodedPublicKey = null;
    if ("X.509".equals(publicKey.getFormat())) {
        encodedPublicKey = publicKey.getEncoded();
    }
    if (encodedPublicKey == null) {
        try {
            encodedPublicKey =
                    KeyFactory.getInstance(publicKey.getAlgorithm())
                            .getKeySpec(publicKey, X509EncodedKeySpec.class)
                            .getEncoded();
        } catch (InvalidKeySpecException e) {
            throw new InvalidKeyException(
                    "Failed to obtain X.509 encoded form of public key " + publicKey
                            + " of class " + publicKey.getClass().getName(),
                    e);
        }
    }
    if ((encodedPublicKey == null) || (encodedPublicKey.length == 0)) {
        throw new InvalidKeyException(
                "Failed to obtain X.509 encoded form of public key " + publicKey
                        + " of class " + publicKey.getClass().getName());
    }
    return encodedPublicKey;
}
 
开发者ID:F8LEFT,项目名称:FApkSigner,代码行数:27,代码来源:V2SchemeSigner.java

示例3: getAlgorithmIdentifier

import java.security.PublicKey; //导入方法依赖的package包/类
protected static AlgorithmIdentifier getAlgorithmIdentifier(
    PublicKey key)
    throws CertPathValidatorException
{
    try
    {
        ASN1InputStream aIn = new ASN1InputStream(key.getEncoded());

        SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(aIn.readObject());

        return info.getAlgorithmId();
    }
    catch (Exception e)
    {
        throw new ExtCertPathValidatorException("Subject public key cannot be decoded.", e);
    }
}
 
开发者ID:Appdome,项目名称:ipack,代码行数:18,代码来源:CertPathValidatorUtilities.java

示例4: addVerifierKey

import java.security.PublicKey; //导入方法依赖的package包/类
/**
 * Add a verifier key.
 *
 * @param verifierKey
 *          The public key used for verification.
 * @param id
 *          Id of the key.
 * @param copy
 *          Whether to copy the key.
 */
private void addVerifierKey(PublicKey verifierKey, byte[] id, boolean copy) {
  checkArgument(verifierKey != null, "verifierKey is null");
  checkArgument(id != null, "id is null");
  checkArgument(id.length != 0, "id is empty");

  if (copy) {
    try {
      X509EncodedKeySpec keySpec = new X509EncodedKeySpec(verifierKey.getEncoded());
      KeyFactory keyFactory = KeyFactory.getInstance(verifierKey.getAlgorithm());
      this.verificationKeys.put(ByteBuffer.wrap(id.clone()), keyFactory.generatePublic(keySpec));
    } catch (InvalidKeySpecException | NoSuchAlgorithmException e) { // Won't be thrown, as we having a working algorithm and key spec.
      throw new IllegalStateException(e);
    }
  } else {
    this.verificationKeys.put(ByteBuffer.wrap(id), verifierKey);
  }
}
 
开发者ID:mit-ll,项目名称:PACE,代码行数:28,代码来源:LocalSignatureKeyContainer.java

示例5: KeyIdentifier

import java.security.PublicKey; //导入方法依赖的package包/类
/**
 * Creates a KeyIdentifier from a public-key value.
 *
 * <p>From RFC2459: Two common methods for generating key identifiers from
 * the public key are:
 * <ol>
 * <li>The keyIdentifier is composed of the 160-bit SHA-1 hash of the
 * value of the BIT STRING subjectPublicKey (excluding the tag,
 * length, and number of unused bits).
 *
 * <li>The keyIdentifier is composed of a four bit type field with
 * the value 0100 followed by the least significant 60 bits of the
 * SHA-1 hash of the value of the BIT STRING subjectPublicKey.
 * </ol>
 * <p>This method supports method 1.
 *
 * @param pubKey the public key from which to construct this KeyIdentifier
 * @throws IOException on parsing errors
 */
public KeyIdentifier(PublicKey pubKey)
    throws IOException
{
    DerValue algAndKey = new DerValue(pubKey.getEncoded());
    if (algAndKey.tag != DerValue.tag_Sequence)
        throw new IOException("PublicKey value is not a valid "
                              + "X.509 public key");

    AlgorithmId algid = AlgorithmId.parse(algAndKey.data.getDerValue());
    byte[] key = algAndKey.data.getUnalignedBitString().toByteArray();

    MessageDigest md = null;
    try {
        md = MessageDigest.getInstance("SHA1");
    } catch (NoSuchAlgorithmException e3) {
        throw new IOException("SHA1 not supported");
    }
    md.update(key);
    this.octetString = md.digest();
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:40,代码来源:KeyIdentifier.java

示例6: KeyIdentifier

import java.security.PublicKey; //导入方法依赖的package包/类
/**
 * Creates a KeyIdentifier from a public-key value.
 *
 * <p>From RFC2459: Two common methods for generating key identifiers from
 * the public key are:
 * <ol>
 * <li>The keyIdentifier is composed of the 160-bit SHA-1 hash of the
 * value of the BIT STRING subjectPublicKey (excluding the tag,
 * length, and number of unused bits).
 * <p>
 * <li>The keyIdentifier is composed of a four bit type field with
 * the value 0100 followed by the least significant 60 bits of the
 * SHA-1 hash of the value of the BIT STRING subjectPublicKey.
 * </ol>
 * <p>This method supports method 1.
 *
 * @param pubKey the public key from which to construct this KeyIdentifier
 * @throws IOException on parsing errors
 */
public KeyIdentifier(PublicKey pubKey)
    throws IOException
{
    DerValue algAndKey = new DerValue(pubKey.getEncoded());
    if (algAndKey.tag != DerValue.tag_Sequence)
        throw new IOException("PublicKey value is not a valid "
                              + "X.509 public key");

    AlgorithmId algid = AlgorithmId.parse(algAndKey.data.getDerValue());
    byte[] key = algAndKey.data.getUnalignedBitString().toByteArray();

    MessageDigest md = null;
    try {
        md = MessageDigest.getInstance("SHA1");
    } catch (NoSuchAlgorithmException e3) {
        throw new IOException("SHA1 not supported");
    }
    md.update(key);
    this.octetString = md.digest();
}
 
开发者ID:SunburstApps,项目名称:OpenJSharp,代码行数:40,代码来源:KeyIdentifier.java

示例7: engineInitVerify

import java.security.PublicKey; //导入方法依赖的package包/类
protected void engineInitVerify(
    PublicKey   publicKey)
    throws InvalidKeyException
{
    CipherParameters    param;

    if (publicKey instanceof ECPublicKey)
    {
        param = ECUtil.generatePublicKeyParameter(publicKey);
    }
    else if (publicKey instanceof GOST3410Key)
    {
        param = GOST3410Util.generatePublicKeyParameter(publicKey);
    }
    else
    {
        try
        {
            byte[]  bytes = publicKey.getEncoded();

            publicKey = BouncyCastleProvider.getPublicKey(SubjectPublicKeyInfo.getInstance(bytes));

            if (publicKey instanceof ECPublicKey)
            {
                param = ECUtil.generatePublicKeyParameter(publicKey);
            }
            else
            {
                throw new InvalidKeyException("can't recognise key type in DSA based signer");
            }
        }
        catch (Exception e)
        {
            throw new InvalidKeyException("can't recognise key type in DSA based signer");
        }
    }

    digest.reset();
    signer.init(false, param);
}
 
开发者ID:Appdome,项目名称:ipack,代码行数:41,代码来源:SignatureSpi.java

示例8: setSubjectPublicKey

import java.security.PublicKey; //导入方法依赖的package包/类
/**
 * Sets the subjectPublicKey criterion. The
 * {@code X509Certificate} must contain the specified subject public
 * key. If {@code null}, no subjectPublicKey check will be done.
 *
 * @param key the subject public key to check for (or {@code null})
 * @see #getSubjectPublicKey
 */
public void setSubjectPublicKey(PublicKey key) {
    if (key == null) {
        subjectPublicKey = null;
        subjectPublicKeyBytes = null;
    } else {
        subjectPublicKey = key;
        subjectPublicKeyBytes = key.getEncoded();
    }
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:18,代码来源:X509CertSelector.java

示例9: testKeyPairGeneration

import java.security.PublicKey; //导入方法依赖的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

示例10: signRawTransaction

import java.security.PublicKey; //导入方法依赖的package包/类
/**
 * Signs the raw bytes using a travel document.
 * Follows the steps in this answer: https://bitcoin.stackexchange.com/a/5241
 * @return signedRawTransaction
 */
public byte[] signRawTransaction(PublicKey pubkey, byte[][] parts, PassportConnection pcon) throws Exception {
    byte[] rawTransaction = Bytes.concat(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5],
            parts[6], parts[7], parts[8], parts[9], parts[10], parts[11], parts[12]);

    // Double hash transaction
    byte[] step14 = Sha256Hash.hash(Sha256Hash.hash(rawTransaction));

    // Generate signature and get publickey
    byte[] multiSignature = new byte[320];
    byte[] hashPart;

    for (int i = 0; i < 4; i++) {
        hashPart = Arrays.copyOfRange(step14, i * 8, i * 8 + 8);
        System.arraycopy(pcon.signData(hashPart), 0, multiSignature, i * 80, 80);
    }

    byte[] signatureLength = Util.hexStringToByteArray("fd97014d4101");
    byte[] hashCodeType = Util.hexStringToByteArray("01");
    byte[] publicKeyASN = pubkey.getEncoded();

    byte[] publicKey = new byte[81];
    System.arraycopy(publicKeyASN, publicKeyASN.length-81, publicKey, 0, 81);

    byte[] publickeyLength = Util.hexStringToByteArray("4c51");

    // Set signature and pubkey in format
    byte[] step16 = Bytes.concat(signatureLength, multiSignature, hashCodeType, publickeyLength, publicKey);

    // Update transaction with signature and remove hash code type
    byte[] step19 = Bytes.concat(parts[0], parts[1], parts[2], parts[3], step16, parts[6],
            parts[7], parts[8], parts[9], parts[10], parts[11], parts[12]);

    return step19;
}
 
开发者ID:digital-voting-pass,项目名称:polling-station-app,代码行数:40,代码来源:PassportTransactionFormatter.java

示例11: CertId

import java.security.PublicKey; //导入方法依赖的package包/类
public CertId(X500Principal issuerName, PublicKey issuerKey,
              SerialNumber serialNumber) throws IOException {

    // compute issuerNameHash
    MessageDigest md = null;
    try {
        md = MessageDigest.getInstance("SHA1");
    } catch (NoSuchAlgorithmException nsae) {
        throw new IOException("Unable to create CertId", nsae);
    }
    hashAlgId = SHA1_ALGID;
    md.update(issuerName.getEncoded());
    issuerNameHash = md.digest();

    // compute issuerKeyHash (remove the tag and length)
    byte[] pubKey = issuerKey.getEncoded();
    DerValue val = new DerValue(pubKey);
    DerValue[] seq = new DerValue[2];
    seq[0] = val.data.getDerValue(); // AlgorithmID
    seq[1] = val.data.getDerValue(); // Key
    byte[] keyBytes = seq[1].getBitString();
    md.update(keyBytes);
    issuerKeyHash = md.digest();
    certSerialNumber = serialNumber;

    if (debug) {
        HexDumpEncoder encoder = new HexDumpEncoder();
        System.out.println("Issuer Name is " + issuerName);
        System.out.println("issuerNameHash is " +
            encoder.encodeBuffer(issuerNameHash));
        System.out.println("issuerKeyHash is " +
            encoder.encodeBuffer(issuerKeyHash));
        System.out.println("SerialNumber is " + serialNumber.getNumber());
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:36,代码来源:CertId.java

示例12: getPEMPublicKeyFromDER

import java.security.PublicKey; //导入方法依赖的package包/类
private static String getPEMPublicKeyFromDER(PublicKey publicKey) {
	String begin = "-----BEGIN PUBLIC KEY-----";
	String end = "-----END PUBLIC KEY-----";
	X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey.getEncoded());
	String key = Base64.getEncoder().encodeToString(x509EncodedKeySpec.getEncoded());
	return begin + "\n" + key + "\n" + end;
}
 
开发者ID:gahana,项目名称:edge-jwt-sample,代码行数:8,代码来源:JWTValidatorTest.java

示例13: testPublic

import java.security.PublicKey; //导入方法依赖的package包/类
private static void testPublic(KeyFactory kf, PublicKey key) throws Exception {
    System.out.println("Testing public key...");
    PublicKey key2 = (PublicKey)kf.translateKey(key);
    KeySpec keySpec = kf.getKeySpec(key, ECPublicKeySpec.class);
    PublicKey key3 = kf.generatePublic(keySpec);
    KeySpec x509Spec = kf.getKeySpec(key, X509EncodedKeySpec.class);
    PublicKey key4 = kf.generatePublic(x509Spec);
    KeySpec x509Spec2 = new X509EncodedKeySpec(key.getEncoded());
    PublicKey key5 = kf.generatePublic(x509Spec2);
    testKey(key, key);
    testKey(key, key2);
    testKey(key, key3);
    testKey(key, key4);
    testKey(key, key5);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:16,代码来源:TestKeyFactory.java

示例14: createCertID

import java.security.PublicKey; //导入方法依赖的package包/类
private static CertID createCertID(AlgorithmIdentifier hashAlg, X509Certificate issuerCert,
    ASN1Integer serialNumber, String provider)
    throws OCSPException
{
    try
    {
        MessageDigest digest = OCSPUtil.createDigestInstance(hashAlg.getAlgorithm() .getId(),
            provider);

        X509Principal issuerName = PrincipalUtil.getSubjectX509Principal(issuerCert);

        digest.update(issuerName.getEncoded());

        ASN1OctetString issuerNameHash = new DEROctetString(digest.digest());
        PublicKey issuerKey = issuerCert.getPublicKey();

        ASN1InputStream aIn = new ASN1InputStream(issuerKey.getEncoded());
        SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(aIn.readObject());

        digest.update(info.getPublicKeyData().getBytes());

        ASN1OctetString issuerKeyHash = new DEROctetString(digest.digest());

        return new CertID(hashAlg, issuerNameHash, issuerKeyHash, serialNumber);
    }
    catch (Exception e)
    {
        throw new OCSPException("problem creating ID: " + e, e);
    }
}
 
开发者ID:Appdome,项目名称:ipack,代码行数:31,代码来源:CertificateID.java


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