sun.security.x509.AlgorithmId Java Examples

The following examples show how to use sun.security.x509.AlgorithmId. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PrivateKeyInfo.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Constructs a PKCS#8 PrivateKeyInfo from its ASN.1 encoding.
 */
PrivateKeyInfo(byte[] encoded) throws IOException {
    DerValue val = new DerValue(encoded);

    if (val.tag != DerValue.tag_Sequence)
        throw new IOException("private key parse error: not a sequence");

    // version
    BigInteger parsedVersion = val.data.getBigInteger();
    if (!parsedVersion.equals(VERSION)) {
        throw new IOException("version mismatch: (supported: " +
                              VERSION + ", parsed: " + parsedVersion);
    }

    // privateKeyAlgorithm
    this.algid = AlgorithmId.parse(val.data.getDerValue());

    // privateKey
    this.privkey = val.data.getOctetString();

    // OPTIONAL attributes not supported yet
}
 
Example #2
Source File: PrivateKeyInfo.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Constructs a PKCS#8 PrivateKeyInfo from its ASN.1 encoding.
 */
PrivateKeyInfo(byte[] encoded) throws IOException {
    DerValue val = new DerValue(encoded);

    if (val.tag != DerValue.tag_Sequence)
        throw new IOException("private key parse error: not a sequence");

    // version
    BigInteger parsedVersion = val.data.getBigInteger();
    if (!parsedVersion.equals(VERSION)) {
        throw new IOException("version mismatch: (supported: " +
                              VERSION + ", parsed: " + parsedVersion);
    }

    // privateKeyAlgorithm
    this.algid = AlgorithmId.parse(val.data.getDerValue());

    // privateKey
    this.privkey = val.data.getOctetString();

    // OPTIONAL attributes not supported yet
}
 
Example #3
Source File: SignerInfo.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
public SignerInfo(X500Name  issuerName,
                  BigInteger serial,
                  AlgorithmId digestAlgorithmId,
                  PKCS9Attributes authenticatedAttributes,
                  AlgorithmId digestEncryptionAlgorithmId,
                  byte[] encryptedDigest,
                  PKCS9Attributes unauthenticatedAttributes) {
    this.version = BigInteger.ONE;
    this.issuerName = issuerName;
    this.certificateSerialNumber = serial;
    this.digestAlgorithmId = digestAlgorithmId;
    this.authenticatedAttributes = authenticatedAttributes;
    this.digestEncryptionAlgorithmId = digestEncryptionAlgorithmId;
    this.encryptedDigest = encryptedDigest;
    this.unauthenticatedAttributes = unauthenticatedAttributes;
}
 
Example #4
Source File: RSASignature.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Decode the signature data. Verify that the object identifier matches
 * and return the message digest.
 */
public static byte[] decodeSignature(ObjectIdentifier oid, byte[] signature)
        throws IOException {
    DerInputStream in = new DerInputStream(signature);
    DerValue[] values = in.getSequence(2);
    if ((values.length != 2) || (in.available() != 0)) {
        throw new IOException("SEQUENCE length error");
    }
    AlgorithmId algId = AlgorithmId.parse(values[0]);
    if (algId.getOID().equals((Object)oid) == false) {
        throw new IOException("ObjectIdentifier mismatch: "
            + algId.getOID());
    }
    if (algId.getEncodedParams() != null) {
        throw new IOException("Unexpected AlgorithmId parameters");
    }
    byte[] digest = values[1].getOctetString();
    return digest;
}
 
