org.bouncycastle.asn1.ASN1TaggedObject Java Examples

The following examples show how to use org.bouncycastle.asn1.ASN1TaggedObject. 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: ProxyMessage.java    From xipki with Apache License 2.0 6 votes vote down vote up
public static P11Params getInstance(Object obj) throws BadAsn1ObjectException {
  if (obj == null || obj instanceof P11Params) {
    return (P11Params) obj;
  }

  try {
    if (obj instanceof ASN1TaggedObject) {
      return new P11Params((ASN1TaggedObject) obj);
    } else if (obj instanceof byte[]) {
      return getInstance(ASN1Primitive.fromByteArray((byte[]) obj));
    } else {
      throw new BadAsn1ObjectException("unknown object: " + obj.getClass().getName());
    }
  } catch (IOException | IllegalArgumentException ex) {
    throw new BadAsn1ObjectException("unable to parse encoded object: " + ex.getMessage(), ex);
  }
}
 
Example #2
Source File: ProxyMessage.java    From xipki with Apache License 2.0 6 votes vote down vote up
private IdentityId(ASN1Sequence seq) throws BadAsn1ObjectException {
  requireRange(seq, 2, 4);
  P11SlotIdentifier slotId =
      SlotIdentifier.getInstance(seq.getObjectAt(0)).getValue();
  P11ObjectIdentifier keyId =
      ObjectIdentifier.getInstance(seq.getObjectAt(1)).getValue();
  String publicKeyLabel = null;
  String certLabel = null;

  final int n = seq.size();
  for (int i = 2; i < n; i++) {
    ASN1Encodable asn1 = seq.getObjectAt(i);
    if (asn1 instanceof ASN1TaggedObject) {
      ASN1TaggedObject tagAsn1 = (ASN1TaggedObject) asn1;
      int tag = tagAsn1.getTagNo();
      if (tag == 1) {
        publicKeyLabel = DERUTF8String.getInstance(tagAsn1.getObject()).getString();
      } else if (tag == 2) {
        certLabel = DERUTF8String.getInstance(tagAsn1.getObject()).getString();
      }
    }

  }

  this.value = new P11IdentityId(slotId, keyId, publicKeyLabel, certLabel);
}
 
Example #3
Source File: ProxyMessage.java    From xipki with Apache License 2.0 6 votes vote down vote up
private NewObjectControl(ASN1Sequence seq) throws BadAsn1ObjectException {
  final int size = seq.size();
  Args.min(size, "seq.size", 1);
  String label = DERUTF8String.getInstance(seq.getObjectAt(0)).getString();
  byte[] id = null;

  for (int i = 1; i < size; i++) {
    ASN1Encodable obj = seq.getObjectAt(i);
    if (obj instanceof ASN1TaggedObject) {
      continue;
    }

    ASN1TaggedObject tagObj = (ASN1TaggedObject) obj;
    int tagNo = tagObj.getTagNo();
    if (tagNo == 0) {
      id = DEROctetString.getInstance(tagObj.getObject()).getOctets();
    }
  }

  this.control = new P11NewKeyControl(id, label);
}
 
Example #4
Source File: AbstractRequirementChecks.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
@BeforeEach
public void init() throws Exception {
	DSSDocument signedDocument = getSignedDocument();

	ASN1InputStream asn1sInput = new ASN1InputStream(signedDocument.openStream());
	ASN1Sequence asn1Seq = (ASN1Sequence) asn1sInput.readObject();
	assertEquals(2, asn1Seq.size());
	ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1Seq.getObjectAt(0));
	assertEquals(PKCSObjectIdentifiers.signedData, oid);

	ASN1TaggedObject taggedObj = ASN1TaggedObject.getInstance(asn1Seq.getObjectAt(1));
	signedData = SignedData.getInstance(taggedObj.getObject());

	ASN1Set signerInfosAsn1 = signedData.getSignerInfos();
	assertEquals(1, signerInfosAsn1.size());

	signerInfo = SignerInfo.getInstance(ASN1Sequence.getInstance(signerInfosAsn1.getObjectAt(0)));

	Utils.closeQuietly(asn1sInput);
}
 
Example #5
Source File: CertifiedAttributesV2.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
@SuppressWarnings("rawtypes")
private CertifiedAttributesV2(ASN1Sequence seq) {
	int index = 0;
	values = new Object[seq.size()];

	for (Enumeration e = seq.getObjects(); e.hasMoreElements();) {
		ASN1TaggedObject taggedObject = ASN1TaggedObject.getInstance(e.nextElement());

		if (taggedObject.getTagNo() == 0) {
			values[index] = AttributeCertificate.getInstance(ASN1Sequence.getInstance(taggedObject, true));
		} else if (taggedObject.getTagNo() == 1) {
			LOG.info("OtherAttributeCertificate detected");
		} else {
			throw new IllegalArgumentException("illegal tag: " + taggedObject.getTagNo());
		}
		index++;
	}
}
 
