Add a basic test for BN_bn2dec.
[oweals/openssl.git] / test / bntest.c
index 804406c94d439f2142ab09a8ba41e36117c9d512..51b75d3ed08c9de1ffcbc1e643282d2c9ff1cddb 100644 (file)
@@ -83,6 +83,7 @@ int test_gf2m_mod_solve_quad(BIO *bp, BN_CTX *ctx);
 int test_kron(BIO *bp, BN_CTX *ctx);
 int test_sqrt(BIO *bp, BN_CTX *ctx);
 int test_small_prime(BIO *bp, BN_CTX *ctx);
+int test_bn2dec(BIO *bp);
 int rand_neg(void);
 static int results = 0;
 
@@ -260,6 +261,11 @@ int main(int argc, char *argv[])
         goto err;
     (void)BIO_flush(out);
 
+    message(out, "BN_bn2dec");
+    if (!test_bn2dec(out))
+        goto err;
+    (void)BIO_flush(out);
+
 #ifndef OPENSSL_NO_EC2M
     message(out, "BN_GF2m_add");
     if (!test_gf2m_add(out))
@@ -504,7 +510,7 @@ static void print_word(BIO *bp, BN_ULONG w)
 int test_div_word(BIO *bp)
 {
     BIGNUM *a, *b;
-    BN_ULONG r, s;
+    BN_ULONG r, rmod, s;
     int i;
 
     a = BN_new();
@@ -518,8 +524,14 @@ int test_div_word(BIO *bp)
 
         s = b->d[0];
         BN_copy(b, a);
+        rmod = BN_mod_word(b, s);
         r = BN_div_word(b, s);
 
+        if (rmod != r) {
+            fprintf(stderr, "Mod (word) test failed!\n");
+            return 0;
+        }
+
         if (bp != NULL) {
             if (!results) {
                 BN_print(bp, a);
@@ -1214,7 +1226,7 @@ int test_gf2m_add(BIO *bp)
     c = BN_new();
 
     for (i = 0; i < num0; i++) {
-        BN_rand(a, 512, 0, 0);
+        BN_rand(a, 512, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ANY);
         BN_copy(b, BN_value_one());
         a->neg = rand_neg();
         b->neg = rand_neg();
@@ -1833,6 +1845,52 @@ int test_small_prime(BIO *bp, BN_CTX *ctx)
     return ret;
 }
 
+int test_bn2dec(BIO *bp)
+{
+    static const char *bn2dec_tests[] = {
+        "0",
+        "1",
+        "-1",
+        "100",
+        "-100",
+        "123456789012345678901234567890",
+        "-123456789012345678901234567890",
+        "123456789012345678901234567890123456789012345678901234567890",
+        "-123456789012345678901234567890123456789012345678901234567890",
+    };
+    int ret = 0;
+    size_t i;
+    BIGNUM *bn = NULL;
+    char *dec = NULL;
+
+    for (i = 0; i < OSSL_NELEM(bn2dec_tests); i++) {
+        if (!BN_dec2bn(&bn, bn2dec_tests[i]))
+            goto err;
+
+        dec = BN_bn2dec(bn);
+        if (dec == NULL) {
+            fprintf(stderr, "BN_bn2dec failed on %s.\n", bn2dec_tests[i]);
+            goto err;
+        }
+
+        if (strcmp(dec, bn2dec_tests[i]) != 0) {
+            fprintf(stderr, "BN_bn2dec gave %s, wanted %s.\n", dec,
+                    bn2dec_tests[i]);
+            goto err;
+        }
+
+        OPENSSL_free(dec);
+        dec = NULL;
+    }
+
+    ret = 1;
+
+err:
+    BN_free(bn);
+    OPENSSL_free(dec);
+    return ret;
+}
+
 int test_lshift(BIO *bp, BN_CTX *ctx, BIGNUM *a_)
 {
     BIGNUM *a, *b, *c, *d;