Example #5
Source File: EncryptedPrivateKeyInfo.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Constructs an <code>EncryptedPrivateKeyInfo</code> from the
 * encryption algorithm parameters and the encrypted data.
 *
 * @param algParams the algorithm parameters for the encryption
 * algorithm. <code>algParams.getEncoded()</code> should return
 * the ASN.1 encoded bytes of the <code>parameters</code> field
 * of the <code>AlgorithmIdentifer</code> component of the
 * <code>EncryptedPrivateKeyInfo</code> type.
 * @param encryptedData encrypted data. The contents of
 * <code>encrypedData</code> are copied to protect against
 * subsequent modification when constructing this object.
 * @exception NullPointerException if <code>algParams</code> or
 * <code>encryptedData</code> is null.
 * @exception IllegalArgumentException if <code>encryptedData</code>
 * is empty, i.e. 0-length.
 * @exception NoSuchAlgorithmException if the specified algName of
 * the specified <code>algParams</code> parameter is not supported.
 */
public EncryptedPrivateKeyInfo(AlgorithmParameters algParams,
    byte[] encryptedData) throws NoSuchAlgorithmException {

    if (algParams == null) {
        throw new NullPointerException("algParams must be non-null");
    }
    this.algid = AlgorithmId.get(algParams);

    if (encryptedData == null) {
        throw new NullPointerException("encryptedData must be non-null");
    } else if (encryptedData.length == 0) {
        throw new IllegalArgumentException("the encryptedData " +
                                            "parameter must not be empty");
    } else {
        this.encryptedData = encryptedData.clone();
    }

    // delay the generation of ASN.1 encoding until
    // getEncoded() is called
    this.encoded = null;
}
 
Example #6
Source File: RSASignature.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Decode the signature data. Verify that the object identifier matches
 * and return the message digest.
 */
public static byte[] decodeSignature(ObjectIdentifier oid, byte[] sig)
        throws IOException {
    // Enforce strict DER checking for signatures
    DerInputStream in = new DerInputStream(sig, 0, sig.length, false);
    DerValue[] values = in.getSequence(2);
    if ((values.length != 2) || (in.available() != 0)) {
        throw new IOException("SEQUENCE length error");
    }
    AlgorithmId algId = AlgorithmId.parse(values[0]);
    if (algId.getOID().equals(oid) == false) {
        throw new IOException("ObjectIdentifier mismatch: "
            + algId.getOID());
    }
    if (algId.getEncodedParams() != null) {
        throw new IOException("Unexpected AlgorithmId parameters");
    }
    byte[] digest = values[1].getOctetString();
    return digest;
}
 
Example #7
Source File: RSASignature.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Decode the signature data. Verify that the object identifier matches
 * and return the message digest.
 */
public static byte[] decodeSignature(ObjectIdentifier oid, byte[] sig)
        throws IOException {
    // Enforce strict DER checking for signatures
    DerInputStream in = new DerInputStream(sig, 0, sig.length, false);
    DerValue[] values = in.getSequence(2);
    if ((values.length != 2) || (in.available() != 0)) {
        throw new IOException("SEQUENCE length error");
    }
    AlgorithmId algId = AlgorithmId.parse(values[0]);
    if (algId.getOID().equals((Object)oid) == false) {
        throw new IOException("ObjectIdentifier mismatch: "
            + algId.getOID());
    }
    if (algId.getEncodedParams() != null) {
        throw new IOException("Unexpected AlgorithmId parameters");
    }
    byte[] digest = values[1].getOctetString();
    return digest;
}
 
Example #8
Source File: EncryptedPrivateKeyInfo.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("fallthrough")
private void checkPKCS8Encoding(byte[] encodedKey)
    throws IOException {
    DerInputStream in = new DerInputStream(encodedKey);
    DerValue[] values = in.getSequence(3);

    switch (values.length) {
    case 4:
        checkTag(values[3], DerValue.TAG_CONTEXT, "attributes");
        /* fall through */
    case 3:
        checkTag(values[0], DerValue.tag_Integer, "version");
        keyAlg = AlgorithmId.parse(values[1]).getName();
        checkTag(values[2], DerValue.tag_OctetString, "privateKey");
        break;
    default:
        throw new IOException("invalid key encoding");
    }
}
 
