use of org.bouncycastle.asn1.ASN1UTF8String in project LinLong-Java by zhenwei1108.
the class OEROutputStream method write.
public void write(ASN1Encodable encodable, OERDefinition.Element oerElement) throws IOException {
if (encodable == OEROptional.ABSENT) {
return;
} else if (encodable instanceof OEROptional) {
write(((OEROptional) encodable).get(), oerElement);
return;
}
encodable = encodable.toASN1Primitive();
switch(oerElement.baseType) {
case SEQ:
{
ASN1Sequence seq = ASN1Sequence.getInstance(encodable);
// build mask.
int j = 7;
int mask = 0;
if (oerElement.extensionsInDefinition) {
if (oerElement.hasPopulatedExtension()) {
mask |= bits[j];
}
j--;
}
for (int t = 0; t < oerElement.children.size(); t++) {
OERDefinition.Element childOERDescription = oerElement.children.get(t);
if (j < 0) {
out.write(mask);
j = 7;
mask = 0;
}
ASN1Encodable asn1EncodableChild = seq.getObjectAt(t);
if (childOERDescription.explicit && asn1EncodableChild instanceof OEROptional) {
// TODO call stack like definition error.
throw new IllegalStateException("absent sequence element that is required by oer definition");
}
if (!childOERDescription.explicit) {
ASN1Encodable obj = seq.getObjectAt(t);
if (childOERDescription.getDefaultValue() != null) {
if (obj instanceof OEROptional) {
if (((OEROptional) obj).isDefined()) {
if (!((OEROptional) obj).get().equals(childOERDescription.defaultValue)) {
mask |= bits[j];
}
}
} else {
if (!childOERDescription.getDefaultValue().equals(obj)) {
mask |= bits[j];
}
}
} else {
if (asn1EncodableChild != OEROptional.ABSENT) {
mask |= bits[j];
}
}
j--;
}
}
if (j != 7) {
out.write(mask);
}
//
for (int t = 0; t < oerElement.children.size(); t++) {
ASN1Encodable child = seq.getObjectAt(t);
OERDefinition.Element childOERElement = oerElement.children.get(t);
if (childOERElement.getDefaultValue() != null) {
if (childOERElement.getDefaultValue().equals(child)) {
continue;
}
}
write(child, childOERElement);
}
out.flush();
debugPrint(oerElement.appendLabel(""));
}
break;
case SEQ_OF:
//
// Assume this comes in as a sequence.
//
Enumeration e;
if (encodable instanceof ASN1Set) {
e = ((ASN1Set) encodable).getObjects();
encodeQuantity(((ASN1Set) encodable).size());
} else if (encodable instanceof ASN1Sequence) {
e = ((ASN1Sequence) encodable).getObjects();
encodeQuantity(((ASN1Sequence) encodable).size());
} else {
throw new IllegalStateException("encodable at for SEQ_OF is not a container");
}
while (e.hasMoreElements()) {
Object o = e.nextElement();
write((ASN1Encodable) o, oerElement.getFirstChid());
}
out.flush();
debugPrint(oerElement.appendLabel(""));
break;
case CHOICE:
{
ASN1Primitive item = encodable.toASN1Primitive();
BitBuilder bb = new BitBuilder();
int tag;
if (item instanceof ASN1ApplicationSpecific) {
//
// Application specific tag prefix.
//
tag = ((ASN1ApplicationSpecific) item).getApplicationTag();
bb.writeBit(0).writeBit(1);
item = ((ASN1ApplicationSpecific) item).getEnclosedObject();
} else if (item instanceof ASN1TaggedObject) {
ASN1TaggedObject taggedObject = (ASN1TaggedObject) item;
//
// Tag prefix.
//
int tagClass = taggedObject.getTagClass();
bb.writeBit(tagClass & BERTags.CONTEXT_SPECIFIC).writeBit(tagClass & BERTags.APPLICATION);
tag = taggedObject.getTagNo();
item = taggedObject.getBaseObject().toASN1Primitive();
} else {
throw new IllegalStateException("only support tagged objects");
}
// Small tag value encode in remaining bits
if (tag <= 63) {
bb.writeBits(tag, 6);
} else {
// Large tag value variant.
bb.writeBits(0xFF, 6);
// Encode as 7bit bytes where MSB indicated continuing byte.
bb.write7BitBytes(tag);
}
if (debugOutput != null) {
if (item instanceof ASN1ApplicationSpecific) {
debugPrint(oerElement.appendLabel("AS"));
} else if (item instanceof ASN1TaggedObject) {
debugPrint(oerElement.appendLabel("CS"));
}
}
// Save the header.
bb.writeAndClear(out);
write(item, oerElement.children.get(tag));
out.flush();
break;
}
case ENUM:
{
BigInteger ordinal;
if (encodable instanceof ASN1Integer) {
ordinal = ASN1Integer.getInstance(encodable).getValue();
} else {
ordinal = ASN1Enumerated.getInstance(encodable).getValue();
}
for (Iterator it = oerElement.children.iterator(); it.hasNext(); ) {
OERDefinition.Element child = (OERDefinition.Element) it.next();
//
if (child.enumValue.equals(ordinal)) {
if (ordinal.compareTo(BigInteger.valueOf(127)) > 0) {
// Note 2 Section 11.4 of T-REC-X.696-201508-I!!PDF-E.pdf
byte[] val = ordinal.toByteArray();
int l = 0x80 | (val.length & 0xFF);
out.write(l);
out.write(val);
} else {
out.write(ordinal.intValue() & 0x7F);
}
out.flush();
debugPrint(oerElement.appendLabel(oerElement.rangeExpression()));
return;
}
}
throw new IllegalArgumentException("enum value " + ordinal + " " + Hex.toHexString(ordinal.toByteArray()) + " no in defined child list");
}
case INT:
{
ASN1Integer integer = ASN1Integer.getInstance(encodable);
// >0 = positive and <0 = negative
int intBytesForRange = oerElement.intBytesForRange();
if (intBytesForRange > 0) {
//
// For unsigned fixed length 1,2,4,8 byte integers.
//
byte[] encoded = BigIntegers.asUnsignedByteArray(intBytesForRange, integer.getValue());
switch(intBytesForRange) {
case 1:
case 2:
case 4:
case 8:
out.write(encoded);
break;
default:
throw new IllegalStateException("unknown uint length " + intBytesForRange);
}
} else if (intBytesForRange < 0) {
//
// For twos compliment numbers of 1,2,4,8 bytes in encoded length.
//
byte[] encoded;
BigInteger number = integer.getValue();
switch(intBytesForRange) {
case -1:
encoded = new byte[] { BigIntegers.byteValueExact(number) };
break;
case -2:
encoded = Pack.shortToBigEndian(BigIntegers.shortValueExact(number));
break;
case -4:
encoded = Pack.intToBigEndian(BigIntegers.intValueExact(number));
break;
case -8:
encoded = Pack.longToBigEndian(BigIntegers.longValueExact(number));
break;
default:
throw new IllegalStateException("unknown twos compliment length");
}
out.write(encoded);
} else {
// Unbounded at one or both ends and needs length encoding.
byte[] encoded;
if (oerElement.isLowerRangeZero()) {
// Since we have already captured the fixed with unsigned ints.
// Everything is assumed unbounded we need to encode a length and write the value.
encoded = BigIntegers.asUnsignedByteArray(integer.getValue());
} else {
// Twos complement
encoded = integer.getValue().toByteArray();
}
// Deals with long and short forms.
encodeLength(encoded.length);
out.write(encoded);
}
debugPrint(oerElement.appendLabel(oerElement.rangeExpression()));
out.flush();
}
break;
case OCTET_STRING:
{
ASN1OctetString octets = ASN1OctetString.getInstance(encodable);
byte[] bytes = octets.getOctets();
if (oerElement.isFixedLength()) {
out.write(bytes);
} else {
encodeLength(bytes.length);
out.write(bytes);
}
debugPrint(oerElement.appendLabel(oerElement.rangeExpression()));
out.flush();
break;
}
case UTF8_STRING:
{
ASN1UTF8String utf8 = ASN1UTF8String.getInstance(encodable);
byte[] encoded = Strings.toUTF8ByteArray(utf8.getString());
encodeLength(encoded.length);
out.write(encoded);
debugPrint(oerElement.appendLabel(""));
out.flush();
break;
}
case BIT_STRING:
{
DERBitString bitString = DERBitString.getInstance(encodable);
byte[] bytes = bitString.getBytes();
if (oerElement.isFixedLength()) {
out.write(bytes);
debugPrint(oerElement.appendLabel(oerElement.rangeExpression()));
} else {
int padBits = bitString.getPadBits();
// 13.3.1
encodeLength(bytes.length + 1);
// 13.3.2
out.write(padBits);
// 13.3.3
out.write(bytes);
debugPrint(oerElement.appendLabel(oerElement.rangeExpression()));
}
out.flush();
}
break;
case NULL:
// Does not encode in OER.
break;
case EXTENSION:
{
ASN1OctetString octets = ASN1OctetString.getInstance(encodable);
byte[] bytes = octets.getOctets();
if (oerElement.isFixedLength()) {
out.write(bytes);
} else {
encodeLength(bytes.length);
out.write(bytes);
}
debugPrint(oerElement.appendLabel(oerElement.rangeExpression()));
out.flush();
break;
}
case ENUM_ITEM:
// Used to define options does not encode.
break;
case BOOLEAN:
debugPrint(oerElement.label);
ASN1Boolean asn1Boolean = ASN1Boolean.getInstance(encodable);
if (asn1Boolean.isTrue()) {
out.write(255);
} else {
out.write(0);
}
out.flush();
}
}
use of org.bouncycastle.asn1.ASN1UTF8String in project openkeystore by cyberphone.
the class RelativeDistinguishedName method add.
private void add(String nameOrOID, String value) throws IOException {
if (nameOrOID.indexOf('.') < 0) {
String t = name2OID(nameOrOID);
if (t == null) {
StringBuilder s = new StringBuilder();
s.append("Unknown attribute '").append(nameOrOID).append("', select among the following:");
Enumeration<String> e = name2OID.keys();
while (e.hasMoreElements()) {
String key = e.nextElement();
s.append("\n ").append(key).append(" [").append(name2OID.get(key)).append("]");
}
throw new IOException(s.toString());
}
nameOrOID = t;
}
// e-mail and dc as IA5String, all others as Printable or UTF-8
// (if contatining non-printable characters).
add(nameOrOID, (nameOrOID.equals("1.2.840.113549.1.9.1") || nameOrOID.equals("0.9.2342.19200300.100.1.25")) ? (ASN1String) new ASN1IA5String(value) : ASN1PrintableString.isPrintableString(value) ? (ASN1String) new ASN1PrintableString(value) : (ASN1String) new ASN1UTF8String(value));
}
use of org.bouncycastle.asn1.ASN1UTF8String in project xipki by xipki.
the class DecodedPkiMessage method decode.
@SuppressWarnings("unchecked")
public static DecodedPkiMessage decode(CMSSignedData pkiMessage, EnvelopedDataDecryptor recipient, CollectionStore<X509CertificateHolder> certStore) throws MessageDecodingException {
Args.notNull(pkiMessage, "pkiMessage");
Args.notNull(recipient, "recipient");
SignerInformationStore signerStore = pkiMessage.getSignerInfos();
Collection<SignerInformation> signerInfos = signerStore.getSigners();
if (signerInfos.size() != 1) {
throw new MessageDecodingException("number of signerInfos is not 1, but " + signerInfos.size());
}
SignerInformation signerInfo = signerInfos.iterator().next();
SignerId sid = signerInfo.getSID();
Collection<?> signedDataCerts = null;
if (certStore != null) {
signedDataCerts = certStore.getMatches(sid);
}
if (CollectionUtil.isEmpty(signedDataCerts)) {
signedDataCerts = pkiMessage.getCertificates().getMatches(signerInfo.getSID());
}
if (signedDataCerts == null || signedDataCerts.size() != 1) {
throw new MessageDecodingException("could not find embedded certificate to verify the signature");
}
AttributeTable signedAttrs = signerInfo.getSignedAttributes();
if (signedAttrs == null) {
throw new MessageDecodingException("missing SCEP attributes");
}
Date signingTime = null;
// signingTime
ASN1Encodable attrValue = ScepUtil.getFirstAttrValue(signedAttrs, CMSAttributes.signingTime);
if (attrValue != null) {
signingTime = ScepUtil.getTime(attrValue);
}
// transactionId
String str = getPrintableStringAttrValue(signedAttrs, ScepObjectIdentifiers.ID_TRANSACTION_ID);
if (StringUtil.isBlank(str)) {
throw new MessageDecodingException("missing required SCEP attribute transactionId");
}
TransactionId transactionId = new TransactionId(str);
// messageType
Integer intValue = getIntegerPrintStringAttrValue(signedAttrs, ScepObjectIdentifiers.ID_MESSAGE_TYPE);
if (intValue == null) {
throw new MessageDecodingException("tid " + transactionId.getId() + ": missing required SCEP attribute messageType");
}
MessageType messageType;
try {
messageType = MessageType.forValue(intValue);
} catch (IllegalArgumentException ex) {
throw new MessageDecodingException("tid " + transactionId.getId() + ": invalid messageType '" + intValue + "'");
}
// senderNonce
Nonce senderNonce = getNonceAttrValue(signedAttrs, ScepObjectIdentifiers.ID_SENDER_NONCE);
if (senderNonce == null) {
throw new MessageDecodingException("tid " + transactionId.getId() + ": missing required SCEP attribute senderNonce");
}
DecodedPkiMessage ret = new DecodedPkiMessage(transactionId, messageType, senderNonce);
if (signingTime != null) {
ret.setSigningTime(signingTime);
}
Nonce recipientNonce = null;
try {
recipientNonce = getNonceAttrValue(signedAttrs, ScepObjectIdentifiers.ID_RECIPIENT_NONCE);
} catch (MessageDecodingException ex) {
ret.setFailureMessage("could not parse recipientNonce: " + ex.getMessage());
}
if (recipientNonce != null) {
ret.setRecipientNonce(recipientNonce);
}
PkiStatus pkiStatus = null;
FailInfo failInfo;
if (MessageType.CertRep == messageType) {
// pkiStatus
try {
intValue = getIntegerPrintStringAttrValue(signedAttrs, ScepObjectIdentifiers.ID_PKI_STATUS);
} catch (MessageDecodingException ex) {
ret.setFailureMessage("could not parse pkiStatus: " + ex.getMessage());
return ret;
}
if (intValue == null) {
ret.setFailureMessage("missing required SCEP attribute pkiStatus");
return ret;
}
try {
pkiStatus = PkiStatus.forValue(intValue);
} catch (IllegalArgumentException ex) {
ret.setFailureMessage("invalid pkiStatus '" + intValue + "'");
return ret;
}
ret.setPkiStatus(pkiStatus);
// failureInfo
if (pkiStatus == PkiStatus.FAILURE) {
try {
intValue = getIntegerPrintStringAttrValue(signedAttrs, ScepObjectIdentifiers.ID_FAILINFO);
} catch (MessageDecodingException ex) {
ret.setFailureMessage("could not parse failInfo: " + ex.getMessage());
return ret;
}
if (intValue == null) {
ret.setFailureMessage("missing required SCEP attribute failInfo");
return ret;
}
try {
failInfo = FailInfo.forValue(intValue);
} catch (IllegalArgumentException ex) {
ret.setFailureMessage("invalid failInfo '" + intValue + "'");
return ret;
}
ret.setFailInfo(failInfo);
// failInfoText
ASN1Encodable value = ScepUtil.getFirstAttrValue(signedAttrs, ScepObjectIdentifiers.ID_SCEP_FAILINFOTEXT);
if (value != null) {
if (value instanceof ASN1UTF8String) {
ret.setFailInfoText(((ASN1UTF8String) value).getString());
} else if (value != null) {
throw new MessageDecodingException("the value of attribute failInfoText " + " is not UTF8String");
}
}
}
// end if(pkiStatus == PkiStatus.FAILURE)
}
// end if (MessageType.CertRep == messageType)
// other signedAttributes
Attribute[] attrs = signedAttrs.toASN1Structure().getAttributes();
for (Attribute attr : attrs) {
ASN1ObjectIdentifier type = attr.getAttrType();
if (!SCEP_ATTR_TYPES.contains(type)) {
ret.addSignendAttribute(type, attr.getAttrValues().getObjectAt(0));
}
}
// unsignedAttributes
AttributeTable unsignedAttrs = signerInfo.getUnsignedAttributes();
attrs = (unsignedAttrs == null) ? null : unsignedAttrs.toASN1Structure().getAttributes();
if (attrs != null) {
for (Attribute attr : attrs) {
ASN1ObjectIdentifier type = attr.getAttrType();
ret.addUnsignendAttribute(type, attr.getAttrValues().getObjectAt(0));
}
}
try {
HashAlgo digestAlgo = HashAlgo.getInstance(signerInfo.getDigestAlgorithmID());
ret.setDigestAlgorithm(digestAlgo);
String sigAlgOid = signerInfo.getEncryptionAlgOID();
if (!PKCSObjectIdentifiers.rsaEncryption.getId().equals(sigAlgOid)) {
SignAlgo signAlgo = SignAlgo.getInstance(signerInfo.toASN1Structure().getDigestEncryptionAlgorithm());
if (digestAlgo != signAlgo.getHashAlgo()) {
ret.setFailureMessage("digestAlgorithm and encryptionAlgorithm do not use the same digestAlgorithm");
return ret;
}
}
} catch (NoSuchAlgorithmException ex) {
String msg = ex.getMessage();
LOG.error(msg);
LOG.debug(msg, ex);
ret.setFailureMessage(msg);
return ret;
}
X509CertificateHolder signerCert = (X509CertificateHolder) signedDataCerts.iterator().next();
ret.setSignatureCert(new X509Cert(signerCert));
// validate the signature
SignerInformationVerifier verifier;
try {
verifier = new JcaSimpleSignerInfoVerifierBuilder().build(signerCert);
} catch (OperatorCreationException | CertificateException ex) {
final String msg = "could not build signature verifier: " + ex.getMessage();
LOG.error(msg);
LOG.debug(msg, ex);
ret.setFailureMessage(msg);
return ret;
}
boolean signatureValid;
try {
signatureValid = signerInfo.verify(verifier);
} catch (CMSException ex) {
final String msg = "could not verify the signature: " + ex.getMessage();
LOG.error(msg);
LOG.debug(msg, ex);
ret.setFailureMessage(msg);
return ret;
}
ret.setSignatureValid(signatureValid);
if (!signatureValid) {
return ret;
}
if (MessageType.CertRep == messageType && (pkiStatus == PkiStatus.FAILURE | pkiStatus == PkiStatus.PENDING)) {
return ret;
}
// MessageData
CMSTypedData signedContent = pkiMessage.getSignedContent();
ASN1ObjectIdentifier signedContentType = signedContent.getContentType();
if (!CMSObjectIdentifiers.envelopedData.equals(signedContentType)) {
// fall back: some SCEP client, such as JSCEP use id-data
if (!CMSObjectIdentifiers.data.equals(signedContentType)) {
ret.setFailureMessage("either id-envelopedData or id-data is excepted, but not '" + signedContentType.getId());
return ret;
}
}
CMSEnvelopedData envData;
try {
envData = new CMSEnvelopedData((byte[]) signedContent.getContent());
} catch (CMSException ex) {
final String msg = "could not create the CMSEnvelopedData: " + ex.getMessage();
LOG.error(msg);
LOG.debug(msg, ex);
ret.setFailureMessage(msg);
return ret;
}
ret.setContentEncryptionAlgorithm(envData.getContentEncryptionAlgorithm().getAlgorithm());
byte[] encodedMessageData;
try {
encodedMessageData = recipient.decrypt(envData);
} catch (MessageDecodingException ex) {
final String msg = "could not create the CMSEnvelopedData: " + ex.getMessage();
LOG.error(msg);
LOG.debug(msg, ex);
ret.setFailureMessage(msg);
ret.setDecryptionSuccessful(false);
return ret;
}
ret.setDecryptionSuccessful(true);
try {
if (MessageType.PKCSReq == messageType || MessageType.RenewalReq == messageType) {
CertificationRequest messageData = CertificationRequest.getInstance(encodedMessageData);
ret.setMessageData(messageData);
} else if (MessageType.CertPoll == messageType) {
IssuerAndSubject messageData = IssuerAndSubject.getInstance(encodedMessageData);
ret.setMessageData(messageData);
} else if (MessageType.GetCert == messageType || MessageType.GetCRL == messageType) {
IssuerAndSerialNumber messageData = IssuerAndSerialNumber.getInstance(encodedMessageData);
ret.setMessageData(messageData);
ret.setMessageData(messageData);
} else if (MessageType.CertRep == messageType) {
ContentInfo ci = ContentInfo.getInstance(encodedMessageData);
ret.setMessageData(ci);
} else {
throw new RuntimeException("should not reach here, unknown messageType " + messageType);
}
} catch (Exception ex) {
final String msg = "could not parse the messageData: " + ex.getMessage();
LOG.error(msg);
LOG.debug(msg, ex);
ret.setFailureMessage(msg);
return ret;
}
return ret;
}
use of org.bouncycastle.asn1.ASN1UTF8String in project LinLong-Java by zhenwei1108.
the class CMSTimeStampedGenerator method setMetaData.
/**
* Set the MetaData for the generated message.
*
* @param hashProtected true if the MetaData should be included in first imprint calculation,
* false otherwise.
* @param fileName optional file name, may be null.
* @param mediaType optional media type, may be null.
* @param attributes optional attributes, may be null.
*/
public void setMetaData(boolean hashProtected, String fileName, String mediaType, Attributes attributes) {
ASN1UTF8String asn1FileName = null;
if (fileName != null) {
asn1FileName = new DERUTF8String(fileName);
}
ASN1IA5String asn1MediaType = null;
if (mediaType != null) {
asn1MediaType = new DERIA5String(mediaType);
}
setMetaData(hashProtected, asn1FileName, asn1MediaType, attributes);
}
Aggregations