Debian Codegraph @

xmpp-vala/src/module/xep/0300_cryptographic_hashes.vala

raw
1 using GLib;
2 using Gee;
3
4 namespace Xmpp.Xep.CryptographicHashes {
5 public const string NS_URI = "urn:xmpp:hashes:2";
6
7 public Gee.List<Hash> get_hashes(StanzaNode node) {
8 var hashes = new ArrayList<Hash>();
9 foreach (StanzaNode hash_node in node.get_subnodes("hash", NS_URI)) {
10 hashes.add(new Hash.from_stanza_node(hash_node));
11 }
12 return hashes;
13 }
14
15 public Gee.List<Hash> get_supported_hashes(Gee.List<Hash> hashes) {
16 var ret = new ArrayList<Hash>();
17 foreach (Hash hash in hashes) {
18 ChecksumType? hash_type = hash_string_to_type(hash.algo);
19 if (hash_type != null) {
20 ret.add(hash);
21 }
22 }
23 return ret;
24 }
25
26 public bool has_supported_hashes(Gee.List<Hash> hashes) {
27 foreach (Hash hash in hashes) {
28 ChecksumType? hash_type = hash_string_to_type(hash.algo);
29 if (hash_type != null) return true;
30 }
31 return false;
32 }
33
34 public class Hash : Object {
35 public string algo;
36 // hash encoded in Base64
37 public string val;
38
39 public Hash.with_checksum(ChecksumType checksum_type, string hash) {
40 algo = hash_type_to_string(checksum_type);
41 val = hash;
42 }
43
44 public Hash.compute(GLib.ChecksumType type, uint8[] data) {
45 GLib.Checksum checksum = new GLib.Checksum(type);
46 checksum.update(data, data.length);
47 // 64 * 8 = 512 (sha-512 is the longest hash variant)
48 uint8[] digest = new uint8[64];
49 size_t length = digest.length;
50 checksum.get_digest(digest, ref length);
51 this.algo = hash_type_to_string(type);
52 this.val = GLib.Base64.encode(digest[0:length]);
53 }
54
55 public StanzaNode to_stanza_node() {
56 return new StanzaNode.build("hash", NS_URI).add_self_xmlns()
57 .put_attribute("algo", this.algo)
58 .put_node(new StanzaNode.text(this.val));
59 }
60
61 public Hash.from_stanza_node(StanzaNode node) {
62 this.algo = node.get_attribute("algo");
63 this.val = node.get_string_content();
64 }
65 }
66
67 public static string hash_type_to_string(ChecksumType type) {
68 switch(type) {
69 case ChecksumType.MD5:
70 return "md5";
71 case ChecksumType.SHA1:
72 return "sha-1";
73 case ChecksumType.SHA256:
74 return "sha-256";
75 case ChecksumType.SHA384:
76 return "sha-384";
77 case ChecksumType.SHA512:
78 return "sha-512";
79 }
80 return "(null)";
81 }
82
83 public static ChecksumType? hash_string_to_type(string hash) {
84 switch (hash) {
85 case "sha-1":
86 return ChecksumType.SHA1;
87 case "sha-256":
88 return ChecksumType.SHA256;
89 case "sha-384":
90 return ChecksumType.SHA384;
91 case "sha-512":
92 return ChecksumType.SHA512;
93 }
94 return null;
95 }
96 }