org.bouncycastle.asn1.DERPrintableString Java Examples

The following examples show how to use org.bouncycastle.asn1.DERPrintableString. 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: 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 #2
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 #3
Source File: DialogHelper.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
private static void populateTextField(Attribute[] attrs, JTextField textField, ASN1ObjectIdentifier pkcs9Attr) {
	if (attrs != null) {
		for (Attribute attribute : attrs) {

			ASN1ObjectIdentifier attributeOid = attribute.getAttrType();

			if (attributeOid.equals(pkcs9Attr)) {
				ASN1Encodable challenge = attribute.getAttributeValues()[0];

				// data type can be one of IA5String or UTF8String
				if (challenge instanceof DERPrintableString) {
					textField.setText(((DERPrintableString) challenge).getString());
				} else if (challenge instanceof DERUTF8String) {
					textField.setText(((DERUTF8String) challenge).getString());
				}
				textField.setCaretPosition(0);
			}
		}
	}
}
 
Example #4
Source File: Asn1Dump.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
private String dumpString(ASN1String asn1String) {
	StringBuilder sb = new StringBuilder();

	sb.append(indentSequence.toString(indentLevel));

	if (asn1String instanceof DERBMPString) {
		sb.append("BMP STRING=");
	} else if (asn1String instanceof DERGeneralString) {
		sb.append("GENERAL STRING=");
	} else if (asn1String instanceof DERIA5String) {
		sb.append("IA5 STRING=");
	} else if (asn1String instanceof DERNumericString) {
		sb.append("NUMERIC STRING=");
	} else if (asn1String instanceof DERPrintableString) {
		sb.append("PRINTABLE STRING=");
	} else if (asn1String instanceof DERT61String) {
		sb.append("TELETEX STRING=");
	} else if (asn1String instanceof DERUniversalString) {
		sb.append("UNIVERSAL STRING=");
	} else if (asn1String instanceof DERUTF8String) {
		sb.append("UTF8 STRING=");
	} else if (asn1String instanceof DERVisibleString) {
		sb.append("VISIBLE STRING=");
	} else {
		sb.append("UNKNOWN STRING=");
	}

	sb.append("'");
	sb.append(asn1String.getString());
	sb.append("'");
	sb.append(NEWLINE);

	return sb.toString();
}
 
Example #5
Source File: CertStore.java    From xipki with Apache License 2.0 5 votes vote down vote up
public String getLatestSerialNumber(X500Name nameWithSn) throws OperationException {
  RDN[] rdns1 = nameWithSn.getRDNs();
  RDN[] rdns2 = new RDN[rdns1.length];
  for (int i = 0; i < rdns1.length; i++) {
    RDN rdn = rdns1[i];
    rdns2[i] =  rdn.getFirst().getType().equals(ObjectIdentifiers.DN.serialNumber)
        ? new RDN(ObjectIdentifiers.DN.serialNumber, new DERPrintableString("%")) : rdn;
  }

  String namePattern = X509Util.getRfc4519Name(new X500Name(rdns2));

  final String sql = sqlLatestSerialForSubjectLike;
  ResultSet rs = null;
  PreparedStatement ps = borrowPreparedStatement(sql);

  String subjectStr;

  try {
    ps.setString(1, namePattern);
    rs = ps.executeQuery();
    if (!rs.next()) {
      return null;
    }

    subjectStr = rs.getString("SUBJECT");
  } catch (SQLException ex) {
    throw new OperationException(DATABASE_FAILURE, ex.getMessage());
  } finally {
    datasource.releaseResources(ps, rs);
  }

  X500Name lastName = new X500Name(subjectStr);
  RDN[] rdns = lastName.getRDNs(ObjectIdentifiers.DN.serialNumber);
  if (rdns == null || rdns.length == 0) {
    return null;
  }

  return X509Util.rdnValueToString(rdns[0].getFirst().getValue());
}
 
