Method: OpenSSL::PKey::DSA#initialize

Defined in:
ossl_pkey_dsa.c

#newObject #new(string[, pass]) ⇒ Object #new(size) ⇒ Object

Creates a new DSA instance by reading an existing key from string.

If called without arguments, creates a new instance with no key components set. They can be set individually by #set_pqg and #set_key.

If called with a String, tries to parse as DER or PEM encoding of a DSA key. See also OpenSSL::PKey.read which can parse keys of any kinds.

If called with a number, generates random parameters and a key pair. This form works as an alias of DSA.generate.

string

A String that contains a DER or PEM encoded key.

pass

A String that contains an optional password.

size

See DSA.generate.

Examples:

p OpenSSL::PKey::DSA.new(1024)
#=> #<OpenSSL::PKey::DSA:0x000055a8d6025bf0 oid=DSA>

p OpenSSL::PKey::DSA.new(File.read('dsa.pem'))
#=> #<OpenSSL::PKey::DSA:0x000055555d6b8110 oid=DSA>

p OpenSSL::PKey::DSA.new(File.read('dsa.pem'), 'mypassword')
#=> #<OpenSSL::PKey::DSA:0x0000556f973c40b8 oid=DSA>


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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'ossl_pkey_dsa.c', line 83

static VALUE
ossl_dsa_initialize(int argc, VALUE *argv, VALUE self)
{
    EVP_PKEY *pkey;
    DSA *dsa;
    BIO *in = NULL;
    VALUE arg, pass;
    int type;

    TypedData_Get_Struct(self, EVP_PKEY, &ossl_evp_pkey_type, pkey);
    if (pkey)
        rb_raise(rb_eTypeError, "pkey already initialized");

    /* The DSA.new(size, generator) form is handled by lib/openssl/pkey.rb */
    rb_scan_args(argc, argv, "02", &arg, &pass);
    if (argc == 0) {
        dsa = DSA_new();
        if (!dsa)
            ossl_raise(eDSAError, "DSA_new");
        goto legacy;
    }

    pass = ossl_pem_passwd_value(pass);
    arg = ossl_to_der_if_possible(arg);
    in = ossl_obj2bio(&arg);

    /* DER-encoded DSAPublicKey format isn't supported by the generic routine */
    dsa = (DSA *)PEM_ASN1_read_bio((d2i_of_void *)d2i_DSAPublicKey,
                                   PEM_STRING_DSA_PUBLIC,
                                   in, NULL, NULL, NULL);
    if (dsa)
        goto legacy;
    OSSL_BIO_reset(in);

    pkey = ossl_pkey_read_generic(in, pass);
    BIO_free(in);
    if (!pkey)
        ossl_raise(eDSAError, "Neither PUB key nor PRIV key");

    type = EVP_PKEY_base_id(pkey);
    if (type != EVP_PKEY_DSA) {
        EVP_PKEY_free(pkey);
        rb_raise(eDSAError, "incorrect pkey type: %s", OBJ_nid2sn(type));
    }
    RTYPEDDATA_DATA(self) = pkey;
    return self;

  legacy:
    BIO_free(in);
    pkey = EVP_PKEY_new();
    if (!pkey || EVP_PKEY_assign_DSA(pkey, dsa) != 1) {
        EVP_PKEY_free(pkey);
        DSA_free(dsa);
        ossl_raise(eDSAError, "EVP_PKEY_assign_DSA");
    }
    RTYPEDDATA_DATA(self) = pkey;
    return self;
}