org.bouncycastle.asn1.ASN1Sequence Java Examples

The following examples show how to use org.bouncycastle.asn1.ASN1Sequence. 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: LPA.java    From signer with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void parse(ASN1Primitive derObject) {
    ASN1Sequence sequence = ASN1Object.getDERSequence(derObject);
    ASN1Primitive firstObject = sequence.getObjectAt(0).toASN1Primitive();
    this.version = new Version();
    int indice = 0;
    if (firstObject instanceof ASN1Integer) {
        this.version.parse(firstObject);
        indice++;
    }
    ASN1Primitive policyInfos = sequence.getObjectAt(indice).toASN1Primitive();
    DLSequence policyInfosSequence = (DLSequence) policyInfos;
    if (policyInfosSequence != null && policyInfosSequence.size() > 0) {
        this.policyInfos = new ArrayList<>();
        for (int i = 0; i < policyInfosSequence.size(); i++) {
            PolicyInfo policyInfo = new PolicyInfo();
            policyInfo.parse(policyInfosSequence.getObjectAt(i).toASN1Primitive());
            this.policyInfos.add(policyInfo);
        }
    }
    this.nextUpdate = new GeneralizedTime();
    this.nextUpdate.parse(sequence.getObjectAt(indice + 1).toASN1Primitive());
}
 