Example #6
Source File: MyUtil.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static PKCS10CertificationRequest generateRequest(PrivateKey privatekey,
    SubjectPublicKeyInfo subjectPublicKeyInfo, X500Name subjectDn,
    String challengePassword, List<Extension> extensions)
    throws OperatorCreationException {
  Args.notNull(privatekey, "privatekey");
  Args.notNull(subjectPublicKeyInfo, "subjectPublicKeyInfo");
  Args.notNull(subjectDn, "subjectDn");

  Map<ASN1ObjectIdentifier, ASN1Encodable> attributes =
      new HashMap<ASN1ObjectIdentifier, ASN1Encodable>();

  if (StringUtil.isNotBlank(challengePassword)) {
    DERPrintableString asn1Pwd = new DERPrintableString(challengePassword);
    attributes.put(PKCSObjectIdentifiers.pkcs_9_at_challengePassword, asn1Pwd);
  }

  if (CollectionUtil.isNotEmpty(extensions)) {
    Extensions asn1Extensions = new Extensions(extensions.toArray(new Extension[0]));
    attributes.put(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, asn1Extensions);
  }

  PKCS10CertificationRequestBuilder csrBuilder =
      new PKCS10CertificationRequestBuilder(subjectDn, subjectPublicKeyInfo);

  if (attributes != null) {
    for (ASN1ObjectIdentifier attrType : attributes.keySet()) {
      csrBuilder.addAttribute(attrType, attributes.get(attrType));
    }
  }

  ContentSigner contentSigner = new JcaContentSignerBuilder(
      ScepUtil.getSignatureAlgorithm(privatekey, HashAlgo.SHA1)).build(privatekey);
  return csrBuilder.build(contentSigner);
}
 
Example #7
Source File: PkiMessage.java    From xipki with Apache License 2.0 5 votes vote down vote up
private AttributeTable getSignedAttributes() {
  ASN1EncodableVector vec = new ASN1EncodableVector();
  // messageType
  addAttribute(vec, ScepObjectIdentifiers.ID_MESSAGE_TYPE,
      new DERPrintableString(Integer.toString(messageType.getCode())));

  // senderNonce
  addAttribute(vec, ScepObjectIdentifiers.ID_SENDER_NONCE,
      new DEROctetString(senderNonce.getBytes()));

  // transactionID
  addAttribute(vec, ScepObjectIdentifiers.ID_TRANSACTION_ID,
      new DERPrintableString(transactionId.getId()));

  // failInfo
  if (failInfo != null) {
    addAttribute(vec, ScepObjectIdentifiers.ID_FAILINFO,
        new DERPrintableString(Integer.toString(failInfo.getCode())));
  }

  // pkiStatus
  if (pkiStatus != null) {
    addAttribute(vec, ScepObjectIdentifiers.ID_PKI_STATUS,
        new DERPrintableString(Integer.toString(pkiStatus.getCode())));
  }

  // recipientNonce
  if (recipientNonce != null) {
    addAttribute(vec, ScepObjectIdentifiers.ID_RECIPIENT_NONCE,
        new DEROctetString(recipientNonce.getBytes()));
  }

  for (ASN1ObjectIdentifier type : signedAttributes.keySet()) {
    addAttribute(vec, type, signedAttributes.get(type));
  }
  return new AttributeTable(vec);
}
 
Example #8
Source File: DecodedPkiMessage.java    From xipki with Apache License 2.0 5 votes vote down vote up
private static String getPrintableStringAttrValue(AttributeTable attrs,
    ASN1ObjectIdentifier type) throws MessageDecodingException {
  ASN1Encodable value = ScepUtil.getFirstAttrValue(attrs, type);
  if (value instanceof DERPrintableString) {
    return ((DERPrintableString) value).getString();
  } else if (value != null) {
    throw new MessageDecodingException("the value of attribute " + type.getId()
      + " is not PrintableString");
  } else {
    return null;
  }
}
 
Example #9
Source File: CaClientExample.java    From xipki with Apache License 2.0 5 votes vote down vote up
protected static CertificationRequest genCsr(MyKeypair keypair, String subject,
    String challengePassword) throws GeneralSecurityException, OperatorCreationException {
  X500Name subjectDn = new X500Name(subject);

  PKCS10CertificationRequestBuilder csrBuilder = new PKCS10CertificationRequestBuilder(
      subjectDn, keypair.publicKeyInfo);

  if (challengePassword != null && !challengePassword.isEmpty()) {
    csrBuilder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_challengePassword,
        new DERPrintableString(challengePassword));
  }

  ContentSigner signer = buildSigner(keypair.privateKey, "SHA256");
  return csrBuilder.build(signer).toASN1Structure();
}
 
