End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
OpenSSL::PKey::PKey#sign_raw
static VALUE
ossl_pkey_sign_raw(int argc, VALUE *argv, VALUE self)
{
EVP_PKEY *pkey;
VALUE digest, data, options, sig;
const EVP_MD *md = NULL;
EVP_PKEY_CTX *ctx;
size_t outlen;
int state;
GetPKey(self, pkey);
rb_scan_args(argc, argv, "21", &digest, &data, &options);
if (!NIL_P(digest))
md = ossl_evp_get_digestbyname(digest);
StringValue(data);
ctx = EVP_PKEY_CTX_new(pkey, /* engine */NULL);
if (!ctx)
ossl_raise(ePKeyError, "EVP_PKEY_CTX_new");
if (EVP_PKEY_sign_init(ctx) <= 0) {
EVP_PKEY_CTX_free(ctx);
ossl_raise(ePKeyError, "EVP_PKEY_sign_init");
}
if (md && EVP_PKEY_CTX_set_signature_md(ctx, md) <= 0) {
EVP_PKEY_CTX_free(ctx);
ossl_raise(ePKeyError, "EVP_PKEY_CTX_set_signature_md");
}
if (!NIL_P(options)) {
pkey_ctx_apply_options(ctx, options, &state);
if (state) {
EVP_PKEY_CTX_free(ctx);
rb_jump_tag(state);
}
}
if (EVP_PKEY_sign(ctx, NULL, &outlen, (unsigned char *)RSTRING_PTR(data),
RSTRING_LEN(data)) <= 0) {
EVP_PKEY_CTX_free(ctx);
ossl_raise(ePKeyError, "EVP_PKEY_sign");
}
if (outlen > LONG_MAX) {
EVP_PKEY_CTX_free(ctx);
rb_raise(ePKeyError, "signature would be too large");
}
sig = ossl_str_new(NULL, (long)outlen, &state);
if (state) {
EVP_PKEY_CTX_free(ctx);
rb_jump_tag(state);
}
if (EVP_PKEY_sign(ctx, (unsigned char *)RSTRING_PTR(sig), &outlen,
(unsigned char *)RSTRING_PTR(data),
RSTRING_LEN(data)) <= 0) {
EVP_PKEY_CTX_free(ctx);
ossl_raise(ePKeyError, "EVP_PKEY_sign");
}
EVP_PKEY_CTX_free(ctx);
rb_str_set_len(sig, outlen);
return sig;
}
Signs data using a private key pkey. Unlike sign, data will not be hashed by digest automatically.
See verify_raw for the verification operation.
Added in version 3.0. See also the man page EVP_PKEY_sign(3).
digest-
A
Stringthat represents the message digest algorithm name, ornilif thePKeytype requires no digest algorithm. Although this method will not hashdatawith it, this parameter may still be required depending on the signature algorithm. data-
A
String. The data to be signed. options-
A
Hashthat contains algorithm specific control operations to OpenSSL. See OpenSSL’s man page EVP_PKEY_CTX_ctrl_str(3) for details.
Example:
data = "Sign me!" hash = OpenSSL::Digest.digest("SHA256", data) pkey = OpenSSL::PKey.generate_key("RSA", rsa_keygen_bits: 2048) signopts = { rsa_padding_mode: "pss" } signature = pkey.sign_raw("SHA256", hash, signopts) # Creates a copy of the RSA key pkey, but without the private components pub_key = pkey.public_key puts pub_key.verify_raw("SHA256", signature, hash, signopts) # => true