buildPlaintextCredential function
Builds a json-Object where every Attribute gets a value and salt from json-Object credential
.
E.g.
{
"type" : "NameAgeCredential",
"name" : "Max",
"age" : 20
}
becomes to
{
"id": "did:ethr:0x82734",
"type": ["HashedPlaintextCredential2021","NameAgeCredential"],
"hashAlg" : "keccak-256",
"name":
{
"value":"Max",
"salt":"dc0931a0-60c6-4bc8-a27d-b3fd13e62c63"
},
"age":
{
"value":20,
"salt":"3e9bacd3-aa74-42c1-9895-e490e3931a73"
}
}
where salt is a Version 4 UUID.
credential
could be a string or Map<String, dynamic> representing a valid json-Object.
Implementation
String buildPlaintextCredential(dynamic credential, String? holderDid,
{bool addHashAlg = true}) {
Map<String, dynamic> credMap = credentialToMap(credential);
Map<String, dynamic> finalCred = {};
if (credMap.containsKey('credentialSubject')) {
credMap = credMap['credentialSubject'];
}
if (credMap.containsKey('@context')) {
finalCred['@context'] = credMap['@context'];
credMap.remove('@context');
}
if (addHashAlg) {
List<String> types = [];
types.add('HashedPlaintextCredential2021');
if (credMap.containsKey('type') || credMap.containsKey('@type')) {
var value = credMap['type'];
credMap.remove('type');
if (value == null) {
value = credMap['@type'];
credMap.remove('@type');
}
if (value is String) {
if (!types.contains(value)) types.add(value);
} else if (value is List) {
for (var element in value) {
if (!types.contains(element)) types.add(element);
}
} else {
throw Exception('Unsupported datatype for type key');
}
finalCred['type'] = types;
}
}
if (holderDid != '') {
finalCred['id'] = holderDid;
}
if (addHashAlg) finalCred['hashAlg'] = 'keccak-256';
credMap.forEach((key, value) {
if (key == 'type' || key == '@type') {
finalCred[key] = value;
} else if (value is String || value is num || value is bool) {
finalCred[key] = _hashStringOrNum(value);
} else if (value is List) {
List<Map<String, dynamic>?> newValue = [];
for (var element in value) {
if (element is String || element is num || element is bool) {
newValue.add(_hashStringOrNum(element));
} else if (element is Map<String, dynamic>) {
newValue.add(jsonDecode(
buildPlaintextCredential(element, '', addHashAlg: false)));
} else {
throw Exception('unknown type with key $key');
}
}
finalCred[key] = newValue;
} else if (value is Map<String, dynamic>) {
finalCred[key] =
jsonDecode(buildPlaintextCredential(value, '', addHashAlg: false));
} else {
throw Exception('unknown datatype with key $key');
}
});
return jsonEncode(finalCred);
}