Java Code Examples for org.bouncycastle.asn1.ASN1ObjectIdentifier#getInstance()

The following examples show how to use org.bouncycastle.asn1.ASN1ObjectIdentifier#getInstance() . 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: X509Ext.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
private String getHoldInstructionCodeStringValue(byte[] value) throws IOException {
	// @formatter:off
	/* HoldInstructionCode ::= OBJECT IDENTIFER */
	// @formatter:on

	StringBuilder sb = new StringBuilder();

	ASN1ObjectIdentifier holdInstructionCode = ASN1ObjectIdentifier.getInstance(value);
	HoldInstructionCodeType holdInstructionCodeType =
			HoldInstructionCodeType.resolveOid(holdInstructionCode.getId());

	if (holdInstructionCodeType != null) {
		sb.append(holdInstructionCodeType.friendly());
	} else {
		// Unrecognised Hold Instruction Code
		sb.append(holdInstructionCode.getId());
	}
	sb.append(NEWLINE);

	return sb.toString();
}
 
Example 2
Source File: X509Ext.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
private String getValidityModelStringValue(byte[] octets) {

		// @formatter:off

		/*
			ValidityModel::= SEQUENCE
			{
				validityModelId OBJECT IDENTIFIER
				validityModelInfo ANY DEFINED BY validityModelId OPTIONAL
			}
		 */

		// @formatter:on

		ASN1Sequence asn1Sequence = ASN1Sequence.getInstance(octets);
		ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1Sequence.getObjectAt(0));
		ValidityModelType validityModel = ValidityModelType.resolveOid(oid.getId());

		return validityModel.friendly();
	}
 
Example 3
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 4
Source File: DSSASN1Utils.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Gets the ASN.1 algorithm identifier structure corresponding to the algorithm 
 * found in the provided Timestamp Hash Index Table, if such algorithm is present
 *
 * @param atsHashIndexValue
 *            ats-hash-index table from a timestamp
 * @return the ASN.1 algorithm identifier structure
 */
public static AlgorithmIdentifier getAlgorithmIdentifier(final ASN1Sequence atsHashIndexValue) {
	if (atsHashIndexValue != null && atsHashIndexValue.size() > 3) {
		final int algorithmIndex = 0;
		final ASN1Encodable asn1Encodable = atsHashIndexValue.getObjectAt(algorithmIndex);
		
		if (asn1Encodable instanceof ASN1Sequence) {
			final ASN1Sequence asn1Sequence = (ASN1Sequence) asn1Encodable;
			return AlgorithmIdentifier.getInstance(asn1Sequence);
		} else if (asn1Encodable instanceof ASN1ObjectIdentifier) {
			// TODO (16/11/2014): The relevance and usefulness of the test case must be checked (do the signatures
			// like this exist?)
			ASN1ObjectIdentifier derObjectIdentifier = ASN1ObjectIdentifier.getInstance(asn1Encodable);
			return new AlgorithmIdentifier(derObjectIdentifier);
		}
	}
	return null;
}
 
Example 5
Source File: Kerb5Context.java    From jcifs with GNU Lesser General Public License v2.1 5 votes vote down vote up
Key searchSessionKey ( Subject subject ) throws GSSException {
    MIEName src = new MIEName(this.gssContext.getSrcName().export());
    MIEName targ = new MIEName(this.gssContext.getTargName().export());

    ASN1ObjectIdentifier mech = ASN1ObjectIdentifier.getInstance(this.gssContext.getMech().getDER());
    for ( KerberosTicket ticket : subject.getPrivateCredentials(KerberosTicket.class) ) {
        MIEName client = new MIEName(mech, ticket.getClient().getName());
        MIEName server = new MIEName(mech, ticket.getServer().getName());
        if ( src.equals(client) && targ.equals(server) ) {
            return ticket.getSessionKey();
        }
    }
    return null;
}
 