Example #6
Source File: SignerAttributeV2.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
@SuppressWarnings("rawtypes")
private SignerAttributeV2(ASN1Sequence seq) {
	int index = 0;
	values = new Object[seq.size()];

	for (Enumeration e = seq.getObjects(); e.hasMoreElements();) {
		ASN1TaggedObject taggedObject = ASN1TaggedObject.getInstance(e.nextElement());

		if (taggedObject.getTagNo() == 0) {
			ASN1Sequence attrs = ASN1Sequence.getInstance(taggedObject, true);
			Attribute[] attributes = new Attribute[attrs.size()];

			for (int i = 0; i != attributes.length; i++) {
				attributes[i] = Attribute.getInstance(attrs.getObjectAt(i));
			}
			values[index] = attributes;
		} else if (taggedObject.getTagNo() == 1) {
			values[index] = CertifiedAttributesV2.getInstance(ASN1Sequence.getInstance(taggedObject, true));
		} else if (taggedObject.getTagNo() == 2) {
		    	LOG.info("SAML assertion detected");
			values[index] = SignedAssertions.getInstance(ASN1Sequence.getInstance(taggedObject, true));
		} else {
			throw new IllegalArgumentException("illegal tag: " + taggedObject.getTagNo());
		}
		index++;
	}
}
 
Example #7
Source File: UserIdentityExtractor.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private ASN1Encodable unwrap(ASN1Encodable encodable) {
    while (encodable instanceof ASN1TaggedObject) {
        ASN1TaggedObject taggedObj = (ASN1TaggedObject) encodable;
        encodable = taggedObj.getObject();
    }

    return encodable;
}
 
Example #8
Source File: ProxyMessage.java    From xipki with Apache License 2.0 5 votes vote down vote up
private NewKeyControl(ASN1Sequence seq) throws BadAsn1ObjectException {
  final int size = seq.size();
  Args.min(size, "seq.size", 1);
  String label = DERUTF8String.getInstance(seq.getObjectAt(0)).getString();

  Set<P11KeyUsage> usages = new HashSet<>();
  byte[] id = null;
  Boolean extractable = null;

  for (int i = 1; i < size; i++) {
    ASN1Encodable obj = seq.getObjectAt(i);
    if (!(obj instanceof ASN1TaggedObject)) {
      continue;
    }

    ASN1TaggedObject tagObj = (ASN1TaggedObject) obj;
    int tagNo = tagObj.getTagNo();
    if (tagNo == 0) {
      id = DEROctetString.getInstance(tagObj.getObject()).getOctets();
    } else if (tagNo == 1) {
      ASN1Sequence usageSeq = ASN1Sequence.getInstance(tagObj.getObject());
      final int usageSize = usageSeq.size();
      for (int j = 0; j < usageSize; j++) {
        ASN1Enumerated usageEnum = ASN1Enumerated.getInstance(usageSeq.getObjectAt(j));
        int enumValue = usageEnum.getValue().intValue();
        P11KeyUsage usage = valueToUsageMap.get(enumValue);
        if (usage == null) {
          throw new IllegalArgumentException("invalid usage " + enumValue);
        }
        usages.add(usage);
      }
    } else if (tagNo == 2) {
      extractable = ASN1Boolean.getInstance(tagObj.getObject()).isTrue();
    }
  }

  this.control = new P11NewKeyControl(id, label);
  this.control.setUsages(usages);
  this.control.setExtractable(extractable);
}
 
Example #9
Source File: ExtensionExistence.java    From xipki with Apache License 2.0 5 votes vote down vote up
private ExtensionExistence(ASN1Sequence seq) {
  int size = seq.size();
  if (size > 2) {
    throw new IllegalArgumentException("wrong number of elements in sequence");
  }

  for (int i = 0; i < size; i++) {
    ASN1TaggedObject tagObject = ASN1TaggedObject.getInstance(seq.getObjectAt(i));
    int tag = tagObject.getTagNo();
    Args.range(tag, "tag", 0, 1);
    ASN1Sequence subSeq = ASN1Sequence.getInstance(tagObject.getObject());
    List<ASN1ObjectIdentifier> oids = new LinkedList<>();
    int subSize = subSeq.size();
    for (int j = 0; j < subSize; j++) {
      oids.add(ASN1ObjectIdentifier.getInstance(subSeq.getObjectAt(j)));
    }

    if (tag == 0) {
      needExtensions = Collections.unmodifiableList(oids);
    } else {
      wantExtensions = Collections.unmodifiableList(oids);
    }
  }

  if (needExtensions == null) {
    needExtensions = Collections.unmodifiableList(Collections.emptyList());
  }

  if (wantExtensions == null) {
    wantExtensions = Collections.unmodifiableList(Collections.emptyList());
  }
}
 
