Implementation of HMAC-SHA1 encryption algorithm in c++ and java

HMAC-SHA1 is an encryption algorithm that is commonly used daily. For example, when interacting with an https server, the data will be encrypted using this method. Sometimes the client and server are implemented in different languages, making it difficult to verify unilaterally. Therefore, I looked for a multi-language implementation.
For example, if the server is Apache,
its code may be
new HmacUtils(HmacAlgorithms.HMAC_SHA_1, key).hmacHex(data).
There may be other additional algorithms behind it, which will not be discussed.
Then most of the corresponding clients use c++ or java
c++ to implement the following

#include <stdio.h>
#include <string.h>

#include <string>
#include <iostream>

#include <openssl/md5.h>
#include <openssl/hmac.h>
#include <openssl/sha.h>

std::string HexHmacSha1(const char * key, const char * input)
{
    unsigned char md[20];
    char mdBufs[20*2+1] = {0};
    unsigned int len = 0;

    HMAC(EVP_sha1(), key, strlen(key), (unsigned char*)input, strlen(input), md, &len);

    for (unsigned int i = 0; i < len; ++i)
    {
        sprintf(mdBufs + i*2, "%02x", md[i]);
    }
    printf("in:%s, out:%s\n", input, mdBufs);

    return mdBufs;
}

int main(int argc, char **argv)
{
    const char *key = "key-xxxxx";
    const char *data = "Hello World";
    std::string hexSha = HexHmacSha1(key, data);

    data = "Next Test";
    hexSha = HexHmacSha1(key, data);

    return 0;
}

After compilation and execution, the example prints as follows:
in:Hello World, out:e3729ba295d21330983b64018edfd3affa57a6f2
in:Next Test, out:16978e2117c2f9b727111c8a939cafa4ccd9d751

import java.security.MessageDigest;
import java.util.Formatter;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class CryptoUtil {
    
    
    /**
     * MD5加密
     */
    public static String md5s(String plainText) {
    
    
        String str = "";
        try {
    
    
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            byte b[] = md.digest();

            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
    
    
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            str = buf.toString();
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
        return str;
    }


    private static String toHexString(byte[] bytes) {
    
    
        Formatter formatter = new Formatter();
        for (byte b : bytes) {
    
    
            formatter.format("%02x", b);
        }
        return formatter.toString();
    }

    public static String hmacSha1(String value, String key) {
    
    
        try {
    
    
            byte[] keyBytes = key.getBytes();
            SecretKeySpec signingKey = new SecretKeySpec(keyBytes,"HmacSHA1");
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(signingKey);
            byte[] rawHmac = mac.doFinal(value.getBytes());
            return toHexString(rawHmac);
        } catch (Exception e) {
    
    
            throw new RuntimeException(e);
        }
    }
}

// 使用示例
String key = "key-xxxxx";
String data = "Hello World";
String hmacHex = CryptoUtil.hmacSha1(data, key);
Log.d("", "in:" + key + "out:" + hmacHex);
// 打印出 in:key-xxxxxout:e3729ba295d21330983b64018edfd3affa57a6f2

Both implementations have the same output.
Author: Too handsome to go out

Guess you like

Origin blog.csdn.net/zmlovelx/article/details/128882389