org.bouncycastle.asn1.ASN1Encodable Java Examples

The following examples show how to use org.bouncycastle.asn1.ASN1Encodable. 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: DSSASN1Utils.java    From dss with GNU Lesser General Public License v2.1 7 votes vote down vote up
public static Map<String, String> get(final X500Principal x500Principal) {
	Map<String, String> treeMap = new HashMap<>();
	final byte[] encoded = x500Principal.getEncoded();
	final ASN1Sequence asn1Sequence = ASN1Sequence.getInstance(encoded);
	final ASN1Encodable[] asn1Encodables = asn1Sequence.toArray();
	for (final ASN1Encodable asn1Encodable : asn1Encodables) {

		final DLSet dlSet = (DLSet) asn1Encodable;
		for (int ii = 0; ii < dlSet.size(); ii++) {

			final DLSequence dlSequence = (DLSequence) dlSet.getObjectAt(ii);
			if (dlSequence.size() != 2) {

				throw new DSSException("The DLSequence must contains exactly 2 elements.");
			}
			final ASN1Encodable asn1EncodableAttributeType = dlSequence.getObjectAt(0);
			final String stringAttributeType = getString(asn1EncodableAttributeType);
			final ASN1Encodable asn1EncodableAttributeValue = dlSequence.getObjectAt(1);
			final String stringAttributeValue = getString(asn1EncodableAttributeValue);
			treeMap.put(stringAttributeType, stringAttributeValue);
		}
	}
	return treeMap;
}
 
Example #2
Source File: CAdESSignature.java    From dss with GNU Lesser General Public License v2.1 7 votes vote down vote up
private SignerAttribute getSignerAttributeV1() {
	final Attribute id_aa_ets_signerAttr = getSignedAttribute(PKCSObjectIdentifiers.id_aa_ets_signerAttr);
	if (id_aa_ets_signerAttr != null) {
		final ASN1Set attrValues = id_aa_ets_signerAttr.getAttrValues();
		final ASN1Encodable attrValue = attrValues.getObjectAt(0);
		try {
			return SignerAttribute.getInstance(attrValue);
		} catch (Exception e) {
			String warningMessage = "Unable to parse signerAttr - [{}]. Reason : {}";
			if (LOG.isDebugEnabled()) {
				LOG.warn(warningMessage, Utils.toBase64(DSSASN1Utils.getDEREncoded(attrValue)), e.getMessage(), e);
			} else {
				LOG.warn(warningMessage, Utils.toBase64(DSSASN1Utils.getDEREncoded(attrValue)), e.getMessage());
			}
		}
	}
	return null;
}
 
Example #3
Source File: CadesLevelBaselineLTATimestampExtractor.java    From dss with GNU Lesser General Public License v2.1 7 votes vote down vote up
/**
 * The field crlsHashIndex is a sequence of octet strings. Each one contains the
 * hash value of one instance of RevocationInfoChoice within crls field of the
 * root SignedData. A hash value for every instance of RevocationInfoChoice, as
 * present at the time when the corresponding archive time-stamp is requested,
 * shall be included in crlsHashIndex. No other hash values shall be included in
 * this field.
 *
 * @return
 * @throws eu.europa.esig.dss.model.DSSException
 */
@SuppressWarnings("unchecked")
private ASN1Sequence getCRLsHashIndex() {

	final ASN1EncodableVector crlsHashIndex = new ASN1EncodableVector();

	final SignedData signedData = SignedData.getInstance(cmsSignedData.toASN1Structure().getContent());
	final ASN1Set signedDataCRLs = signedData.getCRLs();
	if (signedDataCRLs != null) {
		final Enumeration<ASN1Encodable> crLs = signedDataCRLs.getObjects();
		if (crLs != null) {
			while (crLs.hasMoreElements()) {
				final ASN1Encodable asn1Encodable = crLs.nextElement();
				digestAndAddToList(crlsHashIndex, DSSASN1Utils.getDEREncoded(asn1Encodable));
			}
		}
	}

	return new DERSequence(crlsHashIndex);
}
 