Example #10
Source File: OCSPCertificateVerifier.java    From oxAuth with MIT License 5 votes vote down vote up
@SuppressWarnings({ "deprecation", "resource" })
private String getOCSPUrl(X509Certificate certificate) throws IOException {
	ASN1Primitive obj;
	try {
		obj = getExtensionValue(certificate, Extension.authorityInfoAccess.getId());
	} catch (IOException ex) {
		log.error("Failed to get OCSP URL", ex);
		return null;
	}

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

	AuthorityInformationAccess authorityInformationAccess = AuthorityInformationAccess.getInstance(obj);

	AccessDescription[] accessDescriptions = authorityInformationAccess.getAccessDescriptions();
	for (AccessDescription accessDescription : accessDescriptions) {
		boolean correctAccessMethod = accessDescription.getAccessMethod().equals(X509ObjectIdentifiers.ocspAccessMethod);
		if (!correctAccessMethod) {
			continue;
		}

		GeneralName name = accessDescription.getAccessLocation();
		if (name.getTagNo() != GeneralName.uniformResourceIdentifier) {
			continue;
		}

		DERIA5String derStr = DERIA5String.getInstance((ASN1TaggedObject) name.toASN1Primitive(), false);
		return derStr.getString();
	}

	return null;

}
 
Example #11
Source File: CRLCertificateVerifier.java    From oxAuth with MIT License 5 votes vote down vote up
public String getCrlUri(X509Certificate certificate) throws IOException {
	ASN1Primitive obj;
	try {
		obj = getExtensionValue(certificate, Extension.cRLDistributionPoints.getId());
	} catch (IOException ex) {
		log.error("Failed to get CRL URL", ex);
		return null;
	}

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

	CRLDistPoint distPoint = CRLDistPoint.getInstance(obj);

	DistributionPoint[] distributionPoints = distPoint.getDistributionPoints();
	for (DistributionPoint distributionPoint : distributionPoints) {
		DistributionPointName distributionPointName = distributionPoint.getDistributionPoint();
		if (DistributionPointName.FULL_NAME != distributionPointName.getType()) {
			continue;
		}

		GeneralNames generalNames = (GeneralNames) distributionPointName.getName();
		GeneralName[] names = generalNames.getNames();
		for (GeneralName name : names) {
			if (name.getTagNo() != GeneralName.uniformResourceIdentifier) {
				continue;
			}

			DERIA5String derStr = DERIA5String.getInstance((ASN1TaggedObject) name.toASN1Primitive(), false);
			return derStr.getString();
		}
	}

	return null;
}
 
Example #12
Source File: AuthorizationList.java    From android-testdpc with Apache License 2.0 5 votes vote down vote up
private static ASN1TaggedObject parseAsn1TaggedObject(ASN1SequenceParser parser)
        throws CertificateParsingException {
    ASN1Encodable asn1Encodable = parseAsn1Encodable(parser);
    if (asn1Encodable == null || asn1Encodable instanceof ASN1TaggedObject) {
        return (ASN1TaggedObject) asn1Encodable;
    }
    throw new CertificateParsingException(
            "Expected tagged object, found " + asn1Encodable.getClass().getName());
}
 
Example #13
Source File: RevocationInfoArchival.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private RevocationInfoArchival(ASN1Sequence seq)
{
    if (seq.size() > 3)
    {
        throw new IllegalArgumentException("Bad sequence size: "
            + seq.size());
    }
    Enumeration e = seq.getObjects();
    while (e.hasMoreElements())
    {
        ASN1TaggedObject o = (ASN1TaggedObject)e.nextElement();
        switch (o.getTagNo())
        {
            case 0:
                ASN1Sequence crlValsSeq = (ASN1Sequence)o.getObject();
                Enumeration crlValsEnum = crlValsSeq.getObjects();
                while (crlValsEnum.hasMoreElements())
                {
                    CertificateList.getInstance(crlValsEnum.nextElement());
                }
                this.crlVals = crlValsSeq;
                break;
            case 1:
                ASN1Sequence ocspValsSeq = (ASN1Sequence)o.getObject();
                Enumeration ocspValsEnum = ocspValsSeq.getObjects();
                while (ocspValsEnum.hasMoreElements())
                {
                    OCSPResponse.getInstance(ocspValsEnum.nextElement());
                }
                this.ocspVals = ocspValsSeq;
                break;
            case 2:
                this.otherRevVals = OtherRevVals.getInstance(o.getObject());
                break;
            default:
                throw new IllegalArgumentException("invalid tag: "
                    + o.getTagNo());
        }
    }
}
 
