gpt4 book ai didi

java - Java代码的C实现的输出差异

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:49:36 31 4
gpt4 key购买 nike

我在我的程序中使用 PBKDF2 密码散列技术。我所指的示例程序是用 C 编写的。程序片段如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <getopt.h>
#include <openssl/evp.h>
#include <openssl/rand.h>
#include "base64.h"

#define KEY_LENGTH 24
#define SEPARATOR "$"
#define SALTLEN 12

#define USAGE() fprintf(stderr, "Usage: %s [-i iterations] [-p password]\n", progname)

int main(int argc, char **argv)
{
int iterations = 901, rc, blen;
unsigned char saltbytes[SALTLEN];
char *salt, *b64;
unsigned char key[128];
char *pw1, *pw2, *password;
char *progname = argv[0];
int c;
int prompt;

prompt = 1;

while ((c = getopt(argc, argv, "i:p:")) != EOF) {
switch (c) {
case 'i':
iterations = atoi(optarg);
break;
case 'p':
pw1 = strdup(optarg);
pw2 = strdup(optarg);
prompt = 0;
break;
default:
exit(USAGE());
}
}

argc -= optind - 1;
argv += optind - 1;

if (argc != 1) {
exit(USAGE());
}

if ( prompt ) {
pw1 = strdup(getpass("Enter password: "));
pw2 = getpass("Re-enter same password: ");
}

if (strcmp(pw1, pw2) != 0) {
fprintf(stderr, "Passwords don't match!\n");
return (1);
}

password = pw1;

rc = RAND_bytes(saltbytes, SALTLEN);
if (rc == 0) {
fprintf(stderr, "Cannot get random bytes for salt!\n");
return 2;
}

base64_encode(saltbytes, SALTLEN, &salt);

#ifdef RAW_SALT
PKCS5_PBKDF2_HMAC(password, strlen(password),
(unsigned char *)saltbytes, SALTLEN,
iterations,
EVP_sha256(), KEY_LENGTH, key);
#else
int saltlen;
saltlen = strlen(salt);

PKCS5_PBKDF2_HMAC(password, strlen(password),
(unsigned char *)salt, saltlen,
iterations,
EVP_sha256(), KEY_LENGTH, key);
#endif


blen = base64_encode(key, KEY_LENGTH, &b64);
if (blen > 0) {
printf("PBKDF2$%s$%d$%s$%s\n",
"sha256",
iterations,
salt,
b64);

free(b64);
}

free(password);
return 0;
}

C程序输出如下: PBKDF2$sha256$901$QLtznh6yjEs4a4Fl$uzp3QAEpFZsqBvCssnL1eXZFxCiKzV7P

我尝试在Java中复制相同的内容,如下所示:

public class NewPBKDF2 {

public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException {
String originalPassword = "A3E9907E59A6379DB6A9C2657D242A64886D5B21E3586B3D4C2B4E6329570A10";
String generatedSecuredPasswordHash = generateStorngPasswordHash(originalPassword);
System.out.println(generatedSecuredPasswordHash);
}

private static String generateStorngPasswordHash(String password) throws NoSuchAlgorithmException, InvalidKeySpecException {
int iterations = 901;
char[] chars = password.toCharArray();
byte[] salt = getSalt();
String salt1 = Base64.getEncoder().encodeToString(salt);
int length = 24;




PBEKeySpec spec = new PBEKeySpec(chars, salt, iterations, length * 8 );
SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
byte[] hash = skf.generateSecret(spec).getEncoded();
String hash1 = bytesToHex(hash);

try {
hash1 = Base64.getEncoder().encodeToString(hash1.getBytes("utf-8"));
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(NewPBKDF2.class.getName()).log(Level.SEVERE, null, ex);
}


return "PBKDF2$sha256$"+ iterations +"$"+salt1+"$"+hash1;
}

private static byte[] getSalt() throws NoSuchAlgorithmException {
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");

byte[] salt = new byte[12];


sr.nextBytes(salt);
return salt;
}

static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}

public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}

}

上面的程序给我的输出如下:

PBKDF2$sha256$901$v2DdYPk47r/I3aQJ$N0Y3MjZENzVEOTE5MDcxQkNEOEM5MTAyREQ2MjdEQ0NGNzIzRTZGN0ZCOUYzN0NF

为什么我得到不同的密码长度(最后一部分)。我不明白。你能帮我找出我的错误吗?

最佳答案

您的问题的答案基于各种字符编码 样式的基础。 String 长度的不同是因为在两种情况下(C 和 Java 实现)使用了不同的编码。

您可以在您的示例中注意到,hash1(因此长度差异很明显)变量在 Java< 中以 UTF-8 编码/strong> 而C使用ASCII字符编码(在ANSI标准中已经提到)。
此外,UTF-8 是一种多字节编码,是一种多字节编码,每个字符使用 1 到 4 个字节。你也可以引用这个:How many bytes does Unicode Character takes?这可能很有趣,这就是为什么与 C 相比,Java 中的散列长度更长。

希望答案有助于对经过深入研究的问题获得一些见解。

关于java - Java代码的C实现的输出差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45893641/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com