Example #9
Source File: SignerInfo.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
public SignerInfo(X500Name  issuerName,
                  BigInteger serial,
                  AlgorithmId digestAlgorithmId,
                  PKCS9Attributes authenticatedAttributes,
                  AlgorithmId digestEncryptionAlgorithmId,
                  byte[] encryptedDigest,
                  PKCS9Attributes unauthenticatedAttributes) {
    this.version = BigInteger.ONE;
    this.issuerName = issuerName;
    this.certificateSerialNumber = serial;
    this.digestAlgorithmId = digestAlgorithmId;
    this.authenticatedAttributes = authenticatedAttributes;
    this.digestEncryptionAlgorithmId = digestEncryptionAlgorithmId;
    this.encryptedDigest = encryptedDigest;
    this.unauthenticatedAttributes = unauthenticatedAttributes;
}
 
Example #10
Source File: SignedJarBuilder.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
/** Write the certificate file with a digital signature. */
private void writeSignatureBlock(Signature signature, X509Certificate publicKey,
        PrivateKey privateKey)
        throws IOException, GeneralSecurityException {
    SignerInfo signerInfo = new SignerInfo(
            new X500Name(publicKey.getIssuerX500Principal().getName()),
            publicKey.getSerialNumber(),
            AlgorithmId.get(DIGEST_ALGORITHM),
            AlgorithmId.get(privateKey.getAlgorithm()),
            signature.sign());

    PKCS7 pkcs7 = new PKCS7(
            new AlgorithmId[] { AlgorithmId.get(DIGEST_ALGORITHM) },
            new ContentInfo(ContentInfo.DATA_OID, null),
            new X509Certificate[] { publicKey },
            new SignerInfo[] { signerInfo });

    pkcs7.encodeSignedData(mOutputJar);
}
 
Example #11
Source File: RSASignature.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Decode the signature data. Verify that the object identifier matches
 * and return the message digest.
 */
public static byte[] decodeSignature(ObjectIdentifier oid, byte[] signature)
        throws IOException {
    DerInputStream in = new DerInputStream(signature);
    DerValue[] values = in.getSequence(2);
    if ((values.length != 2) || (in.available() != 0)) {
        throw new IOException("SEQUENCE length error");
    }
    AlgorithmId algId = AlgorithmId.parse(values[0]);
    if (algId.getOID().equals((Object)oid) == false) {
        throw new IOException("ObjectIdentifier mismatch: "
            + algId.getOID());
    }
    if (algId.getEncodedParams() != null) {
        throw new IOException("Unexpected AlgorithmId parameters");
    }
    byte[] digest = values[1].getOctetString();
    return digest;
}
 
Example #12
Source File: EncryptedPrivateKeyInfo.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Constructs an <code>EncryptedPrivateKeyInfo</code> from the
 * encryption algorithm parameters and the encrypted data.
 *
 * @param algParams the algorithm parameters for the encryption
 * algorithm. <code>algParams.getEncoded()</code> should return
 * the ASN.1 encoded bytes of the <code>parameters</code> field
 * of the <code>AlgorithmIdentifer</code> component of the
 * <code>EncryptedPrivateKeyInfo</code> type.
 * @param encryptedData encrypted data. The contents of
 * <code>encrypedData</code> are copied to protect against
 * subsequent modification when constructing this object.
 * @exception NullPointerException if <code>algParams</code> or
 * <code>encryptedData</code> is null.
 * @exception IllegalArgumentException if <code>encryptedData</code>
 * is empty, i.e. 0-length.
 * @exception NoSuchAlgorithmException if the specified algName of
 * the specified <code>algParams</code> parameter is not supported.
 */