Example 6
Source File: ExtendedExtension.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static ExtendedExtension getInstance(byte[] encoded, int from, int len)
    throws EncodingException {
  Header hdrExtn = OcspRequest.readHeader(encoded, from);
  Header hdrOid = OcspRequest.readHeader(encoded, hdrExtn.readerIndex);
  Header hdrNext = OcspRequest.readHeader(encoded, hdrOid.readerIndex + hdrOid.len);
  Header hdrExtValue;

  boolean critical;
  if (hdrNext.tag == 0x01) { // critical
    critical = encoded[hdrNext.readerIndex] == (byte) 0xFF;
    hdrExtValue = OcspRequest.readHeader(encoded, hdrNext.readerIndex + hdrNext.len);
  } else {
    critical = false;
    hdrExtValue = hdrNext;
  }

  OID extnType = OID.getInstanceForEncoded(encoded, hdrOid.tagIndex);
  if (extnType == null) {
    byte[] bytes = new byte[hdrOid.readerIndex - hdrOid.tagIndex + hdrOid.len];
    System.arraycopy(encoded, hdrOid.tagIndex, bytes, 0, bytes.length);
    ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(bytes);
    LOG.warn("unknown extension {}", oid.getId());
    if (critical) {
      throw new EncodingException("unkown critical extension: " + oid.getId());
    } else {
      return null;
    }
  }

  int extnValueFrom = hdrExtValue.readerIndex;
  int extnValueLength = hdrExtValue.len;

  return new ExtendedExtension(extnType, encoded, from, critical, len,
      extnValueFrom, extnValueLength);
}
 
Example 7
Source File: ExtensionsChecker.java    From xipki with Apache License 2.0 5 votes vote down vote up
private void checkExtnAuthorizationTemplate(StringBuilder failureMsg,
    byte[] extensionValue, Extensions requestedExtns, ExtensionControl extControl) {
  AuthorizationTemplate conf = authorizationTemplate;
  if (conf == null) {
    checkConstantExtnValue(ObjectIdentifiers.Xipki.id_xipki_ext_authorizationTemplate,
        failureMsg, extensionValue, requestedExtns, extControl);

    byte[] expected = getExpectedExtValue(
        ObjectIdentifiers.Xipki.id_xipki_ext_authorizationTemplate, requestedExtns, extControl);
    if (!Arrays.equals(expected, extensionValue)) {
      addViolation(failureMsg, "extension values", hex(extensionValue),
          (expected == null) ? "not present" : hex(expected));
    }
    return;
  }

  ASN1Sequence seq = ASN1Sequence.getInstance(extensionValue);
  ASN1ObjectIdentifier type = ASN1ObjectIdentifier.getInstance(seq.getObjectAt(0));
  ASN1OctetString accessRights = DEROctetString.getInstance(seq.getObjectAt(1));
  if (!conf.getType().getOid().equals(type.getId())) {
    addViolation(failureMsg, "type", type.getId(), conf.getType());
  }

  byte[] isRights = accessRights.getOctets();
  if (!Arrays.equals(conf.getAccessRights().getValue(), isRights)) {
    addViolation(failureMsg, "accessRights",
        hex(isRights), hex(conf.getAccessRights().getValue()));
  }
}
 
Example 8
Source File: ExtensionsChecker.java    From xipki with Apache License 2.0 5 votes vote down vote up
private void checkExtnValidityModel(StringBuilder failureMsg, byte[] extensionValue,
    Extensions requestedExtns, ExtensionControl extControl) {
  ASN1ObjectIdentifier conf = validityModelId;
  if (conf == null) {
    checkConstantExtnValue(Extn.id_extension_validityModel,
        failureMsg, extensionValue, requestedExtns, extControl);
  } else {
    ASN1Sequence seq = ASN1Sequence.getInstance(extensionValue);
    ASN1ObjectIdentifier extValue = ASN1ObjectIdentifier.getInstance(seq.getObjectAt(0));
    if (!conf.equals(extValue)) {
      addViolation(failureMsg, "content", extValue, conf);
    }
  }
}
 
Example 9
Source File: ProxyMessage.java    From xipki with Apache License 2.0 5 votes vote down vote up
private static ASN1ObjectIdentifier getObjectIdentifier(ASN1Encodable object)
    throws BadAsn1ObjectException {
  try {
    return ASN1ObjectIdentifier.getInstance(object);
  } catch (IllegalArgumentException ex) {
    throw new BadAsn1ObjectException("invalid object ObjectIdentifier: " + ex.getMessage(), ex);
  }
}
 