Example #2
Source File: ProxyMessage.java    From xipki with Apache License 2.0 6 votes vote down vote up
public static NewKeyControl getInstance(Object obj) throws BadAsn1ObjectException {
  if (obj == null || obj instanceof NewKeyControl) {
    return (NewKeyControl) obj;
  }

  try {
    if (obj instanceof ASN1Sequence) {
      return new NewKeyControl((ASN1Sequence) 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 object: " + ex.getMessage(), ex);
  }
}
 
Example #3
Source File: CAdESTimestampSource.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected List<Identifier> getEncapsulatedCertificateIdentifiers(CAdESAttribute unsignedAttribute) {
	List<Identifier> certificateIdentifiers = new ArrayList<>();
	ASN1Sequence seq = (ASN1Sequence) unsignedAttribute.getASN1Object();
	for (int ii = 0; ii < seq.size(); ii++) {
		try {
			final Certificate cs = Certificate.getInstance(seq.getObjectAt(ii));
			CertificateToken certificateToken = DSSUtils.loadCertificate(cs.getEncoded());
			certificateIdentifiers.add(certificateToken.getDSSId());
		} catch (Exception e) {
			String errorMessage = "Unable to parse an encapsulated certificate : {}";
			if (LOG.isDebugEnabled()) {
				LOG.warn(errorMessage, e.getMessage(), e);
			} else {
				LOG.warn(errorMessage, e.getMessage());
			}
		}
	}
	return certificateIdentifiers;
}
 
Example #4
Source File: BurpCertificate.java    From SAMLRaider with MIT License 6 votes vote down vote up
public String getAuthorityKeyIdentifier() {
	byte[] e = certificate.getExtensionValue(Extension.authorityKeyIdentifier.getId());

	if (e == null) {
		return "";
	}

	ASN1Primitive ap;
	byte[] k = {};
	try {
		ap = JcaX509ExtensionUtils.parseExtensionValue(e);
		k = ASN1Sequence.getInstance(ap.getEncoded()).getEncoded();
	} catch (IOException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}
	// Very ugly hack to extract the SHA1 Hash (59 Hex Chars) from the
	// Extension :(
	return CertificateHelper.addHexColons(CertificateHelper.byteArrayToHex(k)).substring(12, k.length * 3 - 1);
}
 
Example #5
Source File: Spkac.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
private PublicKey decodePublicKeyFromBitString(ASN1ObjectIdentifier publicKeyAlgorithmOid,
		ASN1Primitive algorithmParameters, DERBitString publicKey) throws SpkacException {
	if (publicKeyAlgorithmOid.getId().equals(RSA.oid())) {
		return decodeRsaPublicKeyFromBitString(publicKey); // Algorithm parameters are ASN1Null and unnecessary
	} else if (publicKeyAlgorithmOid.getId().equals(DSA.oid())) {
		ASN1Sequence dssParams = (ASN1Sequence) algorithmParameters;

		BigInteger p = ((ASN1Integer) dssParams.getObjectAt(0)).getValue();
		BigInteger q = ((ASN1Integer) dssParams.getObjectAt(1)).getValue();
		BigInteger g = ((ASN1Integer) dssParams.getObjectAt(2)).getValue();

		return decodeDsaPublicKeyFromBitString(publicKey, p, q, g);
	} else {
		throw new SpkacException(MessageFormat.format(
				res.getString("NoSupportPublicKeyAlgorithm.exception.message"), publicKeyAlgorithmOid.getId()));

	}
}
 
Example #6
Source File: ExtensionSyntaxChecker.java    From xipki with Apache License 2.0 6 votes vote down vote up
private static void checkContentTextOrSubFields(String name, ExtnSyntax subField,
    ASN1Encodable obj) throws BadCertTemplateException {
  if (obj instanceof ASN1String) {
    if (subField.getStringRegex() != null) {
      assertMatch(name, subField.getStringRegex(), ((ASN1String) obj).getString());
    }
    return;
  }

  FieldType syntaxType = subField.type();
  if (syntaxType == FieldType.SEQUENCE) {
    checkSequenceSyntax(name, (ASN1Sequence) obj, subField.getSubFields());
  } else if (syntaxType == FieldType.SET) {
    checkSetSyntax(name, (ASN1Set) obj, subField.getSubFields());
  } else if (syntaxType == FieldType.SEQUENCE_OF) {
    checkSequenceOfOrSetOfSyntax(name, (ASN1Sequence) obj, null, subField.getSubFields());
  } else if (syntaxType == FieldType.SET_OF) {
    checkSequenceOfOrSetOfSyntax(name, null, (ASN1Set) obj, subField.getSubFields());
  }
}
 
Example #7
Source File: CMSOCSPSource.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void collectRevocationRefs(AttributeTable unsignedAttributes, ASN1ObjectIdentifier revocationReferencesAttribute, RevocationRefOrigin origin) {
	final Attribute attribute = unsignedAttributes.get(revocationReferencesAttribute);
	if (attribute == null) {
		return;
	}
	final ASN1Set attrValues = attribute.getAttrValues();
	if (attrValues.size() <= 0) {
		return;
	}

	final ASN1Encodable attrValue = attrValues.getObjectAt(0);
	final ASN1Sequence completeRevocationRefs = (ASN1Sequence) attrValue;
	for (int i = 0; i < completeRevocationRefs.size(); i++) {

		final CrlOcspRef otherCertId = CrlOcspRef.getInstance(completeRevocationRefs.getObjectAt(i));
		final OcspListID ocspListID = otherCertId.getOcspids();
		if (ocspListID != null) {
			for (final OcspResponsesID ocspResponsesID : ocspListID.getOcspResponses()) {
				final OCSPRef ocspRef = new OCSPRef(ocspResponsesID);
				addRevocationReference(ocspRef, origin);
			}
		}
	}
}
 
Example #8
Source File: AttestationPackageInfo.java    From Auditor with MIT License 6 votes vote down vote up
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));
}
 
Example #9
Source File: Asn1Utils.java    From AttestationServer with MIT License 6 votes vote down vote up
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;
    }
}
 
Example #10
Source File: RootOfTrust.java    From AttestationServer with MIT License 6 votes vote down vote up
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));
}
 
Example #11
Source File: AttestationPackageInfo.java    From AttestationServer with MIT License 6 votes vote down vote up
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));
}
 
