Implement DER encoding for BOOLEAN, INTEGER and UTF8String in Client

This commit is contained in:
2025-02-23 16:06:09 +00:00
parent 31712d5efa
commit 4b22bd726f
5 changed files with 195 additions and 0 deletions

90
client/src/der.vala Normal file
View File

@@ -0,0 +1,90 @@
namespace StudySystemClient.Der {
public abstract class Datum {
internal uint8 type;
internal uint8[] content;
public uint8[] encode() {
var buffer = new ByteArray();
buffer.append({type});
if (content.length >= 0x80) {
var length_bytes = encode_length(content.length);
buffer.append({0x80 | (uint8)length_bytes.length});
buffer.append(length_bytes);
} else {
buffer.append({(uint8)content.length});
}
buffer.append(content);
return buffer.data;
}
private static uint8[] encode_length(uint length) {
var buffer = new ByteArray();
int shift = 0;
while (length >> (shift + 8) != 0)
shift += 8;
for (; shift >= 0; shift -= 8)
buffer.append({(uint8)(length >> shift)});
return buffer.data;
}
}
public class Boolean : Datum {
internal const uint8 TYPE = 0x01;
public Boolean(bool val) {
type = TYPE;
content = new uint8[] { val ? 0xff : 0x00 };
}
}
public class Integer : Datum {
internal const uint8 TYPE = 0x02;
public Integer(int64 val) {
type = TYPE;
content = encode_int64(val);
}
private static uint64 twos_complement(uint64 x) {
return ~x + 1;
}
private static int min_bits(bool negative, uint64 x) {
int n = 0;
if (negative) {
while ((x >> (n + 8) & 0xff) != 0xff)
n += 8;
} else {
while (x >> (n + 8) > 0)
n += 8;
}
return n;
}
private static uint8[] encode_int64(int64 val) {
var negative = val < 0;
var uval = negative ? twos_complement(val.abs()) : val;
var shift = min_bits(negative, uval);
var buffer = new ByteArray();
for (; shift >= 0; shift -= 8)
buffer.append({(uint8)(uval >> shift)});
if (!negative && (buffer.data[0] & 0x80) != 0)
buffer.prepend({0x00});
return buffer.data;
}
}
public class Utf8String : Datum {
internal const uint8 TYPE = 0x0c;
public Utf8String(string val) {
type = TYPE;
content = val.data;
}
}
}

View File

@@ -11,6 +11,7 @@ lib = library(
'study-system-client',
sources: files(
'connection.vala',
'der.vala',
'main_window.vala',
),
dependencies: [gtk_dep],