Example #14
Source File: CAdESWithContentTimestampTest.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected DSSDocument getSignedDocument() {
	FileDocument fileDocument = new FileDocument("src/test/resources/validation/Signature-C-BES-4.p7m");
	
	try (InputStream is = fileDocument.openStream(); ASN1InputStream asn1sInput = new ASN1InputStream(is)) {
		ASN1Sequence asn1Seq = (ASN1Sequence) asn1sInput.readObject();

		ASN1TaggedObject taggedObj = ASN1TaggedObject.getInstance(asn1Seq.getObjectAt(1));
		ASN1Primitive object = taggedObj.getObject();
		SignedData signedData = SignedData.getInstance(object);

		ASN1Set signerInfosAsn1 = signedData.getSignerInfos();
		ASN1Sequence seqSignedInfo = ASN1Sequence.getInstance(signerInfosAsn1.getObjectAt(0));

		SignerInfo signedInfo = SignerInfo.getInstance(seqSignedInfo);
		ASN1Set authenticatedAttributes = signedInfo.getAuthenticatedAttributes();

		boolean found = false;
		for (int i = 0; i < authenticatedAttributes.size(); i++) {
			ASN1Sequence authAttrSeq = ASN1Sequence.getInstance(authenticatedAttributes.getObjectAt(i));
			ASN1ObjectIdentifier attrOid = ASN1ObjectIdentifier.getInstance(authAttrSeq.getObjectAt(0));
			if (PKCSObjectIdentifiers.id_aa_ets_contentTimestamp.equals(attrOid)) {
				found = true;
			}
		}
		assertTrue(found);
	} catch (Exception e) {
		fail(e);
	}
	
	return fileDocument;
}
 
Example #15
Source File: AuthorizationList.java    From Auditor with MIT License 5 votes vote down vote up
private static ASN1TaggedObject parseAsn1TaggedObject(ASN1SequenceParser parser)
        throws CertificateParsingException {
    ASN1Encodable asn1Encodable = parseAsn1Encodable(parser);
    if (asn1Encodable == null || asn1Encodable instanceof ASN1TaggedObject) {
        return (ASN1TaggedObject) asn1Encodable;
    }
    throw new CertificateParsingException(
            "Expected tagged object, found " + asn1Encodable.getClass().getName());
}
 
Example #16
Source File: Asn1Dump.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
private String dumpTaggedObject(ASN1TaggedObject o) throws Asn1Exception, IOException {

		StringBuilder sb = new StringBuilder();

		sb.append(indentSequence.toString(indentLevel));
		if (o instanceof BERTaggedObject) {
			sb.append("BER TAGGED [");
		} else {
			sb.append("TAGGED [");
		}
		sb.append(Integer.toString(o.getTagNo()));
		sb.append(']');

		if (!o.isExplicit()) {
			sb.append(" IMPLICIT ");
		}
		sb.append(":");
		sb.append(NEWLINE);

		if (o.isEmpty()) {
			sb.append("EMPTY");
		} else {
			sb.append(dump(o.getObject()));
		}

		return sb.toString();
	}
 
Example #17
Source File: Asn1Dump.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get dump of the supplied ASN.1 object.
 *
 * @param asn1Object
 *            ASN.1 object
 * @return Dump of object
 * @throws Asn1Exception
 *             A problem was encountered getting the ASN.1 dump
 * @throws IOException
 *             If an I/O problem occurred
 */