Example #4
Source File: Certprofile.java    From xipki with Apache License 2.0 6 votes vote down vote up
public ASN1Encodable createString(String text) {
  Args.notNull(text, "text");

  if (teletexString == this) {
    return new DERT61String(text);
  } else if (printableString == this) {
    return new DERPrintableString(text);
  } else if (utf8String == this) {
    return new DERUTF8String(text);
  } else if (bmpString == this) {
    return new DERBMPString(text);
  } else if (ia5String == this) {
    return new DERIA5String(text, true);
  } else {
    throw new IllegalStateException("should not reach here, unknown StringType " + this.name());
  }
}
 
Example #5
Source File: SubjectChecker.java    From xipki with Apache License 2.0 6 votes vote down vote up
private static boolean matchStringType(ASN1Encodable atvValue, StringType stringType) {
  boolean correctStringType = true;
  switch (stringType) {
    case bmpString:
      correctStringType = (atvValue instanceof DERBMPString);
      break;
    case printableString:
      correctStringType = (atvValue instanceof DERPrintableString);
      break;
    case teletexString:
      correctStringType = (atvValue instanceof DERT61String);
      break;
    case utf8String:
      correctStringType = (atvValue instanceof DERUTF8String);
      break;
    case ia5String:
      correctStringType = (atvValue instanceof DERIA5String);
      break;
    default:
      throw new IllegalStateException("should not reach here, unknown StringType " + stringType);
  } // end switch
  return correctStringType;
}
 
Example #6
Source File: CMSOCSPSource.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void collectRevocationValues(AttributeTable attributes, ASN1ObjectIdentifier revocationValueAttributes,
		RevocationOrigin origin) {

	final ASN1Encodable attValue = DSSASN1Utils.getAsn1Encodable(attributes, revocationValueAttributes);
	if (attValue !=null) {

		RevocationValues revocationValues = DSSASN1Utils.getRevocationValues(attValue);
		if (revocationValues != null) {
			for (final BasicOCSPResponse basicOCSPResponse : revocationValues.getOcspVals()) {
				final BasicOCSPResp basicOCSPResp = new BasicOCSPResp(basicOCSPResponse);
				OCSPResponseBinary ocspResponseIdentifier = OCSPResponseBinary.build(basicOCSPResp);
				addBinary(ocspResponseIdentifier, origin);
			}
		}
		/*
		 * TODO: should add also OtherRevVals, but: "The syntax and semantics of the
		 * other revocation values (OtherRevVals) are outside the scope of the present
		 * document. The definition of the syntax of the other form of revocation
		 * information is as identified by OtherRevRefType."
		 */
	}
}
 
Example #7
Source File: TestCertificateSignRequest.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
private void verifyServiceId(Extensions extensions) {
  GeneralNames gns =
      GeneralNames.fromExtensions(
          extensions, Extension.subjectAlternativeName);
  GeneralName[] names = gns.getNames();
  for(int i=0; i < names.length; i++) {
    if(names[i].getTagNo() == GeneralName.otherName) {
      ASN1Encodable asn1Encodable = names[i].getName();
      Iterator iterator = ((DLSequence) asn1Encodable).iterator();
      while (iterator.hasNext()) {
        Object o = iterator.next();
        if (o instanceof ASN1ObjectIdentifier) {
          String oid = o.toString();
          Assert.assertEquals(oid, "2.16.840.1.113730.3.1.34");
        }
        if (o instanceof DERTaggedObject) {
          String serviceName = ((DERTaggedObject)o).getObject().toString();
          Assert.assertEquals(serviceName, "OzoneMarketingCluster003");
        }
      }
    }
  }
}
 
