下面列出了怎么用java.security.cert.CertificateParsingException的API类实例代码及写法,或者点击链接到github查看源代码。
public static boolean validateSubjectAltNameField(X509Certificate certificate, int field,
Predicate<Object> fieldValidator) throws UaException {
try {
Collection<List<?>> subjectAltNames = certificate.getSubjectAlternativeNames();
if (subjectAltNames == null) subjectAltNames = Collections.emptyList();
for (List<?> idAndValue : subjectAltNames) {
if (idAndValue != null && idAndValue.size() == 2) {
if (idAndValue.get(0).equals(field)) {
if (fieldValidator.test(idAndValue.get(1))) {
return true;
}
}
}
}
return false;
} catch (CertificateParsingException e) {
throw new UaException(StatusCodes.Bad_CertificateInvalid, e);
}
}
private java.security.cert.Certificate readDERCertificate(
ASN1InputStream dIn)
throws IOException, CertificateParsingException
{
ASN1Sequence seq = (ASN1Sequence)dIn.readObject();
if (seq.size() > 1
&& seq.getObjectAt(0) instanceof ASN1ObjectIdentifier)
{
if (seq.getObjectAt(0).equals(PKCSObjectIdentifiers.signedData))
{
sData = SignedData.getInstance(ASN1Sequence.getInstance(
(ASN1TaggedObject)seq.getObjectAt(1), true)).getCertificates();
return getCertificate();
}
}
return new X509CertificateObject(
Certificate.getInstance(seq));
}
public static ASN1Sequence getAsn1SequenceFromStream(final ASN1InputStream asn1InputStream)
throws IOException, CertificateParsingException {
ASN1Primitive asn1Primitive = asn1InputStream.readObject();
if (!(asn1Primitive instanceof ASN1OctetString)) {
throw new CertificateParsingException(
"Expected octet stream, found " + asn1Primitive.getClass().getName());
}
try (ASN1InputStream seqInputStream = new ASN1InputStream(
((ASN1OctetString) asn1Primitive).getOctets())) {
asn1Primitive = seqInputStream.readObject();
if (!(asn1Primitive instanceof ASN1Sequence)) {
throw new CertificateParsingException(
"Expected sequence, found " + asn1Primitive.getClass().getName());
}
return (ASN1Sequence) asn1Primitive;
}
}
private java.security.cert.Certificate readDERCertificate(
ASN1InputStream dIn)
throws IOException, CertificateParsingException
{
ASN1Sequence seq = (ASN1Sequence)dIn.readObject();
if (seq.size() > 1
&& seq.getObjectAt(0) instanceof ASN1ObjectIdentifier)
{
if (seq.getObjectAt(0).equals(PKCSObjectIdentifiers.signedData))
{
sData = SignedData.getInstance(ASN1Sequence.getInstance(
(ASN1TaggedObject)seq.getObjectAt(1), true)).getCertificates();
return getCertificate();
}
}
return new X509CertificateObject(
Certificate.getInstance(seq));
}
private Certificate readDERCertificate(
InputStream in)
throws IOException, CertificateParsingException
{
ASN1InputStream dIn = new ASN1InputStream(in);
ASN1Sequence seq = (ASN1Sequence)dIn.readObject();
if (seq.size() > 1
&& seq.getObjectAt(0) instanceof ASN1ObjectIdentifier)
{
if (seq.getObjectAt(0).equals(PKCSObjectIdentifiers.signedData))
{
sData = new SignedData(ASN1Sequence.getInstance(
(ASN1TaggedObject)seq.getObjectAt(1), true)).getCertificates();
return getCertificate();
}
}
return new X509CertificateObject(
org.ripple.bouncycastle.asn1.x509.Certificate.getInstance(seq));
}
public RootOfTrust(ASN1Encodable asn1Encodable) throws CertificateParsingException {
if (!(asn1Encodable instanceof ASN1Sequence)) {
throw new CertificateParsingException("Expected sequence for root of trust, found "
+ asn1Encodable.getClass().getName());
}
ASN1Sequence sequence = (ASN1Sequence) asn1Encodable;
verifiedBootKey =
Asn1Utils.getByteArrayFromAsn1(sequence.getObjectAt(VERIFIED_BOOT_KEY_INDEX));
deviceLocked = Asn1Utils.getBooleanFromAsn1(sequence.getObjectAt(DEVICE_LOCKED_INDEX));
verifiedBootState =
Asn1Utils.getIntegerFromAsn1(sequence.getObjectAt(VERIFIED_BOOT_STATE_INDEX));
if (sequence.size() < 4) {
verifiedBootHash = null;
return;
}
verifiedBootHash =
Asn1Utils.getByteArrayFromAsn1(sequence.getObjectAt(VERIFIED_BOOT_HASH_INDEX));
}
public AttestationPackageInfo(ASN1Encodable asn1Encodable) throws CertificateParsingException {
if (!(asn1Encodable instanceof ASN1Sequence)) {
throw new CertificateParsingException(
"Expected sequence for AttestationPackageInfo, found "
+ asn1Encodable.getClass().getName());
}
ASN1Sequence sequence = (ASN1Sequence) asn1Encodable;
try {
packageName = Asn1Utils.getStringFromAsn1OctetStreamAssumingUTF8(
sequence.getObjectAt(PACKAGE_NAME_INDEX));
} catch (UnsupportedEncodingException e) {
throw new CertificateParsingException(
"Converting octet stream to String triggered an UnsupportedEncodingException",
e);
}
version = Asn1Utils.getLongFromAsn1(sequence.getObjectAt(VERSION_INDEX));
}
/**
* add a given extension field for the standard extensions tag (tag 3)
* copying the extension value from another certificate.
* @throws CertificateParsingException if the extension cannot be extracted.
*/
public void copyAndAddExtension(
String oid,
boolean critical,
X509Certificate cert)
throws CertificateParsingException
{
byte[] extValue = cert.getExtensionValue(oid);
if (extValue == null)
{
throw new CertificateParsingException("extension " + oid + " not present");
}
try
{
ASN1Encodable value = X509ExtensionUtil.fromExtensionValue(extValue);
this.addExtension(oid, critical, value);
}
catch (IOException e)
{
throw new CertificateParsingException(e.toString());
}
}
/**
* Returns a list of subject alternative names. Any name that is represented as a String by X509Certificate.getSubjectAlternativeNames() is converted to lowercase and returned.
*
* @param certificate a certificate
* @return a list of subject alternative names; list is never null
* @throws CertificateParsingException if parsing the certificate failed
*/
public static List<String> getSubjectAlternativeNames(final X509Certificate certificate) throws CertificateParsingException {
final Collection<List<?>> altNames = certificate.getSubjectAlternativeNames();
if (altNames == null) {
return new ArrayList<>();
}
final List<String> result = new ArrayList<>();
for (final List<?> generalName : altNames) {
/**
* generalName has the name type as the first element a String or byte array for the second element. We return any general names that are String types.
*
* We don't inspect the numeric name type because some certificates incorrectly put IPs and DNS names under the wrong name types.
*/
final Object value = generalName.get(1);
if (value instanceof String) {
result.add(((String) value).toLowerCase());
}
}
return result;
}
private X509Certificate generateJcaObject(TBSCertificate tbsCert, byte[] signature)
throws CertificateEncodingException
{
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(tbsCert);
v.add(sigAlgId);
v.add(new DERBitString(signature));
try
{
return new X509CertificateObject(Certificate.getInstance(new DERSequence(v)));
}
catch (CertificateParsingException e)
{
throw new ExtCertificateEncodingException("exception producing certificate object", e);
}
}
@Override
public boolean verify(final String hostname, final SSLSession ssls) {
try {
for (final Certificate peerCertificate : ssls.getPeerCertificates()) {
if (peerCertificate instanceof X509Certificate) {
final X509Certificate x509Cert = (X509Certificate) peerCertificate;
final List<String> subjectAltNames = getSubjectAlternativeNames(x509Cert);
if (subjectAltNames.contains(hostname.toLowerCase())) {
return true;
}
}
}
} catch (final SSLPeerUnverifiedException | CertificateParsingException ex) {
LOG.warn("Hostname Verification encountered exception verifying hostname due to: " + ex, ex);
}
return false;
}
public AttestationPackageInfo(ASN1Encodable asn1Encodable) throws CertificateParsingException {
if (!(asn1Encodable instanceof ASN1Sequence)) {
throw new CertificateParsingException(
"Expected sequence for AttestationPackageInfo, found "
+ asn1Encodable.getClass().getName());
}
ASN1Sequence sequence = (ASN1Sequence) asn1Encodable;
try {
packageName = Asn1Utils.getStringFromAsn1OctetStreamAssumingUTF8(
sequence.getObjectAt(PACKAGE_NAME_INDEX));
} catch (UnsupportedEncodingException e) {
throw new CertificateParsingException(
"Converting octet stream to String triggered an UnsupportedEncodingException",
e);
}
version = Asn1Utils.getLongFromAsn1(sequence.getObjectAt(VERSION_INDEX));
}
private Certificate readDERCertificate(
InputStream in)
throws IOException, CertificateParsingException
{
ASN1InputStream dIn = new ASN1InputStream(in);
ASN1Sequence seq = (ASN1Sequence)dIn.readObject();
if (seq.size() > 1
&& seq.getObjectAt(0) instanceof ASN1ObjectIdentifier)
{
if (seq.getObjectAt(0).equals(PKCSObjectIdentifiers.signedData))
{
sData = new SignedData(ASN1Sequence.getInstance(
(ASN1TaggedObject)seq.getObjectAt(1), true)).getCertificates();
return getCertificate();
}
}
return new X509CertificateObject(
org.ripple.bouncycastle.asn1.x509.Certificate.getInstance(seq));
}
/**
* Returns a list of subject alternative names. Any name that is represented as a String by X509Certificate.getSubjectAlternativeNames() is converted to lowercase and returned.
*
* @param certificate a certificate
* @return a list of subject alternative names; list is never null
* @throws CertificateParsingException if parsing the certificate failed
*/
public static List<String> getSubjectAlternativeNames(final X509Certificate certificate) throws CertificateParsingException {
final Collection<List<?>> altNames = certificate.getSubjectAlternativeNames();
if (altNames == null) {
return new ArrayList<>();
}
final List<String> result = new ArrayList<>();
for (final List<?> generalName : altNames) {
/**
* generalName has the name type as the first element a String or byte array for the second element. We return any general names that are String types.
*
* We don't inspect the numeric name type because some certificates incorrectly put IPs and DNS names under the wrong name types.
*/
final Object value = generalName.get(1);
if (value instanceof String) {
result.add(((String) value).toLowerCase());
}
}
return result;
}
@Test
public void testExtractRequestInstanceId() throws CertificateParsingException {
assertNull(X509CertUtils.extractRequestInstanceId(null));
X509Certificate cert = Mockito.mock(X509Certificate.class);
Collection<List<?>> dnsNames = new ArrayList<>();
ArrayList<Object> item1 = new ArrayList<>();
item1.add(2);
item1.add("host1.domain.athenz");
dnsNames.add(item1);
Mockito.when(cert.getSubjectAlternativeNames()).thenReturn(dnsNames);
assertNull(X509CertUtils.extractRequestInstanceId(cert));
ArrayList<Object> item2 = new ArrayList<>();
item2.add(2);
item2.add("instanceid1.instanceid.athenz.test");
dnsNames.add(item2);
assertEquals("instanceid1", X509CertUtils.extractRequestInstanceId(cert));
}
/**
* Returns a list of subject alternative names. Any name that is represented as a String by X509Certificate.getSubjectAlternativeNames() is converted to lowercase and returned.
*
* @param certificate a certificate
* @return a list of subject alternative names; list is never null
* @throws CertificateParsingException if parsing the certificate failed
*/
public static List<String> getSubjectAlternativeNames(final X509Certificate certificate) throws CertificateParsingException {
final Collection<List<?>> altNames = certificate.getSubjectAlternativeNames();
if (altNames == null) {
return new ArrayList<>();
}
final List<String> result = new ArrayList<>();
for (final List<?> generalName : altNames) {
/**
* generalName has the name type as the first element a String or byte array for the second element. We return any general names that are String types.
*
* We don't inspect the numeric name type because some certificates incorrectly put IPs and DNS names under the wrong name types.
*/
final Object value = generalName.get(1);
if (value instanceof String) {
result.add(((String) value).toLowerCase());
}
}
return result;
}
/**
* Create the extension from the passed DER encoded value.
*
* @param critical true if the extension is to be treated as critical.
* @param value an array of DER encoded bytes of the actual value.
* @exception ClassCastException if value is not an array of bytes
* @exception CertificateException on certificate parsing errors.
* @exception IOException on error.
*/
public PrivateKeyUsageExtension(Boolean critical, Object value)
throws CertificateException, IOException {
this.extensionId = PKIXExtensions.PrivateKeyUsage_Id;
this.critical = critical.booleanValue();
this.extensionValue = (byte[]) value;
DerInputStream str = new DerInputStream(this.extensionValue);
DerValue[] seq = str.getSequence(2);
// NB. this is always encoded with the IMPLICIT tag
// The checks only make sense if we assume implicit tagging,
// with explicit tagging the form is always constructed.
for (int i = 0; i < seq.length; i++) {
DerValue opt = seq[i];
if (opt.isContextSpecific(TAG_BEFORE) &&
!opt.isConstructed()) {
if (notBefore != null) {
throw new CertificateParsingException(
"Duplicate notBefore in PrivateKeyUsage.");
}
opt.resetTag(DerValue.tag_GeneralizedTime);
str = new DerInputStream(opt.toByteArray());
notBefore = str.getGeneralizedTime();
} else if (opt.isContextSpecific(TAG_AFTER) &&
!opt.isConstructed()) {
if (notAfter != null) {
throw new CertificateParsingException(
"Duplicate notAfter in PrivateKeyUsage.");
}
opt.resetTag(DerValue.tag_GeneralizedTime);
str = new DerInputStream(opt.toByteArray());
notAfter = str.getGeneralizedTime();
} else
throw new IOException("Invalid encoding of " +
"PrivateKeyUsageExtension");
}
}
/**
* Returns either a string that "sums up" the certificate for humans, in a similar manner to what you might see
* in a web browser, or null if one cannot be extracted. This will typically be the common name (CN) field, but
* can also be the org (O) field, org+location+country if withLocation is set, or the email
* address for S/MIME certificates.
*/
@Nullable
public static String getDisplayNameFromCertificate(@Nonnull X509Certificate certificate, boolean withLocation) throws CertificateParsingException {
X500Name name = new X500Name(certificate.getSubjectX500Principal().getName());
String commonName = null, org = null, location = null, country = null;
for (RDN rdn : name.getRDNs()) {
AttributeTypeAndValue pair = rdn.getFirst();
String val = ((ASN1String) pair.getValue()).getString();
ASN1ObjectIdentifier type = pair.getType();
if (type.equals(RFC4519Style.cn))
commonName = val;
else if (type.equals(RFC4519Style.o))
org = val;
else if (type.equals(RFC4519Style.l))
location = val;
else if (type.equals(RFC4519Style.c))
country = val;
}
final Collection<List<?>> subjectAlternativeNames = certificate.getSubjectAlternativeNames();
String altName = null;
if (subjectAlternativeNames != null)
for (final List<?> subjectAlternativeName : subjectAlternativeNames)
if ((Integer) subjectAlternativeName.get(0) == 1) // rfc822name
altName = (String) subjectAlternativeName.get(1);
if (org != null) {
return withLocation ? Joiner.on(", ").skipNulls().join(org, location, country) : org;
} else if (commonName != null) {
return commonName;
} else {
return altName;
}
}
public static Collection getIssuerAlternativeNames(X509Certificate cert)
throws CertificateParsingException
{
byte[] extVal = cert.getExtensionValue(X509Extension.issuerAlternativeName.getId());
return getAlternativeNames(extVal);
}
private boolean checkCertSubjectAlternativeName(X509Certificate cert) {
Collection<List<?>> san;
try {
san = cert.getSubjectAlternativeNames();
for (List<?> s : san) {
for(Object q : s) {
if(q.equals("echo-api.amazon.com")) { return true; }
}
}
} catch (CertificateParsingException e) {
e.printStackTrace();
}
return false;
}
@Test
public void testFailure_invalidCert() {
CertificateParsingException thrown =
assertThrows(
CertificateParsingException.class,
() ->
runCommandForced(
"--ip_allow_list=1.1.1.1",
"--registrar=blobio",
"[email protected]",
"--certfile=/dev/null"));
assertThat(thrown).hasMessageThat().contains("No X509Certificate found");
}
/**
* Create the extension from the passed DER encoded value.
*
* @param critical true if the extension is to be treated as critical.
* @param value an array of DER encoded bytes of the actual value.
* @exception ClassCastException if value is not an array of bytes
* @exception CertificateException on certificate parsing errors.
* @exception IOException on error.
*/
public PrivateKeyUsageExtension(Boolean critical, Object value)
throws CertificateException, IOException {
this.extensionId = PKIXExtensions.PrivateKeyUsage_Id;
this.critical = critical.booleanValue();
this.extensionValue = (byte[]) value;
DerInputStream str = new DerInputStream(this.extensionValue);
DerValue[] seq = str.getSequence(2);
// NB. this is always encoded with the IMPLICIT tag
// The checks only make sense if we assume implicit tagging,
// with explicit tagging the form is always constructed.
for (int i = 0; i < seq.length; i++) {
DerValue opt = seq[i];
if (opt.isContextSpecific(TAG_BEFORE) &&
!opt.isConstructed()) {
if (notBefore != null) {
throw new CertificateParsingException(
"Duplicate notBefore in PrivateKeyUsage.");
}
opt.resetTag(DerValue.tag_GeneralizedTime);
str = new DerInputStream(opt.toByteArray());
notBefore = str.getGeneralizedTime();
} else if (opt.isContextSpecific(TAG_AFTER) &&
!opt.isConstructed()) {
if (notAfter != null) {
throw new CertificateParsingException(
"Duplicate notAfter in PrivateKeyUsage.");
}
opt.resetTag(DerValue.tag_GeneralizedTime);
str = new DerInputStream(opt.toByteArray());
notAfter = str.getGeneralizedTime();
} else
throw new IOException("Invalid encoding of " +
"PrivateKeyUsageExtension");
}
}
private List<AttestationPackageInfo> parseAttestationPackageInfos(ASN1Encodable asn1Encodable)
throws CertificateParsingException {
if (!(asn1Encodable instanceof ASN1Set)) {
throw new CertificateParsingException(
"Expected set for AttestationApplicationsInfos, found "
+ asn1Encodable.getClass().getName());
}
ASN1Set set = (ASN1Set) asn1Encodable;
List<AttestationPackageInfo> result = new ArrayList<>();
for (ASN1Encodable e : set) {
result.add(new AttestationPackageInfo(e));
}
return result;
}
private List<String> getSubjectAltNames(X509Certificate certificate, int type) {
List<String> result = new ArrayList<String>();
try {
Collection<?> subjectAltNames = certificate.getSubjectAlternativeNames();
if (subjectAltNames == null) {
return Collections.emptyList();
}
for (Object subjectAltName : subjectAltNames) {
List<?> entry = (List<?>) subjectAltName;
if (entry == null || entry.size() < 2) {
continue;
}
Integer altNameType = (Integer) entry.get(0);
if (altNameType == null) {
continue;
}
if (altNameType == type) {
String altName = (String) entry.get(1);
if (altName != null) {
result.add(altName);
}
}
}
return result;
} catch (CertificateParsingException e) {
return Collections.emptyList();
}
}
private X509Certificate generateJcaObject(TBSCertificate tbsCert, byte[] signature)
throws CertificateParsingException
{
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(tbsCert);
v.add(sigAlgId);
v.add(new DERBitString(signature));
return new X509CertificateObject(Certificate.getInstance(new DERSequence(v)));
}
public static ASN1Encodable getAsn1EncodableFromBytes(byte[] bytes)
throws CertificateParsingException {
try (ASN1InputStream asn1InputStream = new ASN1InputStream(bytes)) {
return asn1InputStream.readObject();
} catch (IOException e) {
throw new CertificateParsingException("Failed to parse Encodable", e);
}
}
public static ASN1Sequence getAsn1SequenceFromBytes(byte[] bytes)
throws CertificateParsingException {
try (ASN1InputStream asn1InputStream = new ASN1InputStream(bytes)) {
return getAsn1SequenceFromStream(asn1InputStream);
} catch (IOException e) {
throw new CertificateParsingException("Failed to parse SEQUENCE", e);
}
}
private static List<String> getSubjectAltNames(X509Certificate certificate, int type) {
List<String> result = new ArrayList<>();
try {
Collection<?> subjectAltNames = certificate.getSubjectAlternativeNames();
if (subjectAltNames == null) {
return Collections.emptyList();
}
for (Object subjectAltName : subjectAltNames) {
List<?> entry = (List<?>) subjectAltName;
if (entry == null || entry.size() < 2) {
continue;
}
Integer altNameType = (Integer) entry.get(0);
if (altNameType == null) {
continue;
}
if (altNameType == type) {
String altName = (String) entry.get(1);
if (altName != null) {
result.add(altName);
}
}
}
return result;
} catch (CertificateParsingException e) {
return Collections.emptyList();
}
}
private static long bigIntegerToLong(BigInteger bigInt) throws CertificateParsingException {
if (bigInt.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0
|| bigInt.compareTo(BigInteger.ZERO) < 0) {
throw new CertificateParsingException("INTEGER out of bounds");
}
return bigInt.longValue();
}
public static boolean getBooleanFromAsn1(ASN1Encodable value)
throws CertificateParsingException {
if (!(value instanceof ASN1Boolean)) {
throw new CertificateParsingException(
"Expected boolean, found " + value.getClass().getName());
}
return ((ASN1Boolean) value).isTrue();
}