public String dump(ASN1Primitive asn1Object) throws Asn1Exception, IOException {
	// Get dump of the supplied ASN.1 object incrementing the indent level of the output
	try {
		indentLevel++;

		if (asn1Object instanceof DERBitString) { // special case of ASN1String
			return dumpBitString((DERBitString) asn1Object);
		} else if (asn1Object instanceof ASN1String) {
			return dumpString((ASN1String) asn1Object);
		} else if (asn1Object instanceof ASN1UTCTime) {
			return dumpUTCTime((ASN1UTCTime) asn1Object);
		} else if (asn1Object instanceof ASN1GeneralizedTime) {
			return dumpGeneralizedTime((ASN1GeneralizedTime) asn1Object);
		} else if (asn1Object instanceof ASN1Sequence ||
				asn1Object instanceof ASN1Set ) {
			return dumpSetOrSequence(asn1Object);
		} else if (asn1Object instanceof ASN1TaggedObject) {
			return dumpTaggedObject((ASN1TaggedObject) asn1Object);
		} else if (asn1Object instanceof ASN1Boolean) {
			return dumpBoolean((ASN1Boolean) asn1Object);
		} else if (asn1Object instanceof ASN1Enumerated) {
			return dumpEnumerated((ASN1Enumerated) asn1Object);
		} else if (asn1Object instanceof ASN1Integer) {
			return dumpInteger((ASN1Integer) asn1Object);
		} else if (asn1Object instanceof ASN1Null) {
			return dumpNull();
		} else if (asn1Object instanceof ASN1ObjectIdentifier) {
			return dumpObjectIdentifier((ASN1ObjectIdentifier) asn1Object);
		} else if (asn1Object instanceof ASN1OctetString) {
			return dumpOctetString((ASN1OctetString) asn1Object);
		} else {
			throw new Asn1Exception("Unknown ASN.1 object: " + asn1Object.toString());
		}
	} finally {
		indentLevel--;
	}
}
 
Example #18
Source File: AuthorizationList.java    From android-key-attestation with Apache License 2.0 5 votes vote down vote up
private static Map<Integer, ASN1Primitive> getAuthorizationMap(
    ASN1Encodable[] authorizationList) {
  Map<Integer, ASN1Primitive> authorizationMap = new HashMap<>();
  for (ASN1Encodable entry : authorizationList) {
    ASN1TaggedObject taggedEntry = (ASN1TaggedObject) entry;
    authorizationMap.put(taggedEntry.getTagNo(), taggedEntry.getObject());
  }
  return authorizationMap;
}
 
Example #19
Source File: PdfPKCS7.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Get the "subject" from the TBSCertificate bytes that are passed in
 * @param enc A TBSCertificate in a byte array
 * @return a DERObject
 */
private static ASN1Primitive getSubject(byte[] enc) {
    try {
        ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(enc));
        ASN1Sequence seq = (ASN1Sequence)in.readObject();
        return (ASN1Primitive)seq.getObjectAt(seq.getObjectAt(0) instanceof ASN1TaggedObject ? 5 : 4);
    }
    catch (IOException e) {
        throw new ExceptionConverter(e);
    }
}
 
Example #20
Source File: PdfPKCS7.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Get the "issuer" from the TBSCertificate bytes that are passed in
 * @param enc a TBSCertificate in a byte array
 * @return a DERObject
 */
private static ASN1Primitive getIssuer(byte[] enc) {
    try {
        ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(enc));
        ASN1Sequence seq = (ASN1Sequence)in.readObject();
        return (ASN1Primitive)seq.getObjectAt(seq.getObjectAt(0) instanceof ASN1TaggedObject ? 3 : 2);
    }
    catch (IOException e) {
        throw new ExceptionConverter(e);
    }
}
 
Example #21
Source File: X509SubjectAlternativeNameUPNPrincipalResolver.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * Get UPN String.
 *
 * @param seq ASN1Sequence abstraction representing subject alternative name.
 * First element is the object identifier, second is the object itself.
 *
 * @return UPN string or null
 */
private String getUPNStringFromSequence(final ASN1Sequence seq) {
    if (seq != null) {
        // First in sequence is the object identifier, that we must check
        final DERObjectIdentifier id = DERObjectIdentifier.getInstance(seq.getObjectAt(0));
        if (id != null && UPN_OBJECTID.equals(id.getId())) {
            final ASN1TaggedObject obj = (ASN1TaggedObject) seq.getObjectAt(1);
            final DERUTF8String str = DERUTF8String.getInstance(obj.getObject());
            return str.getString();
        }
    }
    return null;
}
 
Example #22
Source File: AuthorizationList.java    From AttestationServer with MIT License 5 votes vote down vote up
private static ASN1TaggedObject parseAsn1TaggedObject(ASN1SequenceParser parser)
        throws CertificateParsingException {
    ASN1Encodable asn1Encodable = parseAsn1Encodable(parser);
    if (asn1Encodable == null || asn1Encodable instanceof ASN1TaggedObject) {
        return (ASN1TaggedObject) asn1Encodable;
    }
    throw new CertificateParsingException(
            "Expected tagged object, found " + asn1Encodable.getClass().getName());
}
 