Example #10
Source File: CaClientExample.java    From xipki with Apache License 2.0 5 votes vote down vote up
protected static CertificationRequest genCsr(MyKeypair keypair, String subject,
    String challengePassword) throws GeneralSecurityException, OperatorCreationException {
  X500Name subjectDn = new X500Name(subject);

  PKCS10CertificationRequestBuilder csrBuilder = new PKCS10CertificationRequestBuilder(
      subjectDn, keypair.publicKeyInfo);

  if (challengePassword != null && !challengePassword.isEmpty()) {
    csrBuilder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_challengePassword,
        new DERPrintableString(challengePassword));
  }

  ContentSigner signer = buildSigner(keypair.privateKey, "SHA256");
  return csrBuilder.build(signer).toASN1Structure();
}
 
Example #11
Source File: SignedAssertion.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private SignedAssertion(ASN1Sequence seq) {
    if (seq.size() != 2) {
        throw new IllegalArgumentException("Bad sequence size: "
                + seq.size());
    }
    this.assertion = DERPrintableString.getInstance(seq.getObjectAt(1));
}
 
Example #12
Source File: DistinguishedName.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private static String convertToString(byte[] value) {
   try {
      ASN1Primitive content = ASN1Primitive.fromByteArray(value);
      if (content instanceof DERPrintableString) {
         return ((DERPrintableString)content).getString();
      }

      LOG.error("Unsupported ASN1Object :" + content.getClass());
   } catch (Exception var2) {
      LOG.error("Error while converting to String", var2);
   }

   return null;
}
 
Example #13
Source File: X509Ext.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
private String getAttributeValueString(ASN1ObjectIdentifier attributeType, ASN1Encodable attributeValue)
		throws IOException {

	/* AttributeValue ::= ANY  */

	// Get value string for recognized attribute types
	AttributeTypeType attributeTypeType = AttributeTypeType.resolveOid(attributeType.getId());

	switch (attributeTypeType) {
	case DATE_OF_BIRTH:
		return getGeneralizedTimeString(ASN1GeneralizedTime.getInstance(attributeValue));
	case SERIAL_NUMBER:
	case UNSTRUCTURED_ADDRESS:
	case COUNTRY_NAME:
	case GENDER:
	case COUNTRY_OF_CITIZENSHIP:
	case COUNTRY_OF_RESIDENCE:
		return DERPrintableString.getInstance(attributeValue).getString();
	case COMMON_NAME:
	case LOCALITY_NAME:
	case STATE_NAME:
	case STREET_ADDRESS:
	case ORGANIZATION_NAME:
	case ORGANIZATIONAL_UNIT:
	case TITLE:
	case USER_ID:
	case PLACE_OF_BIRTH:
		return DirectoryString.getInstance(attributeValue).getString();
	case MAIL:
	case EMAIL_ADDRESS:
	case UNSTRUCTURED_NAME:
	case DOMAIN_COMPONENT:
		return DERIA5String.getInstance(attributeValue).getString();
	default:
		// Attribute type not recognized - return hex string for value
		return HexUtil.getHexString(attributeValue.toASN1Primitive().getEncoded());
	}
}
 
Example #14
Source File: DistinguishedName.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private static String convertToString(byte[] value) {
   try {
      ASN1Primitive content = ASN1Primitive.fromByteArray(value);
      if (content instanceof DERPrintableString) {
         return ((DERPrintableString)content).getString();
      }

      LOG.error("Unsupported ASN1Object :" + content.getClass());
   } catch (Exception var2) {
      LOG.error("Error while converting to String", var2);
   }

   return null;
}
 
Example #15
Source File: CertificateParser.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private String convertToString(byte[] value) {
   try {
      ASN1Primitive content = ASN1Primitive.fromByteArray(value);
      if (content instanceof DERPrintableString) {
         return ((DERPrintableString)content).getString();
      }

      LOG.error("Unsupported ASN1Object :" + content.getClass());
   } catch (Exception var3) {
      LOG.error("Error while converting to String", var3);
   }

   return "";
}
 
Example #16
Source File: CertificateParser.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private String convertToString(byte[] value) {
   try {
      ASN1Primitive content = ASN1Primitive.fromByteArray(value);
      if (content instanceof DERPrintableString) {
         return ((DERPrintableString)content).getString();
      }

      LOG.error("Unsupported ASN1Object :" + content.getClass());
   } catch (Exception var3) {
      LOG.error("Error while converting to String", var3);
   }

   return "";
}
 
