views:

111

answers:

2

Hi, I have this code in C that use openssl library to calculate the SHA1 digest of a bignumber. How I can translate this code in Ruby?

#include <stdio.h>
#include <openssl/sha.h>
#include <openssl/bn.h>

int
main ()
{
    // Create a bignum = 3
    struct bignum_st *bn = BN_new ();
    BN_set_word (bn, 3);

    // Initialize SHA1 context
    unsigned char digest[SHA_DIGEST_LENGTH];
    SHA_CTX sha_ctx;
    SHA1_Init (&sha_ctx);

    // Calculate SHA1 digest (in binary) of bignum 3
    SHA1_Update (&sha_ctx, bn, BN_num_bytes (bn));
    SHA1_Final (digest, &sha_ctx);

    // Print HEX value of digest
    int i;
    for (i = 0; i < SHA_DIGEST_LENGTH; i++)
      printf ("%x", digest[i]);
    printf ("\n");

    // result is: 516b9783fca517eecbd1d064da2d165310b19759
}

Compile with: gcc sha1.c -lcrypto

Thx.

+1  A: 

Perhaps...?

require 'digest/sha1' sha1 = Digest::SHA1.hexdigest(big_int_var)

Isn't Ruby great :)
Wouter de Bie
A: 
require 'digest/sha1'
sha1 = Digest::SHA1.hexdigest(3)
TypeError: can't convert Fixnum into String

And I dont want digest of '3' but digest of 3...

Pioz
I don't think you can get what you want without writing a C extension to Ruby. You aren't looking for the digest of 3 (that would be `Digest::SHA1.hexdigest([3].pack("i"))`). You are looking for the digest of the bignum containing the value 3. I'm not sure how you can get that from Ruby.
cam
Yeah... im writing that extension :(
Pioz
Isn't C great :)
GregS