Example #23
Source File: KerberosApRequest.java    From jcifs-ng with GNU Lesser General Public License v2.1 4 votes vote down vote up
public KerberosApRequest ( byte[] token, KerberosKey[] keys ) throws PACDecodingException {
    if ( token.length <= 0 )
        throw new PACDecodingException("Empty kerberos ApReq");

    DLSequence sequence;
    try {
        try ( ASN1InputStream stream = new ASN1InputStream(new ByteArrayInputStream(token)) ) {
            sequence = ASN1Util.as(DLSequence.class, stream);
        }
    }
    catch ( IOException e ) {
        throw new PACDecodingException("Malformed Kerberos Ticket", e);
    }

    Enumeration<?> fields = sequence.getObjects();
    while ( fields.hasMoreElements() ) {
        ASN1TaggedObject tagged = ASN1Util.as(ASN1TaggedObject.class, fields.nextElement());
        switch ( tagged.getTagNo() ) {
        case 0:
            ASN1Integer pvno = ASN1Util.as(ASN1Integer.class, tagged);
            if ( !pvno.getValue().equals(new BigInteger(KerberosConstants.KERBEROS_VERSION)) ) {
                throw new PACDecodingException("Invalid kerberos version");
            }
            break;
        case 1:
            ASN1Integer msgType = ASN1Util.as(ASN1Integer.class, tagged);
            if ( !msgType.getValue().equals(new BigInteger(KerberosConstants.KERBEROS_AP_REQ)) )
                throw new PACDecodingException("Invalid kerberos request");
            break;
        case 2:
            DERBitString bitString = ASN1Util.as(DERBitString.class, tagged);
            this.apOptions = bitString.getBytes()[ 0 ];
            break;
        case 3:
            DERApplicationSpecific derTicket = ASN1Util.as(DERApplicationSpecific.class, tagged);
            if ( !derTicket.isConstructed() )
                throw new PACDecodingException("Malformed Kerberos Ticket");
            this.ticket = new KerberosTicket(derTicket.getContents(), this.apOptions, keys);
            break;
        case 4:
            // Let's ignore this for now
            break;
        default:
            throw new PACDecodingException("Invalid field in kerberos ticket");
        }
    }
}
 
Example #24
Source File: KerberosApRequest.java    From jcifs with GNU Lesser General Public License v2.1 4 votes vote down vote up
public KerberosApRequest ( byte[] token, KerberosKey[] keys ) throws PACDecodingException {
    if ( token.length <= 0 )
        throw new PACDecodingException("Empty kerberos ApReq");

    DLSequence sequence;
    try {
        try ( ASN1InputStream stream = new ASN1InputStream(new ByteArrayInputStream(token)) ) {
            sequence = ASN1Util.as(DLSequence.class, stream);
        }
    }
    catch ( IOException e ) {
        throw new PACDecodingException("Malformed Kerberos Ticket", e);
    }

    Enumeration<?> fields = sequence.getObjects();
    while ( fields.hasMoreElements() ) {
        ASN1TaggedObject tagged = ASN1Util.as(ASN1TaggedObject.class, fields.nextElement());
        switch ( tagged.getTagNo() ) {
        case 0:
            ASN1Integer pvno = ASN1Util.as(ASN1Integer.class, tagged);
            if ( !pvno.getValue().equals(new BigInteger(KerberosConstants.KERBEROS_VERSION)) ) {
                throw new PACDecodingException("Invalid kerberos version");
            }
            break;
        case 1:
            ASN1Integer msgType = ASN1Util.as(ASN1Integer.class, tagged);
            if ( !msgType.getValue().equals(new BigInteger(KerberosConstants.KERBEROS_AP_REQ)) )
                throw new PACDecodingException("Invalid kerberos request");
            break;
        case 2:
            DERBitString bitString = ASN1Util.as(DERBitString.class, tagged);
            this.apOptions = bitString.getBytes()[ 0 ];
            break;
        case 3:
            DERApplicationSpecific derTicket = ASN1Util.as(DERApplicationSpecific.class, tagged);
            if ( !derTicket.isConstructed() )
                throw new PACDecodingException("Malformed Kerberos Ticket");
            this.ticket = new KerberosTicket(derTicket.getContents(), this.apOptions, keys);
            break;
        case 4:
            // Let's ignore this for now
            break;
        default:
            throw new PACDecodingException("Invalid field in kerberos ticket");
        }
    }
}
 