Example 10
Source File: ProxyMessage.java    From xipki with Apache License 2.0 5 votes vote down vote up
private GenECEdwardsOrMontgomeryKeypairParams(ASN1Sequence seq) throws BadAsn1ObjectException {
  requireRange(seq, 3, 3);
  int idx = 0;
  slotId = SlotIdentifier.getInstance(seq.getObjectAt(idx++)).getValue();
  control = NewKeyControl.getInstance(seq.getObjectAt(idx++)).getControl();
  curveOid = ASN1ObjectIdentifier.getInstance(seq.getObjectAt(idx++));
}
 
Example 11
Source File: AbstractRequirementChecks.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private int countInSet(ASN1ObjectIdentifier oid, ASN1Set set) {
	int counter = 0;
	if (set != null) {
		for (int i = 0; i < set.size(); i++) {
			ASN1Sequence attrSeq = ASN1Sequence.getInstance(set.getObjectAt(i));
			ASN1ObjectIdentifier attrOid = ASN1ObjectIdentifier.getInstance(attrSeq.getObjectAt(0));
			if (oid.equals(attrOid)) {
				counter++;
			}
		}
	}
	return counter;
}
 
Example 12
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 13
Source File: Kerb5Context.java    From jcifs-ng with GNU Lesser General Public License v2.1 5 votes vote down vote up
Key searchSessionKey ( Subject subject ) throws GSSException {
    MIEName src = new MIEName(this.gssContext.getSrcName().export());
    MIEName targ = new MIEName(this.gssContext.getTargName().export());

    ASN1ObjectIdentifier mech = ASN1ObjectIdentifier.getInstance(this.gssContext.getMech().getDER());
    for ( KerberosTicket ticket : subject.getPrivateCredentials(KerberosTicket.class) ) {
        MIEName client = new MIEName(mech, ticket.getClient().getName());
        MIEName server = new MIEName(mech, ticket.getServer().getName());
        if ( src.equals(client) && targ.equals(server) ) {
            return ticket.getSessionKey();
        }
    }
    return null;
}
 
Example 14
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 15
Source File: PolicyMapping.java    From keystore-explorer with GNU General Public License v3.0 4 votes vote down vote up
private PolicyMapping(ASN1Sequence seq) {
	// java object in sequence is actually not ASN1ObjectIdentifier but CertPolicyId,
	// so we do a conversion in order to avoid possible class cast exception here
	this.issuerDomainPolicy = ASN1ObjectIdentifier.getInstance(seq.getObjectAt(0).toASN1Primitive());
	this.subjectDomainPolicy = ASN1ObjectIdentifier.getInstance(seq.getObjectAt(1).toASN1Primitive());
}
 
Example 16
Source File: MIEName.java    From jcifs-ng with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Instance a <code>MIEName</code> object.
 * 
 * @param buf
 *            the name of context initiator or acceptor
 */
MIEName ( byte[] buf ) {
    int i;
    int len;
    if ( buf.length < TOK_ID_SIZE + MECH_OID_LEN_SIZE ) {
        throw new IllegalArgumentException();
    }
    // TOK_ID
    for ( i = 0; i < TOK_ID.length; i++ ) {
        if ( TOK_ID[ i ] != buf[ i ] ) {
            throw new IllegalArgumentException();
        }
    }
    // MECH_OID_LEN
    len = 0xff00 & ( buf[ i++ ] << 8 );
    len |= 0xff & buf[ i++ ];

    // MECH_OID
    if ( buf.length < i + len ) {
        throw new IllegalArgumentException();
    }
    byte[] bo = new byte[len];
    System.arraycopy(buf, i, bo, 0, len);
    i += len;
    this.oid = ASN1ObjectIdentifier.getInstance(bo);

    // NAME_LEN
    if ( buf.length < i + NAME_LEN_SIZE ) {
        throw new IllegalArgumentException();
    }
    len = 0xff000000 & ( buf[ i++ ] << 24 );
    len |= 0x00ff0000 & ( buf[ i++ ] << 16 );
    len |= 0x0000ff00 & ( buf[ i++ ] << 8 );
    len |= 0x000000ff & buf[ i++ ];

    // NAME
    if ( buf.length < i + len ) {
        throw new IllegalArgumentException();
    }
    this.name = new String(buf, i, len);

}
 