Example #8
Source File: Actions.java    From xipki with Apache License 2.0 6 votes vote down vote up
@Override
protected Object execute0() throws Exception {
  CertificateList crl = CertificateList.getInstance(
      X509Util.toDerEncoded(IoUtil.read(inFile)));

  if (crlNumber != null && crlNumber) {
    ASN1Encodable asn1 = crl.getTBSCertList().getExtensions().getExtensionParsedValue(
        Extension.cRLNumber);
    if (asn1 == null) {
      return "null";
    }
    return getNumber(ASN1Integer.getInstance(asn1).getPositiveValue());
  } else if (issuer != null && issuer) {
    return crl.getIssuer().toString();
  } else if (thisUpdate != null && thisUpdate) {
    return toUtcTimeyyyyMMddhhmmssZ(crl.getThisUpdate().getDate());
  } else if (nextUpdate != null && nextUpdate) {
    return crl.getNextUpdate() == null ? "null" :
      toUtcTimeyyyyMMddhhmmssZ(crl.getNextUpdate().getDate());
  }

  return null;
}
 
Example #9
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 #10
Source File: CMSCertificateSource.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void extractSigningCertificateV1(Attribute attribute) {
	final ASN1Set attrValues = attribute.getAttrValues();
	for (int ii = 0; ii < attrValues.size(); ii++) {
		final ASN1Encodable asn1Encodable = attrValues.getObjectAt(ii);
		try {
			final SigningCertificate signingCertificate = SigningCertificate.getInstance(asn1Encodable);
			if (signingCertificate != null) {
				extractESSCertIDs(signingCertificate.getCerts(), CertificateRefOrigin.SIGNING_CERTIFICATE);
			} else {
				LOG.warn("SigningCertificate attribute is null");
			}
		} catch (Exception e) {
			LOG.warn("SigningCertificate attribute '{}' is not well defined!", Utils.toBase64(DSSASN1Utils.getDEREncoded(asn1Encodable)));
		}
	}
}
 
Example #11
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 #12
Source File: AttestationApplicationId.java    From android-testdpc with Apache License 2.0 6 votes vote down vote up
@RequiresApi(api = VERSION_CODES.N)
public AttestationApplicationId(ASN1Encodable asn1Encodable)
        throws CertificateParsingException {
    if (!(asn1Encodable instanceof ASN1Sequence)) {
        throw new CertificateParsingException(
                "Expected sequence for AttestationApplicationId, found "
                        + asn1Encodable.getClass().getName());
    }

    ASN1Sequence sequence = (ASN1Sequence) asn1Encodable;
    packageInfos = parseAttestationPackageInfos(sequence.getObjectAt(PACKAGE_INFOS_INDEX));
    // The infos must be sorted, the implementation of Comparable relies on it.
    packageInfos.sort(null);
    signatureDigests = parseSignatures(sequence.getObjectAt(SIGNATURE_DIGESTS_INDEX));
    // The digests must be sorted. the implementation of Comparable relies on it
    signatureDigests.sort(new ByteArrayComparator());
}
 
Example #13
Source File: AlgorithmUtil.java    From xipki with Apache License 2.0 6 votes vote down vote up
public static AlgorithmIdentifier extractDigesetAlgFromSigAlg(AlgorithmIdentifier sigAlgId)
    throws NoSuchAlgorithmException {
  ASN1ObjectIdentifier algOid = sigAlgId.getAlgorithm();

  ASN1ObjectIdentifier digestAlgOid;
  if (PKCSObjectIdentifiers.id_RSASSA_PSS.equals(algOid)) {
    ASN1Encodable asn1Encodable = sigAlgId.getParameters();
    RSASSAPSSparams param = RSASSAPSSparams.getInstance(asn1Encodable);
    digestAlgOid = param.getHashAlgorithm().getAlgorithm();
  } else {
    HashAlgo digestAlg = sigAlgOidToDigestMap.get(algOid);
    if (digestAlg == null) {
      throw new NoSuchAlgorithmException("unknown signature algorithm " + algOid.getId());
    }
    digestAlgOid = digestAlg.getOid();
  }

  return new AlgorithmIdentifier(digestAlgOid, DERNull.INSTANCE);
}
 