Example #25
Source File: ExtensionSyntaxChecker.java    From xipki with Apache License 2.0 4 votes vote down vote up
private static ASN1Encodable getParsedImplicitValue(String name, ASN1TaggedObject taggedObject,
    FieldType fieldType) throws BadCertTemplateException {
  try {
    switch (fieldType) {
      case BIT_STRING:
        return DERBitString.getInstance(taggedObject, false);
      case BMPString:
        return DERBMPString.getInstance(taggedObject, false);
      case BOOLEAN:
        return ASN1Boolean.getInstance(taggedObject, false);
      case ENUMERATED:
        return ASN1Enumerated.getInstance(taggedObject, false);
      case GeneralizedTime:
        return DERGeneralizedTime.getInstance(taggedObject, false);
      case IA5String:
        return DERIA5String.getInstance(taggedObject, false);
      case INTEGER:
        return ASN1Integer.getInstance(taggedObject, false);
      case Name:
        return X500Name.getInstance(taggedObject, false);
      case NULL:
        if (!(taggedObject.getObject() instanceof ASN1OctetString
            && ((ASN1OctetString) taggedObject.getObject()).getOctets().length == 0)) {
          throw new BadCertTemplateException("invalid " + name);
        }
        return DERNull.INSTANCE;
      case OCTET_STRING:
        return DEROctetString.getInstance(taggedObject, false);
      case OID:
        return ASN1ObjectIdentifier.getInstance(taggedObject, false);
      case PrintableString:
        return DERPrintableString.getInstance(taggedObject, false);
      case RAW:
        return taggedObject.getObject();
      case SEQUENCE:
      case SEQUENCE_OF:
        return ASN1Sequence.getInstance(taggedObject, false);
      case SET:
      case SET_OF:
        return ASN1Set.getInstance(taggedObject, false);
      case TeletexString:
        return DERT61String.getInstance(taggedObject, false);
      case UTCTime:
        return DERUTCTime.getInstance(taggedObject, false);
      case UTF8String:
        return DERUTF8String.getInstance(taggedObject, false);
      default:
        throw new RuntimeException("Unknown FieldType " + fieldType);
    }
  } catch (IllegalArgumentException ex) {
    throw new BadCertTemplateException("invalid " + name, ex);
  }
}
 
Example #26
Source File: PdfPKCS7.java    From itext2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
private static String getStringFromGeneralName(ASN1Primitive names) throws IOException {
	ASN1TaggedObject taggedObject = (ASN1TaggedObject) names;
    return new String(ASN1OctetString.getInstance(taggedObject, false).getOctets(), "ISO-8859-1");
}
 
Example #27
Source File: X509Ext.java    From portecle with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Gets a HTML escaped string representation of the given object.
 *
 * @param obj Object
 * @return String representation of <code>obj</code>
 */
private static String stringify(Object obj)
{
	if (obj instanceof ASN1String)
	{
		return escapeHtml(((ASN1String) obj).getString());
	}
	// TODO: why not ASN1Integer as number?
	else if (obj instanceof ASN1Integer || obj instanceof byte[])
	{
		return convertToHexString(obj);
	}
	else if (obj instanceof ASN1TaggedObject)
	{
		ASN1TaggedObject tagObj = (ASN1TaggedObject) obj;
		// Note: "[", _not_ '[' ...
		return "[" + tagObj.getTagNo() + "] " + stringify(tagObj.getObject());
	}
	else if (obj instanceof ASN1Sequence)
	{
		ASN1Sequence aObj = (ASN1Sequence) obj;
		StringBuilder tmp = new StringBuilder("[");
		for (int i = 0, len = aObj.size(); i < len; i++)
		{
			tmp.append(stringify(aObj.getObjectAt(i)));
			if (i != len - 1)
			{
				tmp.append(", ");
			}
		}
		return tmp.append("]").toString();
	}
	else
	{
		String hex = null;
		try
		{
			Method method = obj.getClass().getMethod("getOctets", (Class[]) null);
			hex = convertToHexString(method.invoke(obj, (Object[]) null));
		}
		catch (Exception e)
		{
			// Ignore
		}
		if (hex == null && obj != null)
		{
			hex = escapeHtml(obj.toString());
		}
		return hex;
	}
}
 
Example #28
Source File: X509Ext.java    From portecle with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Get Novell Security Attributes (2.16.840.1.113719.1.9.4.1) extension value as a string.
 *
 * @see <a href="https://www.novell.com/documentation/developer/ncslib/npki_enu/data/a2uetmm.html">Novell Security
 *      Attributes Extension</a>
 * @param bValue The octet string value
 * @return Extension value as a string
 * @throws IOException If an I/O problem occurs
 */
