add @text attribute to octet-string if bytes are ASCII text v_0
authorFrantišek Kučera <franta-hg@frantovo.cz>
Thu, 22 Jul 2021 01:06:14 +0200
branchv_0
changeset 39 6ef41443211e
parent 38 44ee477875ec
child 40 85b6f13f1088
add @text attribute to octet-string if bytes are ASCII text
src/lib/GenericASN1ContentHandler.h
--- a/src/lib/GenericASN1ContentHandler.h	Thu Jul 22 00:47:47 2021 +0200
+++ b/src/lib/GenericASN1ContentHandler.h	Thu Jul 22 01:06:14 2021 +0200
@@ -60,6 +60,17 @@
 		return attributes;
 	}
 
+	/**
+	 * @param header
+	 * @param value an octet string
+	 * @return original value if octet string was a text string; otherwise an empty string
+	 */
+	const std::string getText(const Header& header, const std::string& value) {
+		// TODO: support also UTF-8
+		for (uint8_t b : value) if (b < 32 || b >= 127) return "";
+		return value;
+	}
+
 public:
 
 	void addHandler(std::shared_ptr<XMLContentHandler> handler) {
@@ -112,10 +123,17 @@
 	}
 
 	void writeOctetString(const Header& header, std::string value) override {
+		std::vector<std::string> attributes = getCommonAttributes(header,{"length", std::to_string(value.size())});
+		std::string text = getText(header, value);
+		if (text.size()) {
+			attributes.push_back("text");
+			attributes.push_back(text);
+		}
+
 		std::stringstream hex;
 		hex << std::hex << std::setfill('0');
 		for (uint8_t b : value) hex << std::setw(2) << (int) b;
-		handlers.writeStartElement("octet-string", getCommonAttributes(header,{"length", std::to_string(value.size())}));
+		handlers.writeStartElement("octet-string", attributes);
 		handlers.writeCharacters(hex.str());
 		handlers.writeEndElement();
 	}