Example #17
Source File: DistinguishedName.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private static String convertToString(byte[] value) {
   try {
      ASN1Primitive content = ASN1Primitive.fromByteArray(value);
      if (content instanceof DERPrintableString) {
         return ((DERPrintableString)content).getString();
      }

      LOG.error("Unsupported ASN1Object :" + content.getClass());
   } catch (Exception var2) {
      LOG.error("Error while converting to String", var2);
   }

   return null;
}
 
Example #18
Source File: CertificateParser.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private String convertToString(byte[] value) {
   try {
      ASN1Primitive content = ASN1Primitive.fromByteArray(value);
      if (content instanceof DERPrintableString) {
         return ((DERPrintableString)content).getString();
      }

      LOG.error("Unsupported ASN1Object :" + content.getClass());
   } catch (Exception var3) {
      LOG.error("Error while converting to String", var3);
   }

   return "";
}
 
Example #19
Source File: DistinguishedName.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private static String convertToString(byte[] value) {
   try {
      ASN1Primitive content = ASN1Primitive.fromByteArray(value);
      if (content instanceof DERPrintableString) {
         return ((DERPrintableString)content).getString();
      }

      LOG.error("Unsupported ASN1Object :" + content.getClass());
   } catch (Exception var2) {
      LOG.error("Error while converting to String", var2);
   }

   return null;
}
 
Example #20
Source File: CertificateParser.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private String convertToString(byte[] value) {
   try {
      ASN1Primitive content = ASN1Primitive.fromByteArray(value);
      if (content instanceof DERPrintableString) {
         return ((DERPrintableString)content).getString();
      }

      LOG.error("Unsupported ASN1Object :" + content.getClass());
   } catch (Exception var3) {
      LOG.error("Error while converting to String", var3);
   }

   return "";
}
 
Example #21
Source File: DistinguishedName.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private static String convertToString(byte[] value) {
   try {
      ASN1Primitive content = ASN1Primitive.fromByteArray(value);
      if (content instanceof DERPrintableString) {
         return ((DERPrintableString)content).getString();
      }

      LOG.error("Unsupported ASN1Object :" + content.getClass());
   } catch (Exception var2) {
      LOG.error("Error while converting to String", var2);
   }

   return null;
}
 
Example #22
Source File: CertificateParser.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private String convertToString(byte[] value) {
   try {
      ASN1Primitive content = ASN1Primitive.fromByteArray(value);
      if (content instanceof DERPrintableString) {
         return ((DERPrintableString)content).getString();
      }

      LOG.error("Unsupported ASN1Object :" + content.getClass());
   } catch (Exception var3) {
      LOG.error("Error while converting to String", var3);
   }

   return "";
}
 
Example #23
Source File: X509Ext.java    From keystore-explorer with GNU General Public License v3.0 4 votes vote down vote up
private String getDeclarationOfMajorityStringValue(byte[] octets) {

		// @formatter:off

		/*
			DeclarationOfMajoritySyntax ::= CHOICE
			{
				notYoungerThan [0] IMPLICIT INTEGER,
				fullAgeAtCountry [1] IMPLICIT SEQUENCE {
					fullAge BOOLEAN DEFAULT TRUE,
					country PrintableString (SIZE(2))
				},
				dateOfBirth [2] IMPLICIT GeneralizedTime
			}
		 */

		// @formatter:on

		StringBuilder sb = new StringBuilder();

		DeclarationOfMajority declarationOfMajority = DeclarationOfMajority.getInstance(octets);
		int notYoungerThan = declarationOfMajority.notYoungerThan();
		ASN1Sequence fullAgeAtCountry = declarationOfMajority.fullAgeAtCountry();
		ASN1GeneralizedTime dateOfBirth = declarationOfMajority.getDateOfBirth();

		if (notYoungerThan != -1) {
			sb.append(MessageFormat.format(res.getString("DeclarationOfMajority.notYoungerThan"), notYoungerThan));
			sb.append(NEWLINE);
		}

		if (fullAgeAtCountry != null) {
			ASN1Boolean fullAge = ASN1Boolean.getInstance(fullAgeAtCountry.getObjectAt(0));
			DERPrintableString country = DERPrintableString.getInstance(fullAgeAtCountry.getObjectAt(1));

			sb.append(MessageFormat.format(res.getString("DeclarationOfMajority.fullAgeAtCountry"), country.toString(),
					fullAge.toString()));
			sb.append(NEWLINE);
		}

		if (dateOfBirth != null) {
			sb.append(MessageFormat.format(res.getString("DeclarationOfMajority.dateOfBirth"), dateOfBirth));
			sb.append(NEWLINE);
		}

		return sb.toString();
	}
 
