Java代码C实现中的输出差异
我在程序中使用PBKDF2密码哈希技术。我所指的示例程序是C语言。 程序段如下所示:Java代码C实现中的输出差异,java,c,base64,pbkdf2,Java,C,Base64,Pbkdf2,我在程序中使用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 "base6
#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;
}
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;
}
}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括“base64.h”
#定义键长度24
#定义分隔符“$”
#定义SALTLEN 12
#定义用法()fprintf(stderr,“用法:%s[-i][-p密码]\n”,progname)
int main(int argc,字符**argv)
{
int迭代次数=901,rc,blen;
无符号字符saltbytes[SALTLEN];
焦*盐,*b64;
无符号字符密钥[128];
字符*pw1,*pw2,*密码;
char*progname=argv[0];
INTC;
int提示;
提示=1;
而((c=getopt(argc,argv,“i:p:”)!=EOF){
开关(c){
案例“i”:
迭代次数=atoi(optarg);
打破
案例“p”:
pw1=strdup(optarg);
pw2=strdup(optarg);
提示=0;
打破
违约:
退出(用法());
}
}
argc-=optind-1;
argv+=optind-1;
如果(argc!=1){
退出(用法());
}
如果(提示){
pw1=strdup(getpass(“输入密码”);
pw2=getpass(“重新输入相同的密码:”);
}
如果(strcmp(pw1,pw2)!=0){
fprintf(stderr,“密码不匹配!\n”);
申报表(1);
}
密码=pw1;
rc=随机字节(saltbytes,SALTLEN);
如果(rc==0){
fprintf(stderr,“无法为salt获取随机字节!\n”);
返回2;
}
base64_编码(saltbytes、SALTLEN和salt);
#ifdef原盐
PKCS5_PBKDF2_HMAC(密码,strlen(密码),
(无符号字符*)saltbytes,SALTLEN,
迭代,
EVP_sha256(),密钥长度,密钥);
#否则
内特萨特伦;
saltlen=strlen(salt);
PKCS5_PBKDF2_HMAC(密码,strlen(密码),
(未签名的字符*)盐,盐,
迭代,
EVP_sha256(),密钥长度,密钥);
#恩迪夫
blen=base64_编码(键、键长度和b64);
如果(blen>0){
printf(“PBKDF2$%s$%d$%s$%s\n”,
“sha256”,
迭代,
盐,
b64);
免费(b64);
}
免费(密码);
返回0;
}
C程序输出如下:
PBKDF2$sha256$901$QLtznh6yjEs4a4Fl$uzp3QAEpFZsqBvCssnL1eXZFxCiKzV7P
我尝试在Java中复制相同的内容,如下所示:
#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;
}
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;
}
}
公共类NewPBKDF2{
公共静态void main(字符串[]args)抛出NoSuchAlgorithmException、InvalidKeySpecException{
字符串originalPassword=“A3E9907E59A6379DB6A9C2657D242A64886D5B21E3586B3D4C2B4E6329570A10”;
String generatedSecuredPasswordHash=generateStorngPasswordHash(原始密码);
System.out.println(generatedSecuredPasswordHash);
}
私有静态字符串生成器TorngPasswordHash(字符串密码)抛出NoSuchAlgorithmException、InvalidKeySpecException{
int迭代次数=901;
char[]chars=password.toCharArray();
字节[]salt=getSalt();
字符串salt1=Base64.getEncoder().encodeToString(salt);
整数长度=24;
PBEKeySpec spec=新PBEKeySpec(字符、盐、迭代次数、长度*8);
SecretKeyFactory skf=SecretKeyFactory.getInstance(“PBKDF2WithHmacSHA256”);
byte[]hash=skf.generateScret(spec.getEncoded();
字符串hash1=bytesToHex(哈希);
试一试{
hash1=Base64.getEncoder().encodeToString(hash1.getBytes(“utf-8”);
}捕获(不支持DencodingException ex){
Logger.getLogger(NewPBKDF2.class.getName()).log(Level.SEVERE,null,ex);
}
返回“PBKDF2$sha256$”+迭代次数+“$”+salt1+“$”+hash1;
}
私有静态字节[]getSalt()引发NoSuchAlgorithmException{
SecureRandom sr=SecureRandom.getInstance(“SHA1PRNG”);
字节[]salt=新字节[12];
高级次字节(盐);
返盐;
}
静态字符[]hexArray=“0123456789ABCDEF”.toCharArray();
公共静态字符串bytesToHex(字节[]字节){
char[]hexChars=新字符[bytes.length*2];
对于(int j=0;j>>4];
hexChars[j*2+1]=hexArray[v&0x0F];
}
返回新字符串(hexChars);
}
公共静态字节[]hexStringToByteArray(字符串s){
int len=s.length();
字节[]数据=新字节[len/2];
对于(int i=0;i 数据[i/2]=(字节)((Character.digit(s.charAt(i),16)您的问题的答案建立在各种字符编码样式的基础上。字符串长度的不同是因为在这两种情况下使用了不同的编码(C和Java实现)
您可以在示例中注意到,hash1
(因为长度上的差异很明显)变量在UTF-8
中编码在Java中,而C使用ASCII
字符编码(已在标准中提到)。
此外,UTF-8是一种多字节编码,是一种多字节编码,每个字符使用1到4个字节。
您还可以参考以下内容:这可能很有趣,这就是为什么java中的哈希比C长的原因
希望答案有助于了解深入研究的问题。原版密码原版密码(确切)变量中存储了什么?字符串现在已硬编码。但它将随机生成/。