org.bouncycastle.asn1.ASN1Enumerated Java Examples

The following examples show how to use org.bouncycastle.asn1.ASN1Enumerated. 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
@Override
public ASN1Primitive toASN1Primitive() {
  ASN1EncodableVector vector = new ASN1EncodableVector();
  vector.add(new DERUTF8String(control.getLabel()));

  byte[] id = control.getId();
  if (id != null) {
    vector.add(new DERTaggedObject(0, new DEROctetString(id)));
  }

  Set<P11KeyUsage> usages = control.getUsages();
  if (CollectionUtil.isNotEmpty(usages)) {
    ASN1EncodableVector asn1Usages = new ASN1EncodableVector();
    for (P11KeyUsage usage : usages) {
      int value = usageToValueMap.get(usage);
      asn1Usages.add(new ASN1Enumerated(value));
    }
    vector.add(new DERTaggedObject(1, new DERSequence(asn1Usages)));
  }

  if (control.getExtractable() != null) {
    vector.add(new DERTaggedObject(2, ASN1Boolean.getInstance(control.getExtractable())));
  }

  return new DERSequence(vector);
}
 
Example #2
Source File: Asn1Utils.java    From Auditor with MIT License 5 votes vote down vote up
public static int getIntegerFromAsn1(ASN1Encodable asn1Value)
        throws CertificateParsingException {
    if (asn1Value instanceof ASN1Integer) {
        return bigIntegerToInt(((ASN1Integer) asn1Value).getValue());
    } else if (asn1Value instanceof ASN1Enumerated) {
        return bigIntegerToInt(((ASN1Enumerated) asn1Value).getValue());
    } else {
        throw new CertificateParsingException(
                "Integer value expected, " + asn1Value.getClass().getName() + " found.");
    }
}
 
Example #3
Source File: Asn1Utils.java    From AttestationServer with MIT License 5 votes vote down vote up
public static int getIntegerFromAsn1(ASN1Encodable asn1Value)
        throws CertificateParsingException {
    if (asn1Value instanceof ASN1Integer) {
        return bigIntegerToInt(((ASN1Integer) asn1Value).getValue());
    } else if (asn1Value instanceof ASN1Enumerated) {
        return bigIntegerToInt(((ASN1Enumerated) asn1Value).getValue());
    } else {
        throw new CertificateParsingException(
                "Integer value expected, " + asn1Value.getClass().getName() + " found.");
    }
}
 
Example #4
Source File: NegTokenTarg.java    From jcifs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public byte[] toByteArray () {
    try {
        ByteArrayOutputStream collector = new ByteArrayOutputStream();
        DEROutputStream der = new DEROutputStream(collector);
        ASN1EncodableVector fields = new ASN1EncodableVector();
        int res = getResult();
        if ( res != UNSPECIFIED_RESULT ) {
            fields.add(new DERTaggedObject(true, 0, new ASN1Enumerated(res)));
        }
        ASN1ObjectIdentifier mech = getMechanism();
        if ( mech != null ) {
            fields.add(new DERTaggedObject(true, 1, mech));
        }
        byte[] mechanismToken = getMechanismToken();
        if ( mechanismToken != null ) {
            fields.add(new DERTaggedObject(true, 2, new DEROctetString(mechanismToken)));
        }
        byte[] mechanismListMIC = getMechanismListMIC();
        if ( mechanismListMIC != null ) {
            fields.add(new DERTaggedObject(true, 3, new DEROctetString(mechanismListMIC)));
        }
        der.writeObject(new DERTaggedObject(true, 1, new DERSequence(fields)));
        return collector.toByteArray();
    }
    catch ( IOException ex ) {
        throw new IllegalStateException(ex.getMessage());
    }
}
 
Example #5
Source File: ASN1Parsing.java    From android-key-attestation with Apache License 2.0 5 votes vote down vote up
static int getIntegerFromAsn1(ASN1Encodable asn1Value) {
  if (asn1Value instanceof ASN1Integer) {
    return ((ASN1Integer) asn1Value).getValue().intValueExact();
  } else if (asn1Value instanceof ASN1Enumerated) {
    return ((ASN1Enumerated) asn1Value).getValue().intValueExact();
  } else {
    throw new IllegalArgumentException(
        "Integer value expected; found " + asn1Value.getClass().getName() + " instead.");
  }
}
 