Example #24
Source File: PolicyIssuerName.java    From signer with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void parse(ASN1Primitive primitive) {
    if (primitive instanceof DLSequence) {
        DLSequence sequence = (DLSequence) primitive;
        ASN1Encodable asn1Encodable = sequence.getObjectAt(0);
        if (asn1Encodable instanceof DERTaggedObject) {
            DERTaggedObject derTaggedObject = (DERTaggedObject) asn1Encodable;
            ASN1Primitive object = derTaggedObject.getObject();
            if (object instanceof DEROctetString) {
                OctetString octetString = new OctetString();
                octetString.parse(object);
                this.issuerName = octetString.getValueUTF8();
            } else if (object instanceof DERSequence) {
                DERSequence sequence2 = (DERSequence) object;
                for (int i = 0; i < sequence2.size(); i++) {
                    ASN1Encodable obj = sequence2.getObjectAt(i);
                    if (obj instanceof DERSet) {
                        DERSet set = (DERSet) obj;
                        ASN1Encodable object2 = set.getObjectAt(0);
                        if (object2 instanceof DERSequence) {
                            DERSequence sequence3 = (DERSequence) object2;
                            ObjectIdentifier objectIdendifier = new ObjectIdentifier();
                            objectIdendifier.parse(sequence3.getObjectAt(0).toASN1Primitive());
                            String name = null;
                            ASN1Encodable object3 = sequence3.getObjectAt(1);
                            if (object3 instanceof DERPrintableString) {
                                name = ((DERPrintableString) object3).getString();
                            } else if (object3 instanceof DERUTF8String) {
                                name = ((DERUTF8String) object3).getString();
                            } else {
                                System.out.println(policyMessagesBundle.getString("error.not.recognized.object",object3.getClass(),object3.toString()));
                            }
                            if (this.issuerNames == null) {
                                this.issuerNames = new HashMap<ObjectIdentifier, String>();
                            }
                            this.issuerNames.put(objectIdendifier, name);
                        }
                    }
                }
            }
        }
    }
}
 
Example #25
Source File: SignedAssertion.java    From dss with GNU Lesser General Public License v2.1 4 votes vote down vote up
public SignedAssertion(String assertion) {
    this.assertion = new DERPrintableString(assertion);
}
 
Example #26
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 #27
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 #28
Source File: ExtensionsChecker.java    From xipki with Apache License 2.0 4 votes vote down vote up
private void checkDirectoryString(ASN1ObjectIdentifier extnType,
    DirectoryStringType type, String text,
    StringBuilder failureMsg, byte[] extensionValue, Extensions requestedExtns,
    ExtensionControl extControl) {
  if (type == null) {
    checkConstantExtnValue(extnType, failureMsg, extensionValue, requestedExtns, extControl);
    return;
  }

  ASN1Primitive asn1;
  try {
    asn1 = ASN1Primitive.fromByteArray(extensionValue);
  } catch (IOException ex) {
    failureMsg.append("invalid syntax of extension value; ");
    return;
  }

  boolean correctStringType;

  switch (type) {
    case bmpString:
      correctStringType = (asn1 instanceof DERBMPString);
      break;
    case printableString:
      correctStringType = (asn1 instanceof DERPrintableString);
      break;
    case teletexString:
      correctStringType = (asn1 instanceof DERT61String);
      break;
    case utf8String:
      correctStringType = (asn1 instanceof DERUTF8String);
      break;
    default:
      throw new IllegalStateException("should not reach here, unknown DirectoryStringType "
          + type);
  } // end switch

  if (!correctStringType) {
    failureMsg.append("extension value is not of type DirectoryString.")
      .append(text).append("; ");
    return;
  }

  String extTextValue = ((ASN1String) asn1).getString();
  if (!text.equals(extTextValue)) {
    addViolation(failureMsg, "content", extTextValue, text);
  }
}