public EncryptedPrivateKeyInfo(AlgorithmParameters algParams,
    byte[] encryptedData) throws NoSuchAlgorithmException {

    if (algParams == null) {
        throw new NullPointerException("algParams must be non-null");
    }
    this.algid = AlgorithmId.get(algParams);

    if (encryptedData == null) {
        throw new NullPointerException("encryptedData must be non-null");
    } else if (encryptedData.length == 0) {
        throw new IllegalArgumentException("the encryptedData " +
                                            "parameter must not be empty");
    } else {
        this.encryptedData = encryptedData.clone();
    }

    // delay the generation of ASN.1 encoding until
    // getEncoded() is called
    this.encoded = null;
}
 
Example #13
Source File: CspHelper.java    From julongchain with Apache License 2.0 6 votes vote down vote up
static IKey generatePrivateKey(String keystorePath) throws JulongChainException {
    try {
        IKey priv = CSP.keyGen(new SM2KeyGenOpts() {
            @Override
            public boolean isEphemeral() {
                return true;
            }
        });
        byte[] encodedData = encodePrivateKeyPKCS8(priv.toBytes(), new AlgorithmId(SM2PublicKeyImpl.SM2_OID));
        String path = Paths.get(keystorePath, Hex.toHexString(priv.ski()) + "_sk").toString();
        Util.pemExport(path, "PRIVATE KEY", encodedData);
        return priv;
    } catch (Exception e) {
        throw new JulongChainException("An error occurred" + e);
    }
}
 
Example #14
Source File: PrivateKeyInfo.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Constructs a PKCS#8 PrivateKeyInfo from its ASN.1 encoding.
 */
PrivateKeyInfo(byte[] encoded) throws IOException {
    DerValue val = new DerValue(encoded);

    if (val.tag != DerValue.tag_Sequence)
        throw new IOException("private key parse error: not a sequence");

    // version
    BigInteger parsedVersion = val.data.getBigInteger();
    if (!parsedVersion.equals(VERSION)) {
        throw new IOException("version mismatch: (supported: " +
                              VERSION + ", parsed: " + parsedVersion);
    }

    // privateKeyAlgorithm
    this.algid = AlgorithmId.parse(val.data.getDerValue());

    // privateKey
    this.privkey = val.data.getOctetString();

    // OPTIONAL attributes not supported yet
}
 
Example #15
Source File: CryptoUtil.java    From julongchain with Apache License 2.0 6 votes vote down vote up
/**
 * 读取私钥文件
 * @param skPath
 * @return
 * @throws CspException
 * @throws IOException
 */
public static byte[] readSkFile(String skPath) throws CspException, IOException {
    InputStreamReader reader = new InputStreamReader(new FileInputStream(skPath));
    PemReader pemReader = new PemReader(reader);
    PemObject pemObject = pemReader.readPemObject();
    reader.close();
    byte[] encodedData = pemObject.getContent();
    DerValue derValue = new DerValue(new ByteArrayInputStream(encodedData));
    byte[] rawPrivateKey = null;
    if (derValue.tag != 48) {
        throw new CspException("invalid key format");
    } else {
        BigInteger version = derValue.data.getBigInteger();
        if (!version.equals(BigInteger.ZERO)) {
            throw new CspException("version mismatch: (supported: " + Debug.toHexString(BigInteger.ZERO) + ", parsed: " + Debug.toHexString(version));
        } else {
            AlgorithmId algId = AlgorithmId.parse(derValue.data.getDerValue());
            rawPrivateKey = derValue.data.getOctetString();
        }
        return rawPrivateKey;
    }
}
 
Example #16
Source File: ECPrivateKeyImpl.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Construct a key from its components. Used by the
 * KeyFactory.
 */
public ECPrivateKeyImpl(BigInteger s, ECParameterSpec params)
        throws InvalidKeyException {
    this.s = s;
    this.params = params;
    // generate the encoding
    algid = new AlgorithmId
        (AlgorithmId.EC_oid, ECParameters.getAlgorithmParameters(params));
    try {
        DerOutputStream out = new DerOutputStream();
        out.putInteger(1); // version 1
        byte[] privBytes = ECUtil.trimZeroes(s.toByteArray());
        out.putOctetString(privBytes);
        DerValue val =
            new DerValue(DerValue.tag_Sequence, out.toByteArray());
        key = val.toByteArray();
    } catch (IOException exc) {
        // should never occur
        throw new InvalidKeyException(exc);
    }
}
 