Example 17
Source File: MIEName.java    From jcifs with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Instance a <code>MIEName</code> object.
 * 
 * @param buf
 *            the name of context initiator or acceptor
 */
MIEName ( byte[] buf ) {
    int i;
    int len;
    if ( buf.length < TOK_ID_SIZE + MECH_OID_LEN_SIZE ) {
        throw new IllegalArgumentException();
    }
    // TOK_ID
    for ( i = 0; i < TOK_ID.length; i++ ) {
        if ( TOK_ID[ i ] != buf[ i ] ) {
            throw new IllegalArgumentException();
        }
    }
    // MECH_OID_LEN
    len = 0xff00 & ( buf[ i++ ] << 8 );
    len |= 0xff & buf[ i++ ];

    // MECH_OID
    if ( buf.length < i + len ) {
        throw new IllegalArgumentException();
    }
    byte[] bo = new byte[len];
    System.arraycopy(buf, i, bo, 0, len);
    i += len;
    this.oid = ASN1ObjectIdentifier.getInstance(bo);

    // NAME_LEN
    if ( buf.length < i + NAME_LEN_SIZE ) {
        throw new IllegalArgumentException();
    }
    len = 0xff000000 & ( buf[ i++ ] << 24 );
    len |= 0x00ff0000 & ( buf[ i++ ] << 16 );
    len |= 0x0000ff00 & ( buf[ i++ ] << 8 );
    len |= 0x000000ff & buf[ i++ ];

    // NAME
    if ( buf.length < i + len ) {
        throw new IllegalArgumentException();
    }
    this.name = new String(buf, i, len);

}
 
Example 18
Source File: UserIdentityExtractor.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public Object extractUserIdentity(X509Certificate[] certs) {
    if (certs == null || certs.length == 0) {
        throw new IllegalArgumentException();
    }

    try {
        Collection<List<?>> subjectAlternativeNames = certs[0].getSubjectAlternativeNames();

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

        Iterator<List<?>> iterator = subjectAlternativeNames.iterator();

        boolean foundUpn = false;
        String tempOtherName = null;
        String tempOid = null;

        while (iterator.hasNext() && !foundUpn) {
            List<?> next = iterator.next();

            if (Integer.class.cast(next.get(0)) == generalName) {

                // We will try to find UPN_OID among the subjectAltNames of type 'otherName' . Just if not found, we will fallback to the other type
                for (int i = 1 ; i<next.size() ; i++) {
                    Object obj = next.get(i);

                    // We have Subject Alternative Name of other type than 'otherName' . Just return it directly
                    if (generalName != 0) {
                        logger.tracef("Extracted identity '%s' from Subject Alternative Name of type '%d'", obj, generalName);
                        return obj;
                    }

                    byte[] otherNameBytes = (byte[]) obj;

                    try {
                        ASN1InputStream asn1Stream = new ASN1InputStream(new ByteArrayInputStream(otherNameBytes));
                        ASN1Encodable asn1otherName = asn1Stream.readObject();
                        asn1otherName = unwrap(asn1otherName);

                        ASN1Sequence asn1Sequence = ASN1Sequence.getInstance(asn1otherName);

                        if (asn1Sequence != null) {
                            ASN1Encodable encodedOid = asn1Sequence.getObjectAt(0);
                            ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(unwrap(encodedOid));
                            tempOid = oid.getId();

                            ASN1Encodable principalNameEncoded = asn1Sequence.getObjectAt(1);
                            DERUTF8String principalName = DERUTF8String.getInstance(unwrap(principalNameEncoded));

                            tempOtherName = principalName.getString();

                            // We found UPN among the 'otherName' principal. We don't need to look other
                            if (UPN_OID.equals(tempOid)) {
                                foundUpn = true;
                                break;
                            }
                        }

                    } catch (Exception e) {
                        logger.error("Failed to parse subjectAltName", e);
                    }
                }

            }
        }

        logger.tracef("Parsed otherName from subjectAltName. OID: '%s', Principal: '%s'", tempOid, tempOtherName);

        return tempOtherName;

    } catch (CertificateParsingException cause) {
        logger.errorf(cause, "Failed to obtain identity from subjectAltName extension");
    }

    return null;
}