你如何从Java X509证书中读取CertificatePolicy对象?

时间:2014-05-01 14:42:23

标签: certificate x509certificate x509 digital-certificate pki

我可以使用这样的方法为SKID(主题密钥标识符)执行此操作。什么是在JAVA本地执行此操作的可比方法(不使用任何第三方库,如充气城堡)?

我有一个x509证书,里面有这个东西,我希望能够从证书中读出这个:

"....

[3]: ObjectId: 2.5.29.32 Criticality=false
CertificatePolicies [
  [CertificatePolicyId: [5.6.7.8.9.1.2.3.4]
[]  ]
]
...
"


...

import sun.security.util.DerInputStream;
import sun.security.util.DerValue;
import sun.security.x509.AuthorityKeyIdentifierExtension;
import sun.security.x509.CertificatePolicyMap;
import sun.security.x509.CertificatePolicySet;
import sun.security.x509.KeyIdentifier;
import sun.security.x509.SubjectKeyIdentifierExtension;
....

private static final String SUBJECT_KEY_ID = "2.5.29.14";

.....

/**
 * Get the Subject Key Identifier of the PKI Certificate
 * 
 * @return A String containing the SKID
 * @throws CertificateParsingException 
 */
public String getSubjectKeyIdentifier() 
    throws IllegalStateException, CertificateParsingException 
{
    logger.debug("entered");

    // if the variable hasn't yet been initialized with a value, initialize it, else return the existing one.
    if (subjectKeyIDString == null)
    {
        if (cert == null) 
        {
            IllegalStateException ise = new IllegalStateException(ERROR_MSG_NOT_INITIALIZED);
            logger.error(ise);

            throw ise;            
        }

        byte[] skidCertBytes = cert.getExtensionValue(SUBJECT_KEY_ID);

        if (skidCertBytes == null) 
        {
          return null;
        }

        String skidByteString = null;

        try
        {
            DerValue skidDer = new DerValue(skidCertBytes);
            byte[] skidDerBytes = skidDer.getDataBytes();

            // create a SubjectKeyIdentifierExtension object
            SubjectKeyIdentifierExtension skid = new SubjectKeyIdentifierExtension(Boolean.FALSE, skidDerBytes);

            boolean isCritical = skid.isCritical();
            logger.debug("isCritical: [" + isCritical + "]");

            byte[] skidValueBytes = skid.getExtensionValue();

            // go inside the SKID object and get the KID (KeyIdentifier) object
            KeyIdentifier kid = new KeyIdentifier(skidValueBytes);

            // get the bytes of the object (strips off the first two bytes, type & length bytes)
            byte[] kidBytes = kid.getIdentifier();

            // convert the KID bytes to a DerValue object
            DerValue kidDerValue = new DerValue(kidBytes);
            byte[] kidByteValue = kidDerValue.getOctetString();

            // get the SKID->KID->string value 
            skidByteString = byteArrayToHexString(kidByteValue, true);
        }
        catch (IOException e)
        {
            logger.error(e);
        }

        logger.debug(skidByteString);
        return skidByteString;
    }
    else
    {
        return subjectKeyIDString;
    }
}

0 个答案:

没有答案