Module: MTProto::Crypto::AES_IGE

Defined in:
ext/aes_ige/aes_ige.c

Class Method Summary collapse

Class Method Details

.decrypt_ige(ciphertext, key, iv) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'ext/aes_ige/aes_ige.c', line 52

static VALUE
aes_ige_decrypt(VALUE self, VALUE ciphertext, VALUE key, VALUE iv)
{
    Check_Type(ciphertext, T_STRING);
    Check_Type(key, T_STRING);
    Check_Type(iv, T_STRING);

    long ciphertext_len = RSTRING_LEN(ciphertext);
    long key_len = RSTRING_LEN(key);
    long iv_len = RSTRING_LEN(iv);

    if (key_len != 32) {
        rb_raise(rb_eArgError, "Key must be 32 bytes");
    }
    if (iv_len != 32) {
        rb_raise(rb_eArgError, "IV must be 32 bytes");
    }
    if (ciphertext_len % 16 != 0) {
        rb_raise(rb_eArgError, "Ciphertext length must be multiple of 16");
    }

    AES_KEY aes_key;
    int ret = AES_set_decrypt_key((unsigned char *)RSTRING_PTR(key), 256, &aes_key);
    if (ret != 0) {
        rb_raise(rb_eRuntimeError, "AES_set_decrypt_key failed");
    }

    VALUE plaintext = rb_str_new(NULL, ciphertext_len);
    unsigned char iv_copy[32];
    memcpy(iv_copy, RSTRING_PTR(iv), 32);

    AES_ige_encrypt(
        (unsigned char *)RSTRING_PTR(ciphertext),
        (unsigned char *)RSTRING_PTR(plaintext),
        ciphertext_len,
        &aes_key,
        iv_copy,
        AES_DECRYPT
    );

    return plaintext;
}

.encrypt_ige(plaintext, key, iv) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'ext/aes_ige/aes_ige.c', line 9

static VALUE
aes_ige_encrypt(VALUE self, VALUE plaintext, VALUE key, VALUE iv)
{
    Check_Type(plaintext, T_STRING);
    Check_Type(key, T_STRING);
    Check_Type(iv, T_STRING);

    long plaintext_len = RSTRING_LEN(plaintext);
    long key_len = RSTRING_LEN(key);
    long iv_len = RSTRING_LEN(iv);

    if (key_len != 32) {
        rb_raise(rb_eArgError, "Key must be 32 bytes");
    }
    if (iv_len != 32) {
        rb_raise(rb_eArgError, "IV must be 32 bytes");
    }
    if (plaintext_len % 16 != 0) {
        rb_raise(rb_eArgError, "Plaintext length must be multiple of 16");
    }

    AES_KEY aes_key;
    int ret = AES_set_encrypt_key((unsigned char *)RSTRING_PTR(key), 256, &aes_key);
    if (ret != 0) {
        rb_raise(rb_eRuntimeError, "AES_set_encrypt_key failed");
    }

    VALUE ciphertext = rb_str_new(NULL, plaintext_len);
    unsigned char iv_copy[32];
    memcpy(iv_copy, RSTRING_PTR(iv), 32);

    AES_ige_encrypt(
        (unsigned char *)RSTRING_PTR(plaintext),
        (unsigned char *)RSTRING_PTR(ciphertext),
        plaintext_len,
        &aes_key,
        iv_copy,
        AES_ENCRYPT
    );

    return ciphertext;
}