Example #17
Source File: ECPrivateKeyImpl.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Construct a key from its components. Used by the
 * KeyFactory.
 */
public ECPrivateKeyImpl(BigInteger s, ECParameterSpec params)
        throws InvalidKeyException {
    this.s = s;
    this.params = params;
    // generate the encoding
    algid = new AlgorithmId
        (AlgorithmId.EC_oid, ECParameters.getAlgorithmParameters(params));
    try {
        DerOutputStream out = new DerOutputStream();
        out.putInteger(1); // version 1
        byte[] privBytes = ECUtil.trimZeroes(s.toByteArray());
        out.putOctetString(privBytes);
        DerValue val =
            new DerValue(DerValue.tag_Sequence, out.toByteArray());
        key = val.toByteArray();
    } catch (IOException exc) {
        // should never occur
        throw new InvalidKeyException(exc);
    }
}
 
Example #18
Source File: MacData.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
MacData(String algName, byte[] digest, byte[] salt, int iterations)
    throws NoSuchAlgorithmException
{
    if (algName == null)
       throw new NullPointerException("the algName parameter " +
                                           "must be non-null");

    AlgorithmId algid = AlgorithmId.get(algName);
    this.digestAlgorithmName = algid.getName();
    this.digestAlgorithmParams = algid.getParameters();

    if (digest == null) {
        throw new NullPointerException("the digest " +
                                       "parameter must be non-null");
    } else if (digest.length == 0) {
        throw new IllegalArgumentException("the digest " +
                                            "parameter must not be empty");
    } else {
        this.digest = digest.clone();
    }

    this.macSalt = salt;
    this.iterations = iterations;

    // delay the generation of ASN.1 encoding until
    // getEncoded() is called
    this.encoded = null;

}
 
Example #19
Source File: TimestampToken.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private void parse(byte[] timestampTokenInfo) throws IOException {

        DerValue tstInfo = new DerValue(timestampTokenInfo);
        if (tstInfo.tag != DerValue.tag_Sequence) {
            throw new IOException("Bad encoding for timestamp token info");
        }
        // Parse version
        version = tstInfo.data.getInteger();

        // Parse policy
        policy = tstInfo.data.getOID();

        // Parse messageImprint
        DerValue messageImprint = tstInfo.data.getDerValue();
        hashAlgorithm = AlgorithmId.parse(messageImprint.data.getDerValue());
        hashedMessage = messageImprint.data.getOctetString();

        // Parse serialNumber
        serialNumber = tstInfo.data.getBigInteger();

        // Parse genTime
        genTime = tstInfo.data.getGeneralizedTime();

        // Parse optional elements, if present
        while (tstInfo.data.available() > 0) {
            DerValue d = tstInfo.data.getDerValue();
            if (d.tag == DerValue.tag_Integer) {    // must be the nonce
                nonce = d.getBigInteger();
                break;
            }

            // Additional fields:
            // Parse accuracy
            // Parse ordering
            // Parse tsa
            // Parse extensions
        }
    }
 
