Implement DER encoding for BOOLEAN, INTEGER and UTF8String in Client
This commit is contained in:
90
client/src/der.vala
Normal file
90
client/src/der.vala
Normal 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ lib = library(
|
||||
'study-system-client',
|
||||
sources: files(
|
||||
'connection.vala',
|
||||
'der.vala',
|
||||
'main_window.vala',
|
||||
),
|
||||
dependencies: [gtk_dep],
|
||||
|
||||
Reference in New Issue
Block a user