1
2
3
4
5
6
7
8
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
51
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
|
/*
* $Id$
* 'OpenSSL for Ruby' project
* Copyright (C) 2001 Michal Rokos <m.rokos@sh.cvut.cz>
* All rights reserved.
*/
/*
* This program is licenced under the same licence as Ruby.
* (See the file 'LICENCE'.)
*/
#include "ossl.h"
#include "ossl_pkey.h"
#define GetPKey(obj, pkeyp) {\
Data_Get_Struct(obj, ossl_pkey, pkeyp);\
if (!pkeyp->get_EVP_PKEY) rb_raise(ePKeyError, "not initialized!");\
}
/*
* Classes
*/
VALUE cPKey;
VALUE ePKeyError;
/*
* Struct
* see ossl_pkey.h
*/
/*
* Public
*/
VALUE ossl_pkey_new(EVP_PKEY *key)
{
if (!key)
rb_raise(ePKeyError, "Empty key!");
switch (key->type) {
case EVP_PKEY_RSA:
return ossl_rsa_new(key->pkey.rsa);
case EVP_PKEY_DSA:
return ossl_dsa_new(key->pkey.dsa);
}
/*
* Make it or not?
* EVP_PKEY_free(new_key);
*/
rb_raise(ePKeyError, "unsupported key type");
return Qnil;
}
VALUE ossl_pkey_new_from_file(VALUE v)
{
char *path;
FILE *fp;
EVP_PKEY *pkey;
VALUE obj;
path = RSTRING(v)->ptr;
if((fp = fopen(path, "r")) == NULL)
rb_raise(ePKeyError, "%s", strerror(errno));
pkey = PEM_read_PrivateKey(fp, NULL, NULL, NULL);
fclose(fp);
if(!pkey) rb_raise(ePKeyError, "%s", ossl_error());
obj = rb_ensure(ossl_pkey_new, (VALUE)pkey,
(VALUE(*)(VALUE))EVP_PKEY_free, (VALUE)pkey);
return obj;
}
EVP_PKEY *ossl_pkey_get_EVP_PKEY(VALUE obj)
{
ossl_pkey *pkeyp = NULL;
GetPKey(obj, pkeyp);
return pkeyp->get_EVP_PKEY(obj);
}
/*
* Private
*/
static VALUE ossl_pkey_s_new(int argc, VALUE *argv, VALUE klass)
{
ossl_pkey *pkeyp = NULL;
VALUE obj;
if (klass == cPKey)
rb_raise(rb_eNotImpError, "cannot do PKey.new - PKey is an abstract class");
return Qnil;
}
void Init_ossl_pkey(VALUE mPKey)
{
ePKeyError = rb_define_class_under(mPKey, "Error", rb_eStandardError);
cPKey = rb_define_class_under(mPKey, "ANY", rb_cObject);
rb_define_singleton_method(cPKey, "new", ossl_pkey_s_new, -1);
Init_ossl_rsa(mPKey, cPKey, ePKeyError);
Init_ossl_dsa(mPKey, cPKey, ePKeyError);
/*
* TODO:
* Init_ossl_dh(mPKey, cPKey, ePKeyError);
*/
}
|