Example #14
Source File: CertificateUtils.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Extract extensions from CSR object
 */
public static Extensions getExtensionsFromCSR(JcaPKCS10CertificationRequest csr) {
    Attribute[] attributess = csr.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    for (Attribute attribute : attributess) {
        ASN1Set attValue = attribute.getAttrValues();
        if (attValue != null) {
            ASN1Encodable extension = attValue.getObjectAt(0);
            if (extension instanceof Extensions) {
                return (Extensions) extension;
            } else if (extension instanceof DERSequence) {
                return Extensions.getInstance(extension);
            }
        }
    }
    return null;
}
 
Example #15
Source File: RootOfTrust.java    From Auditor 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 #16
Source File: AttestationCertificateBuilder.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
public void addExtension(ASN1ObjectIdentifier oid, boolean isCritical, ASN1Encodable value) {
    try {
        certificateBuilder.addExtension(oid, isCritical, value);
    } catch (CertIOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example #17
Source File: PAdESUtils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Returns {@link RevocationInfoArchival} from the given encodable
 * 
 * @param encodable
 *                  the encoded data to be parsed
 * @return an instance of RevocationValues or null if the parsing failled
 */
public static RevocationInfoArchival getRevocationInfoArchivals(ASN1Encodable encodable) {
	if (encodable != null) {
		try {
			return RevocationInfoArchival.getInstance(encodable);
		} catch (Exception e) {
			LOG.warn("Unable to parse RevocationInfoArchival", e);
		}
	}
	return null;
}
 
Example #18
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 #19
Source File: IdentifiedCertprofile.java    From xipki with Apache License 2.0 5 votes vote down vote up
private static ASN1Sequence createSubjectInfoAccess(
    Map<ASN1ObjectIdentifier, Extension> requestedExtensions,
    Map<ASN1ObjectIdentifier, Set<GeneralNameMode>> modes) throws BadCertTemplateException {
  if (modes == null) {
    return null;
  }

  Extension extn = requestedExtensions.get(Extension.subjectInfoAccess);
  if (extn == null) {
    return null;
  }

  ASN1Encodable extValue = extn.getParsedValue();
  if (extValue == null) {
    return null;
  }

  ASN1Sequence reqSeq = ASN1Sequence.getInstance(extValue);
  int size = reqSeq.size();

  ASN1EncodableVector vec = new ASN1EncodableVector();
  for (int i = 0; i < size; i++) {
    AccessDescription ad = AccessDescription.getInstance(reqSeq.getObjectAt(i));
    ASN1ObjectIdentifier accessMethod = ad.getAccessMethod();
    Set<GeneralNameMode> generalNameModes = modes.get(accessMethod);

    if (generalNameModes == null) {
      throw new BadCertTemplateException("subjectInfoAccess.accessMethod "
          + accessMethod.getId() + " is not allowed");
    }

    GeneralName accessLocation = BaseCertprofile.createGeneralName(
        ad.getAccessLocation(), generalNameModes);
    vec.add(new AccessDescription(accessMethod, accessLocation));
  } // end for

  return vec.size() > 0 ? new DERSequence(vec) : null;
}
 
Example #20
Source File: PAdESCRLSource.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void collectCRLArchivalValues(AttributeTable attributes) {
	final ASN1Encodable attValue = DSSASN1Utils.getAsn1Encodable(attributes, OID.adbe_revocationInfoArchival);
	RevocationInfoArchival revValues = PAdESUtils.getRevocationInfoArchivals(attValue);
	if (revValues != null) {
		for (final CertificateList revValue : revValues.getCrlVals()) {
			try {
				addBinary(CRLUtils.buildCRLBinary(revValue.getEncoded()), RevocationOrigin.ADBE_REVOCATION_INFO_ARCHIVAL);
			} catch (IOException e) {
				LOG.warn("Could not convert CertificateList to CRLBinary : {}", e.getMessage());
			}
		}
	}
}
 
Example #21
Source File: X509Ext.java    From portecle with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get S/MIME capabilities (1.2.840.113549.1.9.15) extension value as a string.
 *
 * <pre>
 * SMIMECapability ::= SEQUENCE {
 *   capabilityID OBJECT IDENTIFIER,
 *   parameters ANY DEFINED BY capabilityID OPTIONAL }
 * SMIMECapabilities ::= SEQUENCE OF SMIMECapability
 * </pre>
 *
 * @see <a href="https://tools.ietf.org/html/rfc2633">RFC 2633</a>
 * @param bValue The octet string value
 * @return Extension value as a string
 * @throws IOException If an I/O problem occurs
 */
private String getSmimeCapabilitiesStringValue(byte[] bValue)
    throws IOException
{
	SMIMECapabilities caps = SMIMECapabilities.getInstance(ASN1Primitive.fromByteArray(bValue));

	String sParams = RB.getString("SmimeParameters");

	StringBuilder sb = new StringBuilder();

	for (Object o : caps.getCapabilities(null))
	{

		SMIMECapability cap = (SMIMECapability) o;

		String sCapId = cap.getCapabilityID().getId();
		String sCap = getRes(sCapId, "UnrecognisedSmimeCapability");

		if (sb.length() != 0)
		{
			sb.append("<br>");
		}
		sb.append("<ul><li>");
		sb.append(MessageFormat.format(sCap, sCapId));

		ASN1Encodable params;
		if ((params = cap.getParameters()) != null)
		{
			sb.append("<ul><li>");
			sb.append(sParams);
			sb.append(": ");
			sb.append(stringify(params));
			sb.append("</li></ul>");
		}

		sb.append("</li></ul>");
	}

	return sb.toString();
}
 
Example #22
Source File: Identity.java    From ts3j with Apache License 2.0 5 votes vote down vote up
public byte[] toASN() throws IOException {
    return new DERSequence(
            new ASN1Encodable[] {
                    new DERBitString(0),
                    new ASN1Integer(32),
                    new ASN1Integer(getPublicKey().getXCoord().toBigInteger()),
                    new ASN1Integer(getPublicKey().getYCoord().toBigInteger())
            }
    ).getEncoded();
}
 
Example #23
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 #24
Source File: ExtensionValues.java    From xipki with Apache License 2.0 5 votes vote down vote up
public boolean addExtension(ASN1ObjectIdentifier type, boolean critical, ASN1Encodable value) {
  Args.notNull(type, "type");
  Args.notNull(value, "value");

  if (extensions.containsKey(type)) {
    return false;
  }
  extensions.put(type, new ExtensionValue(critical, value));
  return true;
}
 
Example #25
Source File: CAdESSignature.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private SignerAttributeV2 getSignerAttributeV2() {
	final Attribute id_aa_ets_signerAttrV2 = getSignedAttribute(OID.id_aa_ets_signerAttrV2);
	if (id_aa_ets_signerAttrV2 != null) {
		final ASN1Set attrValues = id_aa_ets_signerAttrV2.getAttrValues();
		final ASN1Encodable attrValue = attrValues.getObjectAt(0);
		try {
			return SignerAttributeV2.getInstance(attrValue);
		} catch (Exception e) {
			LOG.warn("Unable to parse signerAttrV2 : {}", Utils.toBase64(DSSASN1Utils.getDEREncoded(attrValue)), e);
		}
	}
	return null;
}
 
Example #26
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 #27
Source File: EnrolmentResponse.java    From xipki with Apache License 2.0 5 votes vote down vote up
public EnrolmentResponse(PkiMessage pkcsRep) throws ScepClientException {
  Args.notNull(pkcsRep, "pkcsRep");
  MessageType messageType = pkcsRep.getMessageType();
  if (MessageType.CertRep != messageType) {
    throw new ScepClientException("messageType must not be other than CertRep: " + messageType);
  }
  this.pkcsRep = pkcsRep;

  if (PkiStatus.SUCCESS != pkcsRep.getPkiStatus()) {
    return;
  }

  ASN1Encodable messageData = pkcsRep.getMessageData();
  if (!(messageData instanceof ContentInfo)) {
    throw new ScepClientException("pkcsRep is not a ContentInfo");
  }

  ContentInfo ci = (ContentInfo) messageData;
  SignedData sd = SignedData.getInstance(ci.getContent());
  ASN1Set asn1Certs = sd.getCertificates();
  if (asn1Certs == null || asn1Certs.size() == 0) {
    throw new ScepClientException("no certificate is embedded in pkcsRep");
  }

  try {
    this.certificates = Collections.unmodifiableList(ScepUtil.getCertsFromSignedData(sd));
  } catch (CertificateException ex) {
    throw new ScepClientException(ex.getMessage(), ex);
  }
}
 
Example #28
Source File: BCECUtil.java    From littleca with Apache License 2.0 5 votes vote down vote up
/**
 * openssl d2i_ECPrivateKey函数要求的DER编码的私钥也是PKCS1标准的,
 * 这个工具函数的主要目的就是为了能生成一个openssl可以“识别”的ECC私钥
 *
 * @param priKey
 * @param pubKey
 * @return
 * @throws IOException
 */
public static byte[] convertEcPriKeyToPkcs1Der(ECPrivateKeyParameters priKey,
                                               ECPublicKeyParameters pubKey) throws IOException {
    byte[] pkcs8Bytes = convertEcPriKeyToPkcs8Der(priKey, pubKey);
    PrivateKeyInfo pki = PrivateKeyInfo.getInstance(pkcs8Bytes);
    ASN1Encodable encodable = pki.parsePrivateKey();
    ASN1Primitive primitive = encodable.toASN1Primitive();
    byte[] pkcs1Bytes = primitive.getEncoded();
    return pkcs1Bytes;
}
 
Example #29
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 #30
Source File: cryptoCommon.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Method to verify attestation certificate
 *
 * @param attestationCertificate - the attestation cert to be verified
 * @return - boolean, based on the result of verification
 */
public static boolean verifyU2FAttestationCertificate(X509Certificate attestationCertificate) {

    PublicKey attcertPublicKey = attestationCertificate.getPublicKey();
    byte[] attPublicKey = attcertPublicKey.getEncoded();
    SubjectPublicKeyInfo spki = SubjectPublicKeyInfo.getInstance(ASN1Sequence.getInstance(attPublicKey));
    spki.getAlgorithm();

    //  get algorithm from the AlgorithmIdentifier refer to RFC 5480
    AlgorithmIdentifier sigAlgId = spki.getAlgorithm();
    ASN1ObjectIdentifier asoi = sigAlgId.getAlgorithm();

    if (!(asoi.getId().equals("1.2.840.10045.2.1"))) {
        //not an EC Public Key
        logp(Level.SEVERE, classname, "verifyAttestationCertificate", "FIDO-ERR-5008", "Only Elliptic-Curve (EC) keys are allowed, the public key in this certificate not an EC public key");
        return false;
    }

    //  Get parameters from AlgorithmIdentifier, parameters field is optional RFC 5480,
    ASN1Encodable asne = sigAlgId.getParameters();
    if (asne == null) {
        logp(Level.WARNING, classname, "verifyAttestationCertificate", "FIDO-WARN-5001", "");
    } else {
        if (!(asne.toString().equals("1.2.840.10045.3.1.7"))) { //key not generated using curve secp256r1
            logp(Level.SEVERE, classname, "verifyAttestationCertificate", "FIDO-ERR-5009", "");
            return false;
        }
    }

    logp(Level.FINE, classname, "verifyAttestationCertificate", "FIDO-MSG-5025", "");
    return true;
}