Example #6
Source File: NegTokenTarg.java    From jcifs-ng with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public byte[] toByteArray () {
    try {
        ByteArrayOutputStream collector = new ByteArrayOutputStream();
        DEROutputStream der = new DEROutputStream(collector);
        ASN1EncodableVector fields = new ASN1EncodableVector();
        int res = getResult();
        if ( res != UNSPECIFIED_RESULT ) {
            fields.add(new DERTaggedObject(true, 0, new ASN1Enumerated(res)));
        }
        ASN1ObjectIdentifier mech = getMechanism();
        if ( mech != null ) {
            fields.add(new DERTaggedObject(true, 1, mech));
        }
        byte[] mechanismToken = getMechanismToken();
        if ( mechanismToken != null ) {
            fields.add(new DERTaggedObject(true, 2, new DEROctetString(mechanismToken)));
        }
        byte[] mechanismListMIC = getMechanismListMIC();
        if ( mechanismListMIC != null ) {
            fields.add(new DERTaggedObject(true, 3, new DEROctetString(mechanismListMIC)));
        }
        der.writeObject(new DERTaggedObject(true, 1, new DERSequence(fields)));
        return collector.toByteArray();
    }
    catch ( IOException ex ) {
        throw new IllegalStateException(ex.getMessage());
    }
}
 
Example #7
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 #8
Source File: Asn1Dump.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
private String dumpEnumerated(ASN1Enumerated asn1Enumerated) {
	StringBuilder sb = new StringBuilder();

	sb.append(indentSequence.toString(indentLevel));
	sb.append("ENUMERATED=");
	sb.append(asn1Enumerated.getValue());
	sb.append(NEWLINE);

	return sb.toString();
}
 
Example #9
Source File: Asn1Utils.java    From android-testdpc with Apache License 2.0 5 votes vote down vote up
public static int getIntegerFromAsn1(ASN1Encodable asn1Value)
        throws CertificateParsingException {
    if (asn1Value instanceof ASN1Integer) {
        return bigIntegerToInt(((ASN1Integer) asn1Value).getValue());
    } else if (asn1Value instanceof ASN1Enumerated) {
        return bigIntegerToInt(((ASN1Enumerated) asn1Value).getValue());
    } else {
        throw new CertificateParsingException(
                "Integer value expected, " + asn1Value.getClass().getName() + " found.");
    }
}
 
Example #10
Source File: CmpCaClient.java    From xipki with Apache License 2.0 5 votes vote down vote up
public boolean revokeCert(BigInteger serialNumber, CRLReason reason) throws Exception {
  ProtectedPKIMessageBuilder builder = new ProtectedPKIMessageBuilder(
      PKIHeader.CMP_2000, requestorSubject, responderSubject);
  builder.setMessageTime(new Date());
  builder.setTransactionID(randomTransactionId());
  builder.setSenderNonce(randomSenderNonce());

  CertTemplateBuilder certTempBuilder = new CertTemplateBuilder();
  certTempBuilder.setIssuer(caSubject);
  certTempBuilder.setSerialNumber(new ASN1Integer(serialNumber));

  AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(caSubjectKeyIdentifier);
  byte[] encodedAki = aki.getEncoded();

  Extension extAki = new Extension(Extension.authorityKeyIdentifier, false, encodedAki);
  Extensions certTempExts = new Extensions(extAki);
  certTempBuilder.setExtensions(certTempExts);

  ASN1Enumerated asn1Reason = new ASN1Enumerated(reason.getValue().intValue());
  Extensions exts = new Extensions(
      new Extension(Extension.reasonCode, true, new DEROctetString(asn1Reason.getEncoded())));
  RevDetails revDetails = new RevDetails(certTempBuilder.build(), exts);

  RevReqContent content = new RevReqContent(revDetails);
  builder.setBody(new PKIBody(PKIBody.TYPE_REVOCATION_REQ, content));
  ProtectedPKIMessage request = build(builder);

  PKIMessage response = transmit(request, null);
  return parseRevocationResult(response, serialNumber);
}
 