Example #12
Source File: ProxyMessage.java    From xipki with Apache License 2.0 6 votes vote down vote up
public static RemoveObjectsParams getInstance(Object obj) throws BadAsn1ObjectException {
  if (obj == null || obj instanceof RemoveObjectsParams) {
    return (RemoveObjectsParams) obj;
  }

  try {
    if (obj instanceof ASN1Sequence) {
      return new RemoveObjectsParams((ASN1Sequence) 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 #13
Source File: CaClientExample.java    From xipki with Apache License 2.0 6 votes vote down vote up
protected static MyKeypair generateDsaKeypair() throws Exception {
  // plen: 2048, qlen: 256
  DSAParameterSpec spec = new DSAParameterSpec(P2048_Q256_P, P2048_Q256_Q, P2048_Q256_G);
  KeyPairGenerator kpGen = KeyPairGenerator.getInstance("DSA");
  kpGen.initialize(spec);
  KeyPair kp = kpGen.generateKeyPair();

  DSAPublicKey dsaPubKey = (DSAPublicKey) kp.getPublic();
  ASN1EncodableVector vec = new ASN1EncodableVector();
  vec.add(new ASN1Integer(dsaPubKey.getParams().getP()));
  vec.add(new ASN1Integer(dsaPubKey.getParams().getQ()));
  vec.add(new ASN1Integer(dsaPubKey.getParams().getG()));
  ASN1Sequence dssParams = new DERSequence(vec);

  SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo(
      new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa, dssParams),
      new ASN1Integer(dsaPubKey.getY()));

  return new MyKeypair(kp.getPrivate(), subjectPublicKeyInfo);
}
 
Example #14
Source File: ProxyMessage.java    From xipki with Apache License 2.0 6 votes vote down vote up
public static ObjectIdAndCert getInstance(Object obj) throws BadAsn1ObjectException {
  if (obj == null || obj instanceof ObjectIdAndCert) {
    return (ObjectIdAndCert) obj;
  }

  try {
    if (obj instanceof ASN1Sequence) {
      return new ObjectIdAndCert((ASN1Sequence) 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 object: " + ex.getMessage(), ex);
  }
}
 
Example #15
Source File: DSSASN1Utils.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static List<String> getQCLegislations(CertificateToken certToken) {
	final List<String> result = new ArrayList<>();
	final byte[] qcStatement = certToken.getCertificate().getExtensionValue(Extension.qCStatements.getId());
	if (Utils.isArrayNotEmpty(qcStatement)) {
		try {
			final ASN1Sequence seq = getAsn1SequenceFromDerOctetString(qcStatement);
			// Sequence of QCStatement
			for (int ii = 0; ii < seq.size(); ii++) {
				final QCStatement statement = QCStatement.getInstance(seq.getObjectAt(ii));
				if (QC_LEGISLATION_OID.equals(statement.getStatementId().getId())) {
					ASN1Sequence sequenceLegislation = ASN1Sequence.getInstance(statement.getStatementInfo());
					for (int jj = 0; jj < sequenceLegislation.size(); jj++) {
						result.add(getString(sequenceLegislation.getObjectAt(jj)));
					}
					
				}
			}
		} catch (Exception e) {
			LOG.warn("Unable to parse the qCStatements extension '{}' : {}", Utils.toBase64(qcStatement), e.getMessage(), e);
		}
	}
	return result;
}
 
Example #16
Source File: ProxyMessage.java    From xipki with Apache License 2.0 6 votes vote down vote up
public static Mechanism getInstance(Object obj) throws BadAsn1ObjectException {
  if (obj == null || obj instanceof Mechanism) {
    return (Mechanism) obj;
  }

  try {
    if (obj instanceof ASN1Sequence) {
      return new Mechanism((ASN1Sequence) 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 #17
Source File: ProxyMessage.java    From xipki with Apache License 2.0 6 votes vote down vote up
public static GenECKeypairParams getInstance(Object obj) throws BadAsn1ObjectException {
  if (obj == null || obj instanceof GenECKeypairParams) {
    return (GenECKeypairParams) obj;
  }

  try {
    if (obj instanceof ASN1Sequence) {
      return new GenECKeypairParams((ASN1Sequence) 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 #18
Source File: LPA.java    From signer with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void parse(ASN1Primitive derObject) {
    ASN1Sequence sequence = ASN1Object.getDERSequence(derObject);
    ASN1Primitive policyInfos = sequence.getObjectAt(0).toASN1Primitive();
    DLSequence policyInfosSequence = (DLSequence) policyInfos;
    if (policyInfosSequence != null && policyInfosSequence.size() > 0) {
        this.policyInfos = new ArrayList<>();
        for (int i = 0; i < policyInfosSequence.size(); i++) {
            PolicyInfo policyInfo = new PolicyInfo();
            policyInfo.parse(policyInfosSequence.getObjectAt(i).toASN1Primitive());
            this.policyInfos.add(policyInfo);
        }
    }
    this.nextUpdate = new Time();
    this.nextUpdate.parse(sequence.getObjectAt(1).toASN1Primitive());
}
 
Example #19
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 #20
Source File: PolicyInfo.java    From signer with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void parse(ASN1Primitive derObject) {
    ASN1Sequence derSequence = ASN1Object.getDERSequence(derObject);
    ASN1Primitive firstObject = derSequence.getObjectAt(0).toASN1Primitive();
    this.policyName = new DirectoryString(firstObject.toString());
    ASN1Primitive secondObject = derSequence.getObjectAt(1).toASN1Primitive();
    String fieldOfApplication = secondObject.toString();
    this.fieldOfApplication = new DirectoryString(fieldOfApplication);
    this.signingPeriod = new SigningPeriod();
    this.signingPeriod.parse(derSequence.getObjectAt(2).toASN1Primitive());

    int indice = 3;
    ASN1Primitive revocationObject = derSequence.getObjectAt(indice).toASN1Primitive();
    if (!(secondObject instanceof DERTaggedObject)) {
        indice = 4;
    }
    if (indice == 3) {
        this.revocationDate = new Time();
        this.revocationDate.parse(revocationObject);
    }
}
 
Example #21
Source File: SM2Signer.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
public BigInteger[] derDecode(byte[] encoding) throws IOException {
    ASN1Sequence seq = ASN1Sequence.getInstance(ASN1Primitive.fromByteArray(encoding));
    if (seq.size() != 2) {
        return null;
    }

    BigInteger r = ASN1Integer.getInstance(seq.getObjectAt(0)).getValue();
    BigInteger s = ASN1Integer.getInstance(seq.getObjectAt(1)).getValue();

    byte[] expectedEncoding = derEncode(r, s);
    if (!Arrays.constantTimeAreEqual(expectedEncoding, encoding)) {
        return null;
    }

    return new BigInteger[] {r, s};
}
 
Example #22
Source File: ProxyMessage.java    From xipki with Apache License 2.0 6 votes vote down vote up
public static ObjectIdentifiers getInstance(Object obj) throws BadAsn1ObjectException {
  if (obj == null || obj instanceof ObjectIdentifiers) {
    return (ObjectIdentifiers) obj;
  }

  try {
    if (obj instanceof ASN1Sequence) {
      return new ObjectIdentifiers((ASN1Sequence) 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 #23
Source File: CFDv3Debugger.java    From factura-electronica with Apache License 2.0 6 votes vote down vote up
private void dumpDigests() throws Exception {
    System.err.println(cfd.getCadenaOriginal());
    String certStr = cfd.document.getCertificado();
    Base64 b64 = new Base64();
    byte[] cbs = b64.decode(certStr);
    X509Certificate cert = (X509Certificate) KeyLoaderFactory.createInstance(
            KeyLoaderEnumeration.PUBLIC_KEY_LOADER,
            new ByteArrayInputStream(cbs)).getKey();
    cert.checkValidity();
    String sigStr = cfd.document.getSello();
    byte[] signature = b64.decode(sigStr);
    CFDv3.dump("Digestion firmada", signature, System.err);
    Cipher dec = Cipher.getInstance("RSA");
    dec.init(Cipher.DECRYPT_MODE, cert);
    byte[] result = dec.doFinal(signature);
    CFDv3.dump("Digestion decriptada", result, System.err);
    ASN1InputStream aIn = new ASN1InputStream(result);
    ASN1Sequence seq = (ASN1Sequence) aIn.readObject();
    ASN1OctetString sigHash = (ASN1OctetString) seq.getObjectAt(1);
    CFDv3.dump("Sello", sigHash.getOctets(), System.err);
}
 
Example #24
Source File: SigningCertTrustCondition.java    From signer with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void parse(ASN1Primitive derObject) {
    ASN1Sequence derSequence = ASN1Object.getDERSequence(derObject);
    this.signerTrustTrees = new CertificateTrustTrees();
    this.signerTrustTrees.parse(derSequence.getObjectAt(0).toASN1Primitive());
    this.signerRevReq = new CertRevReq();
    this.signerRevReq.parse(derSequence.getObjectAt(1).toASN1Primitive());
}
 
Example #25
Source File: ProxyMessage.java    From xipki with Apache License 2.0 5 votes vote down vote up
private ImportSecretKeyParams(ASN1Sequence seq) throws BadAsn1ObjectException {
  requireRange(seq, 4, 4);
  int idx = 0;
  slotId = SlotIdentifier.getInstance(seq.getObjectAt(idx++)).getValue();
  control = NewKeyControl.getInstance(seq.getObjectAt(idx++)).getControl();
  keyType = getInteger(seq.getObjectAt(idx++)).longValue();
  keyValue = ASN1OctetString.getInstance(seq.getObjectAt(idx++)).getOctets();
}
 
Example #26
Source File: DSSASN1Utils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static List<CertificatePolicy> getCertificatePolicies(final CertificateToken certToken) {
	List<CertificatePolicy> certificatePolicies = new ArrayList<>();
	final byte[] certificatePoliciesBinaries = certToken.getCertificate().getExtensionValue(Extension.certificatePolicies.getId());
	if (Utils.isArrayNotEmpty(certificatePoliciesBinaries)) {
		try {
			ASN1Sequence seq = getAsn1SequenceFromDerOctetString(certificatePoliciesBinaries);
			for (int ii = 0; ii < seq.size(); ii++) {
				CertificatePolicy cp = new CertificatePolicy();
				final PolicyInformation policyInfo = PolicyInformation.getInstance(seq.getObjectAt(ii));
				cp.setOid(policyInfo.getPolicyIdentifier().getId());
				ASN1Sequence policyQualifiersSeq = policyInfo.getPolicyQualifiers();
				if (policyQualifiersSeq != null) {
					for (int jj = 0; jj < policyQualifiersSeq.size(); jj++) {
						PolicyQualifierInfo pqi = PolicyQualifierInfo.getInstance(policyQualifiersSeq.getObjectAt(jj));
						if (PolicyQualifierId.id_qt_cps.equals(pqi.getPolicyQualifierId())) {
							cp.setCpsUrl(getString(pqi.getQualifier()));
						}
					}
				}
				certificatePolicies.add(cp);
			}
		} catch (Exception e) {
			LOG.warn("Unable to parse the certificatePolicies extension '{}' : {}", Utils.toBase64(certificatePoliciesBinaries), e.getMessage(), e);
		}
	}
	return certificatePolicies;
}
 
Example #27
Source File: ProxyMessage.java    From xipki with Apache License 2.0 5 votes vote down vote up
private RemoveObjectsParams(ASN1Sequence seq) throws BadAsn1ObjectException {
  requireRange(seq, 2, 3);
  int idx = 0;
  slotId = SlotIdentifier.getInstance(seq.getObjectAt(idx++)).getValue();
  final int size = seq.size();
  ASN1Encodable asn1Id = null;
  ASN1Encodable asn1Label = null;
  if (size == 2) {
    ASN1Encodable asn1 = seq.getObjectAt(1);
    if (asn1 instanceof ASN1String) {
      asn1Label = asn1;
    } else {
      asn1Id = asn1;
    }
  } else {
    asn1Id = seq.getObjectAt(idx++);
    asn1Label = seq.getObjectAt(idx++);
  }

  objectId = (asn1Id == null) ? null : getOctetStringBytes(asn1Id);
  objectLabel = (asn1Label == null) ? null : getUtf8String(seq.getObjectAt(idx++));

  if ((objectId == null || objectId.length == 0) && StringUtil.isBlank(objectLabel)) {
    throw new BadAsn1ObjectException("invalid object RemoveObjectsParams: "
        + "at least one of id and label must not be null");
  }
}
 
Example #28
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 #29
Source File: PdfPKCS7.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Get the issuer fields from an X509 Certificate
 * @param cert an X509Certificate
 * @return an X509Name
 */
public static X509Name getIssuerFields(X509Certificate cert) {
    try {
        return new X509Name((ASN1Sequence)getIssuer(cert.getTBSCertificate()));
    }
    catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}
 
Example #30
Source File: DSSASN1Utils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static IssuerSerial getIssuerSerial(byte[] binaries) {
	try (ASN1InputStream is = new ASN1InputStream(binaries)) {
		ASN1Sequence seq = (ASN1Sequence) is.readObject();
		return IssuerSerial.getInstance(seq);
	} catch (Exception e) {
		LOG.error("Unable to decode IssuerSerialV2 textContent '{}' : {}", Utils.toBase64(binaries), e.getMessage(), e);
		return null;
	}
}