Encrypting/decrypting text strings using OpenSSL ECC

后端 未结 2 1557
别跟我提以往
别跟我提以往 2021-01-31 05:20

How can I use OpenSSL\'s ECC support to encrypt or decrypt a text string? I am able to generate ECC private/public keys using OpenSSL APIs, but I don\'t know how to encrypt plai

2条回答
  •  甜味超标
    2021-01-31 05:51

    ECC itself doesn't really define any encryption/decryption operations - algorithms built on elliptic curves do.

    One example is Elliptic-Curve Diffie-Hellman. You could encrypt a message using ECDH by:

    1. Generating an ephemeral EC key.
    2. Using that key and the public key of the recipient, generate a secret using ECDH.
    3. Use that secret as a key to encrypt the message with a symmetric cipher, like AES.
    4. Transmit the encrypted message and the ephemeral public key generated in step 1.

    To decrypt:

    1. Load the ephemeral public key from the message.
    2. Use that public key together with your recipient key to generate a secret using ECDH.
    3. Use that secret as a key to decrypt the message with the symmetric cipher.

    EDIT: The following is the basic idea to generate a secret using ECDH. First we need to define a key derivation function - this one uses the SHA1 hash.

    void *KDF1_SHA1(const void *in, size_t inlen, void *out, size_t *outlen)
    {
        if (*outlen < SHA_DIGEST_LENGTH)
            return NULL;
        else
            *outlen = SHA_DIGEST_LENGTH;
        return SHA1(in, inlen, out);
    }
    

    This is the ECDH code for the sender side. It assumes that the recipient's public key is already in "recip_key", and you have verified it with EC_KEY_check_key(). It also omits much important error checking, for the sake of brevity, which you will definitely want to include in production code.

    EC_KEY *ephemeral_key = NULL;
    const EC_GROUP *group = NULL;
    unsigned char buf[SHA_DIGEST_LENGTH] = { 0 };
    
    group = EC_KEY_get0_group(recip_key);
    ephemeral_key = EC_KEY_new();
    EC_KEY_set_group(ephemeral_key, group);
    
    EC_KEY_generate_key(ephemeral_key);
    ECDH_compute_key(buf, sizeof buf, EC_KEY_get0_public_key(recip_key), ephemeral_key, KDF1_SHA1);
    

    After this the buffer 'buf' contains 20 bytes of material you can use for keying. This abbreviated example is based on the code in "ecdhtest.c" in the openssl source distribution - I suggest taking a look at it.

    You will want to send the public key portion of ephemeral_key with the encrypted message, and securely discard the private key portion. A MAC over the data is also a good idea, and if you need more than 20 bytes of keying material a longer hash is probably in order.

    The recipient does something similar, except that its private key already exists (since the sender had to know the corresponding public key beforehand), and the public key is recieved from the sender.

提交回复
热议问题