private String getNovellSecurityAttributesStringValue(byte[] bValue)
    throws IOException
{
	// TODO...

	ASN1Sequence attrs = (ASN1Sequence) ASN1Primitive.fromByteArray(bValue);
	StringBuilder sb = new StringBuilder();

	// "Novell Security Attribute(tm)"
	String sTM = ((ASN1String) attrs.getObjectAt(2)).getString();
	sb.append(escapeHtml(sTM));
	sb.append("<br>");

	// OCTET STRING of size 2, 1st is major version, 2nd is minor version
	byte[] bVer = ((DEROctetString) attrs.getObjectAt(0)).getOctets();
	sb.append("Major version: ").append(Byte.toString(bVer[0]));
	sb.append(", minor version: ").append(Byte.toString(bVer[1]));
	sb.append("<br>");

	// Nonverified Subscriber Information
	boolean bNSI = ((ASN1Boolean) attrs.getObjectAt(1)).isTrue();
	sb.append("Nonverified Subscriber Information: ").append(bNSI);
	sb.append("<br>");

	// URI reference
	String sUri = ((ASN1String) attrs.getObjectAt(3)).getString();
	sb.append("URI: ");
	sb.append(getLink(sUri, escapeHtml(sUri), LinkClass.BROWSER));

	// GLB Extensions (GLB ~ "Greatest Lower Bound")

	sb.append("<ul>");
	ASN1Sequence glbs = (ASN1Sequence) attrs.getObjectAt(4);
	sb.append("<li>GLB extensions:<ul>");

	/*
	 * TODO: verify that we can do getObjectAt(n) or if we need to examine tag numbers of the tagged objects
	 */

	// Key quality
	ASN1Sequence keyq = (ASN1Sequence) ((ASN1TaggedObject) glbs.getObjectAt(0)).getObject();
	sb.append("<li>").append(RB.getString("NovellKeyQuality"));
	sb.append("<ul>").append(getNovellQualityAttr(keyq)).append("</ul></li>");

	// Crypto process quality
	ASN1Sequence cpq = (ASN1Sequence) ((ASN1TaggedObject) glbs.getObjectAt(1)).getObject();
	sb.append("<li>").append(RB.getString("NovellCryptoProcessQuality"));
	sb.append("<ul>").append(getNovellQualityAttr(cpq)).append("</ul></li>");

	// Certificate class
	ASN1Sequence cclass = (ASN1Sequence) ((ASN1TaggedObject) glbs.getObjectAt(2)).getObject();
	sb.append("<li>").append(RB.getString("NovellCertClass"));
	sb.append(": ");
	BigInteger sv = ((ASN1Integer) cclass.getObjectAt(0)).getValue();
	String sc = getRes("NovellCertClass." + sv, "UnregocnisedNovellCertClass");
	sb.append(MessageFormat.format(sc, sv));
	sb.append("</li>");

	boolean valid = true;
	if (cclass.size() > 1)
	{
		valid = ((ASN1Boolean) cclass.getObjectAt(1)).isTrue();
	}
	sb.append("<li>");
	sb.append(RB.getString("NovellCertClassValid." + valid));
	sb.append("</li></ul>");

	// Enterprise ID
	/*
	 * ASN1Sequence eid = (ASN1Sequence) ((ASN1TaggedObject) glbs.getObjectAt(3)).getObject(); ASN1Sequence
	 * rootLabel = (ASN1Sequence) ((ASN1TaggedObject) eid.getObjectAt(0)).getObject(); ASN1Sequence registryLabel =
	 * (ASN1Sequence) ((ASN1TaggedObject) eid.getObjectAt(1)).getObject(); ASN1Sequence eLabels = (ASN1Sequence)
	 * ((ASN1TaggedObject) eid.getObjectAt(2)).getObject(); for (int i = 0, len = eLabels.size(); i < len; i++) { //
	 * Hmm... I thought this would be a sequence of sequences, // but the following throws a ClassCastException...?
	 * // ASN1Sequence eLabel = (ASN1Sequence) eLabels.getObjectAt(i); }
	 */
	sb.append(RB.getString("NovellEnterpriseID"));
	sb.append(' ').append(RB.getString("DecodeNotImplemented")); // TODO

	return sb.toString();
}
 
Example #29
Source File: ProxyMessage.java    From xipki with Apache License 2.0 4 votes vote down vote up
private P11Params(ASN1TaggedObject taggedObject) throws BadAsn1ObjectException {
  this.tagNo = taggedObject.getTagNo();
  this.p11Params = taggedObject.getObject();
}
 
Example #30
Source File: ASN1Util.java    From jcifs-ng with GNU Lesser General Public License v2.1 2 votes vote down vote up
/**
 * 
 * @param type
 * @param tagged
 * @return tagged object contents cast to type
 * @throws PACDecodingException
 */
public static <T extends ASN1Primitive> T as ( Class<T> type, ASN1TaggedObject tagged ) throws PACDecodingException {
    return as(type, tagged.getObject());
}