Example #11
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 #12
Source File: CmpAgent.java    From xipki with Apache License 2.0 5 votes vote down vote up
private PKIMessage buildUnrevokeOrRemoveCertRequest(UnrevokeOrRemoveCertRequest request,
    int reasonCode) throws CmpClientException {
  PKIHeader header = buildPkiHeader(null);

  List<UnrevokeOrRemoveCertRequest.Entry> requestEntries = request.getRequestEntries();
  List<RevDetails> revDetailsArray = new ArrayList<>(requestEntries.size());
  for (UnrevokeOrRemoveCertRequest.Entry requestEntry : requestEntries) {
    CertTemplateBuilder certTempBuilder = new CertTemplateBuilder();
    certTempBuilder.setIssuer(requestEntry.getIssuer());
    certTempBuilder.setSerialNumber(new ASN1Integer(requestEntry.getSerialNumber()));
    byte[] aki = requestEntry.getAuthorityKeyIdentifier();
    if (aki != null) {
      Extensions certTempExts = getCertTempExtensions(aki);
      certTempBuilder.setExtensions(certTempExts);
    }

    Extension[] extensions = new Extension[1];

    try {
      ASN1Enumerated reason = new ASN1Enumerated(reasonCode);
      extensions[0] = new Extension(Extension.reasonCode, true,
              new DEROctetString(reason.getEncoded()));
    } catch (IOException ex) {
      throw new CmpClientException(ex.getMessage(), ex);
    }
    Extensions exts = new Extensions(extensions);

    RevDetails revDetails = new RevDetails(certTempBuilder.build(), exts);
    revDetailsArray.add(revDetails);
  }

  RevReqContent content = new RevReqContent(revDetailsArray.toArray(new RevDetails[0]));
  PKIBody body = new PKIBody(PKIBody.TYPE_REVOCATION_REQ, content);
  return new PKIMessage(header, body);
}
 
Example #13
Source File: ExtensionSyntaxChecker.java    From xipki with Apache License 2.0 4 votes vote down vote up
private static FieldType getFieldType(ASN1Encodable obj) {
  FieldType expectedType;
  if (obj instanceof DERBitString) {
    expectedType = FieldType.BIT_STRING;
  } else if (obj instanceof DERBMPString) {
    expectedType = FieldType.BMPString;
  } else if (obj instanceof ASN1Boolean) {
    expectedType = FieldType.BOOLEAN;
  } else if (obj instanceof ASN1Enumerated) {
    expectedType = FieldType.ENUMERATED;
  } else if (obj instanceof DERGeneralizedTime) {
    expectedType = FieldType.GeneralizedTime;
  } else if (obj instanceof DERIA5String) {
    expectedType = FieldType.IA5String;
  } else if (obj instanceof ASN1Integer) {
    expectedType = FieldType.INTEGER;
  } else if (obj instanceof DERNull) {
    expectedType = FieldType.NULL;
  } else if (obj instanceof DEROctetString) {
    expectedType = FieldType.OCTET_STRING;
  } else if (obj instanceof ASN1ObjectIdentifier) {
    expectedType = FieldType.OID;
  } else if (obj instanceof DERPrintableString) {
    expectedType = FieldType.PrintableString;
  } else if (obj instanceof DERT61String) {
    expectedType = FieldType.TeletexString;
  } else if (obj instanceof DERUTCTime) {
    expectedType = FieldType.UTCTime;
  } else if (obj instanceof DERUTF8String) {
    expectedType = FieldType.UTF8String;
  } else if (obj instanceof X500Name) {
    expectedType = FieldType.Name;
  } else if (obj instanceof ASN1Sequence) {
    try {
      X500Name.getInstance(obj);
      expectedType = FieldType.Name;
    } catch (Exception ex) {
      expectedType = FieldType.SEQUENCE;
    }
  } else if (obj instanceof ASN1Set) {
    expectedType = FieldType.SET;
  } else {
    expectedType = null;
  }

  return expectedType;
}
 
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: CmpResponder.java    From xipki with Apache License 2.0 4 votes vote down vote up
private PKIBody cmpUnRevokeRemoveCertificates(PKIMessage request, PKIHeaderBuilder respHeader,
    CmpControl cmpControl, PKIHeader reqHeader, PKIBody reqBody, CmpRequestorInfo requestor,
    String msgId, AuditEvent event) {
  Integer requiredPermission = null;
  boolean allRevdetailsOfSameType = true;

  RevReqContent rr = RevReqContent.getInstance(reqBody.getContent());
  RevDetails[] revContent = rr.toRevDetailsArray();

  int len = revContent.length;
  for (int i = 0; i < len; i++) {
    RevDetails revDetails = revContent[i];
    Extensions crlDetails = revDetails.getCrlEntryDetails();
    int reasonCode = CrlReason.UNSPECIFIED.getCode();
    if (crlDetails != null) {
      ASN1ObjectIdentifier extId = Extension.reasonCode;
      ASN1Encodable extValue = crlDetails.getExtensionParsedValue(extId);
      if (extValue != null) {
        reasonCode = ASN1Enumerated.getInstance(extValue).getValue().intValue();
      }
    }

    if (reasonCode == XiSecurityConstants.CMP_CRL_REASON_REMOVE) {
      if (requiredPermission == null) {
        event.addEventType(CaAuditConstants.Cmp.TYPE_rr_remove);
        requiredPermission = PermissionConstants.REMOVE_CERT;
      } else if (requiredPermission != PermissionConstants.REMOVE_CERT) {
        allRevdetailsOfSameType = false;
        break;
      }
    } else if (reasonCode == CrlReason.REMOVE_FROM_CRL.getCode()) {
      if (requiredPermission == null) {
        event.addEventType(CaAuditConstants.Cmp.TYPE_rr_unrevoke);
        requiredPermission = PermissionConstants.UNREVOKE_CERT;
      } else if (requiredPermission != PermissionConstants.UNREVOKE_CERT) {
        allRevdetailsOfSameType = false;
        break;
      }
    } else {
      if (requiredPermission == null) {
        event.addEventType(CaAuditConstants.Cmp.TYPE_rr_revoke);
        requiredPermission = PermissionConstants.REVOKE_CERT;
      } else if (requiredPermission != PermissionConstants.REVOKE_CERT) {
        allRevdetailsOfSameType = false;
        break;
      }
    }
  } // end for

  if (!allRevdetailsOfSameType) {
    ErrorMsgContent emc = new ErrorMsgContent(
        new PKIStatusInfo(PKIStatus.rejection,
        new PKIFreeText("not all revDetails are of the same type"),
        new PKIFailureInfo(PKIFailureInfo.badRequest)));

    return new PKIBody(PKIBody.TYPE_ERROR, emc);
  }

  try {
    checkPermission(requestor, requiredPermission);
  } catch (InsuffientPermissionException ex) {
    event.setStatus(AuditStatus.FAILED);
    event.addEventData(CaAuditConstants.NAME_message, "NOT_PERMITTED");
    return buildErrorMsgPkiBody(PKIStatus.rejection, PKIFailureInfo.notAuthorized, null);
  }

  return unRevokeRemoveCertificates(request, rr, requiredPermission, cmpControl, msgId, event);
}
 
