EVP_DigestUpdate和"从'unsigned char *'到'const char *'&#34的无效转换;

时间:2016-04-05 17:13:26

标签: c++ hash openssl sha256

以下是OpenSSL wiki上EVP Message Digests的示例:

[[WCSession defaultSession] sendMessage:@{@"cmd":@"sendUpdate"} replyHandler:nil errorHandler:^{ /*handle errors*/ }]

问题是当我尝试编译它时出现以下错误:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    <...>
    [[WCSession defaultSession] setDelegate:self];
    [[WCSession defaultSession] activateSession];
    <...>
}

- (void)session:(WCSession *)session activationDidCompleteWithState:(WCSessionActivationState)activationState error:(nullable NSError *)error {
}

- (void)sessionDidBecomeInactive:(WCSession *)session
{}

- (void)sessionDidDeactivate:(WCSession *)session
{
    [session activateSession];
}

- (void)session:(WCSession *)session didReceiveMessage:(NSDictionary<NSString *, id> *)message {
    NSString *cmd = message[@"cmd"];
    if ([cmd isEqual:@"sendUpdate"]) {
        [self sendUpdate];
    }
}

- (void)sendUpdate {
    WCSession *session = [WCSession defaultSession];
    if (session.isWatchAppInstalled && session.activationState == WCSessionActivationStateActivated) {
        [[WCSession defaultSession] transferUserInfo:[self dictionaryFullOfUpdates]];
    }
}

因此void digest_message(unsigned char *message, unsigned char **digest, unsigned int *digest_len) { EVP_MD_CTX *mdctx; if((mdctx = EVP_MD_CTX_create()) == NULL) handleErrors(); if(1 != EVP_DigestInit_ex(mdctx, EVP_sha256(), NULL)) handleErrors(); if(1 != EVP_DigestUpdate(mdctx, message, strlen(message))) handleErrors(); if((*digest = (unsigned char *)OPENSSL_malloc(EVP_MD_size(EVP_sha256()))) == NULL) handleErrors(); if(1 != EVP_DigestFinal_ex(mdctx, *digest, digest_len)) handleErrors(); EVP_MD_CTX_destroy(mdctx); } 调用邮件会导致错误,因为evp_test.cpp:18:60: error: invalid conversion from ‘unsigned char*’ to ‘const char*’ [-fpermissive] if(1 != EVP_DigestUpdate(mdctx, message, strlen(message))) In file included from /usr/include/c++/5/cstring:42:0 需要strlen?这是因为字符串是strlen的数组吗?

我应该采取哪些不同的方式解决问题?

1 个答案:

答案 0 :(得分:0)

已修复:

void digest_message(const unsigned char *message, size_t message_len,
                    unsigned char **digest, unsigned int *digest_len)
{
    EVP_MD_CTX *mdctx;

    if((mdctx = EVP_MD_CTX_create()) == NULL)
        handleErrors();

    if(1 != EVP_DigestInit_ex(mdctx, EVP_sha256(), NULL))
        handleErrors();

    if(1 != EVP_DigestUpdate(mdctx, message, message_len))
        handleErrors();

    if((*digest = (unsigned char *)OPENSSL_malloc(EVP_MD_size(EVP_sha256()))) == NULL)
        handleErrors();

    if(1 != EVP_DigestFinal_ex(mdctx, *digest, digest_len))
        handleErrors();

    EVP_MD_CTX_destroy(mdctx);
}

你是对的,strlen需要一个char数组,而不是unsigned charbyte

更大的问题是设计/工程。需要显式长度参数,因为不能保证字节数组像C字符串一样以NULL结尾。实际上,字节数组中可能嵌入了一些NULL。