Example #20
Source File: NonStandardNames.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        byte[] data = "Hello".getBytes();
        X500Name n = new X500Name("cn=Me");

        CertAndKeyGen cakg = new CertAndKeyGen("RSA", "SHA256withRSA");
        cakg.generate(1024);
        X509Certificate cert = cakg.getSelfCertificate(n, 1000);

        MessageDigest md = MessageDigest.getInstance("SHA-256");
        PKCS9Attributes authed = new PKCS9Attributes(new PKCS9Attribute[]{
            new PKCS9Attribute(PKCS9Attribute.CONTENT_TYPE_OID, ContentInfo.DATA_OID),
            new PKCS9Attribute(PKCS9Attribute.MESSAGE_DIGEST_OID, md.digest(data)),
        });

        Signature s = Signature.getInstance("SHA256withRSA");
        s.initSign(cakg.getPrivateKey());
        s.update(authed.getDerEncoding());
        byte[] sig = s.sign();

        SignerInfo signerInfo = new SignerInfo(
                n,
                cert.getSerialNumber(),
                AlgorithmId.get("SHA-256"),
                authed,
                AlgorithmId.get("SHA256withRSA"),
                sig,
                null
                );

        PKCS7 pkcs7 = new PKCS7(
                new AlgorithmId[] {signerInfo.getDigestAlgorithmId()},
                new ContentInfo(data),
                new X509Certificate[] {cert},
                new SignerInfo[] {signerInfo});

        if (pkcs7.verify(signerInfo, data) == null) {
            throw new Exception("Not verified");
        }
    }
 
Example #21
Source File: X509CertSelectorTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private ObjectIdentifier getCertPubKeyAlgOID(X509Certificate xcert) throws IOException {
    byte[] encodedKey = xcert.getPublicKey().getEncoded();
    DerValue val = new DerValue(encodedKey);
    if (val.tag != DerValue.tag_Sequence) {
        throw new RuntimeException("invalid key format");
    }

    return AlgorithmId.parse(val.data.getDerValue()).getOID();
}
 
Example #22
Source File: EncryptedPrivateKeyInfo.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructs (i.e., parses) an <code>EncryptedPrivateKeyInfo</code> from
 * its ASN.1 encoding.
 * @param encoded the ASN.1 encoding of this object. The contents of
 * the array are copied to protect against subsequent modification.
 * @exception NullPointerException if the <code>encoded</code> is null.
 * @exception IOException if error occurs when parsing the ASN.1 encoding.
 */
public EncryptedPrivateKeyInfo(byte[] encoded)
    throws IOException {
    if (encoded == null) {
        throw new NullPointerException("the encoded parameter " +
                                       "must be non-null");
    }
    this.encoded = encoded.clone();
    DerValue val = new DerValue(this.encoded);

    DerValue[] seq = new DerValue[2];

    seq[0] = val.data.getDerValue();
    seq[1] = val.data.getDerValue();

    if (val.data.available() != 0) {
        throw new IOException("overrun, bytes = " + val.data.available());
    }

    this.algid = AlgorithmId.parse(seq[0]);
    if (seq[0].data.available() != 0) {
        throw new IOException("encryptionAlgorithm field overrun");
    }

    this.encryptedData = seq[1].getOctetString();
    if (seq[1].data.available() != 0) {
        throw new IOException("encryptedData field overrun");
    }
}
 
Example #23
Source File: SignatureFile.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the name of the block file, ending with a block suffix
 * such as ".DSA". */
public String getBlockName() {
    String suffix = "DSA";
    if (signatureBlock != null) {
        SignerInfo info = signatureBlock.getSignerInfos()[0];
        suffix = info.getDigestEncryptionAlgorithmId().getName();
        String temp = AlgorithmId.getEncAlgFromSigAlg(suffix);
        if (temp != null) suffix = temp;
    }
    return "META-INF/" + rawName + "." + suffix;
}
 
Example #24
Source File: PKCS7.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Construct an initialized PKCS7 block.
 *
 * @param digestAlgorithmIds the message digest algorithm identifiers.
 * @param contentInfo the content information.
 * @param certificates an array of X.509 certificates.
 * @param crls an array of CRLs
 * @param signerInfos an array of signer information.
 */