Example #16
Source File: CmpAgent.java    From xipki with Apache License 2.0 4 votes vote down vote up
private PKIMessage buildRevokeCertRequest(RevokeCertRequest request)
    throws CmpClientException {
  PKIHeader header = buildPkiHeader(null);

  List<RevokeCertRequest.Entry> requestEntries = request.getRequestEntries();
  List<RevDetails> revDetailsArray = new ArrayList<>(requestEntries.size());
  for (RevokeCertRequest.Entry requestEntry : requestEntries) {
    CertTemplateBuilder certTempBuilder = new CertTemplateBuilder();
    certTempBuilder.setIssuer(requestEntry.getIssuer());
    certTempBuilder.setSerialNumber(new ASN1Integer(requestEntry.getSerialNumber()));
    byte[] aki = requestEntry.getAuthorityKeyIdentifier();
    if (aki != null) {
      Extensions certTempExts = getCertTempExtensions(aki);
      certTempBuilder.setExtensions(certTempExts);
    }

    Date invalidityDate = requestEntry.getInvalidityDate();
    int idx = (invalidityDate == null) ? 1 : 2;
    Extension[] extensions = new Extension[idx];

    try {
      ASN1Enumerated reason = new ASN1Enumerated(requestEntry.getReason());
      extensions[0] = new Extension(Extension.reasonCode, true,
          new DEROctetString(reason.getEncoded()));

      if (invalidityDate != null) {
        ASN1GeneralizedTime time = new ASN1GeneralizedTime(invalidityDate);
        extensions[1] = new Extension(Extension.invalidityDate, true,
                new DEROctetString(time.getEncoded()));
      }
    } catch (IOException ex) {
      throw new CmpClientException(ex.getMessage(), ex);
    }

    Extensions exts = new Extensions(extensions);

    RevDetails revDetails = new RevDetails(certTempBuilder.build(), exts);
    revDetailsArray.add(revDetails);
  }

  RevReqContent content = new RevReqContent(revDetailsArray.toArray(new RevDetails[0]));
  PKIBody body = new PKIBody(PKIBody.TYPE_REVOCATION_REQ, content);
  return new PKIMessage(header, body);
}