BIGNUM *SRP_Calc_u(const BIGNUM *A, const BIGNUM *B, const BIGNUM *N)
{
    /* k = SHA1(PAD(A) || PAD(B) ) -- tls-srp draft 8 */

    BIGNUM *u = NULL;
    unsigned char cu[SHA_DIGEST_LENGTH];
    unsigned char *cAB = NULL;
    EVP_MD_CTX *ctxt = NULL;
    int longN;
    if ((A == NULL) || (B == NULL) || (N == NULL))
        return NULL;

    if (BN_ucmp(A, N) >= 0 || BN_ucmp(B, N) >= 0)
        return NULL;

    longN = BN_num_bytes(N);

    ctxt = EVP_MD_CTX_new();
    if (ctxt == NULL)
        return NULL;
    if ((cAB = OPENSSL_malloc(2 * longN)) == NULL)
        goto err;

    memset(cAB, 0, longN);

    if (!EVP_DigestInit_ex(ctxt, EVP_sha1(), NULL)
        || !EVP_DigestUpdate(ctxt, cAB + BN_bn2bin(A, cAB + longN), longN)
        || !EVP_DigestUpdate(ctxt, cAB + BN_bn2bin(B, cAB + longN), longN))
        goto err;

    if (!EVP_DigestFinal_ex(ctxt, cu, NULL))
        goto err;

    if ((u = BN_bin2bn(cu, sizeof(cu), NULL)) == NULL)
        goto err;
    if (BN_is_zero(u)) {
        BN_free(u);
        u = NULL;
    }

 err:
    OPENSSL_free(cAB);
    EVP_MD_CTX_free(ctxt);

    return u;
}