public PKCS7(AlgorithmId[] digestAlgorithmIds,
             ContentInfo contentInfo,
             X509Certificate[] certificates,
             X509CRL[] crls,
             SignerInfo[] signerInfos) {

    version = BigInteger.ONE;
    this.digestAlgorithmIds = digestAlgorithmIds;
    this.contentInfo = contentInfo;
    this.certificates = certificates;
    this.crls = crls;
    this.signerInfos = signerInfos;
}
 
Example #25
Source File: X509CertPath.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Encode the CertPath using PKCS#7 format.
 *
 * @return a byte array containing the binary encoding of the PKCS#7 object
 * @exception CertificateEncodingException if an exception occurs
 */
private byte[] encodePKCS7() throws CertificateEncodingException {
    PKCS7 p7 = new PKCS7(new AlgorithmId[0],
                         new ContentInfo(ContentInfo.DATA_OID, null),
                         certs.toArray(new X509Certificate[certs.size()]),
                         new SignerInfo[0]);
    DerOutputStream derout = new DerOutputStream();
    try {
        p7.encodeSignedData(derout);
    } catch (IOException ioe) {
        throw new CertificateEncodingException(ioe.getMessage());
    }
    return derout.toByteArray();
}
 
Example #26
Source File: CertificateGeneration.java    From protect with MIT License 5 votes vote down vote up
/**
 * Creates a certificate from an X509Certificate info and a raw signature
 * 
 * @param toBeSignedCertificateInfo
 * @param certificateSigningAlgorithm
 * @param signature
 * @return
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws NoSuchProviderException
 * @throws SignatureException
 */
public static final X509Certificate createCertificateFromTbsAndSignature(
		final X509CertInfo toBeSignedCertificateInfo, final String certificateSigningAlgorithm,
		final byte[] signature) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException,
		NoSuchProviderException, SignatureException {

	try (DerOutputStream out = new DerOutputStream(); DerOutputStream tmp = new DerOutputStream();) {

		// Append the certificate information
		toBeSignedCertificateInfo.encode(tmp);

		// Append the signature algorithm
		final AlgorithmId algId = AlgorithmId.get(certificateSigningAlgorithm);
		algId.encode(tmp);

		// Append the signature
		tmp.putBitString(signature);

		// Wrap the signed data in a SEQUENCE { data, algorithm, sig }
		out.write(DerValue.tag_Sequence, tmp);
		byte[] signedCert = out.toByteArray();

		// Create a certificate
		return new X509CertImpl(signedCert);

	} catch (IOException e) {
		throw new CertificateEncodingException(e.toString());
	}
}
 
Example #27
Source File: KeyProtector.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example #28
Source File: KeyProtector.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example #29
Source File: MacData.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
MacData(AlgorithmParameters algParams, byte[] digest,
    byte[] salt, int iterations) throws NoSuchAlgorithmException
{
    if (algParams == null)
       throw new NullPointerException("the algParams parameter " +
                                           "must be non-null");

    AlgorithmId algid = AlgorithmId.get(algParams);
    this.digestAlgorithmName = algid.getName();
    this.digestAlgorithmParams = algid.getParameters();

    if (digest == null) {
        throw new NullPointerException("the digest " +
                                       "parameter must be non-null");
    } else if (digest.length == 0) {
        throw new IllegalArgumentException("the digest " +
                                            "parameter must not be empty");
    } else {
        this.digest = digest.clone();
    }

    this.macSalt = salt;
    this.iterations = iterations;

    // delay the generation of ASN.1 encoding until
    // getEncoded() is called
    this.encoded = null;

}
 
Example #30
Source File: PKCS12KeyStore.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private static ObjectIdentifier mapPBEAlgorithmToOID(String algorithm)
    throws NoSuchAlgorithmException {
    // Check for PBES2 algorithms
    if (algorithm.toLowerCase(Locale.ENGLISH).startsWith("pbewithhmacsha")) {
        return pbes2_OID;
    }
    return AlgorithmId.get(algorithm).getOID();
}