Sample code for 30+ languages & platforms
C

secp256k1 Key Generation and Keccak-256

See more ECC Examples

Starting in v11.0.0, Chilkat supports both secp256k1 key generation and Keccak-256 directly. These algorithms are typically used for Bitcoin and Ethereum.

Chilkat C Downloads

C
#include <C_CkPrng.h>
#include <C_CkEcc.h>
#include <C_CkPrivateKey.h>
#include <C_CkStringBuilder.h>
#include <C_CkBinData.h>

void ChilkatSample(void)
    {
    BOOL success;
    HCkPrng fortuna;
    const char *entropy;
    HCkEcc ecc;
    HCkPrivateKey privKey;
    HCkStringBuilder sb;
    HCkBinData bd;

    success = FALSE;

    // This example requires the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    // Create a Fortuna PRNG and seed it with system entropy.
    // This will be our source of random data for generating the ECDSA private key.
    fortuna = CkPrng_Create();
    entropy = CkPrng_getEntropy(fortuna,32,"base64");
    success = CkPrng_AddEntropy(fortuna,entropy,"base64");

    ecc = CkEcc_Create();

    // Generate a random ECDSA private key on the secp256k1 curve.
    privKey = CkPrivateKey_Create();
    success = CkEcc_GenKey(ecc,"secp256k1",fortuna,privKey);
    if (success == FALSE) {
        printf("%s\n",CkEcc_lastErrorText(ecc));
        CkPrng_Dispose(fortuna);
        CkEcc_Dispose(ecc);
        CkPrivateKey_Dispose(privKey);
        return;
    }

    printf("Successfully generated a sec256k1 key.\n");

    // Show how to compute the Keccak-256 hash in a few ways.
    sb = CkStringBuilder_Create();
    CkStringBuilder_Append(sb,"hello");

    printf("keccak-256: %s\n",CkStringBuilder_getHash(sb,"keccak-256","hex_lower","utf-8"));

    // Output:
    // keccak-256: 1c8aff950685c2ed4bc3174f3472287b56d9517b9c948127319a09a7a36deac8

    // To keccak-256 hash binary data
    bd = CkBinData_Create();
    CkBinData_AppendEncoded(bd,"00010203040506","hex");

    printf("keccak-256: %s\n",CkBinData_getHash(bd,"keccak-256","hex_lower"));

    // Output:
    // keccak-256: 801560412425120fa609be232d6fa71c7f64f42aee7977267687dcc0a2f5aa63


    CkPrng_Dispose(fortuna);
    CkEcc_Dispose(ecc);
    CkPrivateKey_Dispose(privKey);
    CkStringBuilder_Dispose(sb);
    CkBinData_Dispose(bd);

    }