Node.js加密代码转换为Java加密代码

huangapple go评论83阅读模式
英文:

Node JS encryption code to Java encryption code

问题

以下是用Java编写的等效代码:

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;

public class Main {

    public static String toHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }

    public static void main(String[] args) throws Exception {
        byte[] key = "XXXXXXXX00000000".getBytes("UTF-8");
        String message = "HelloWorld";

        try {
            key = Arrays.copyOf(key, 16);
            SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encstr = cipher.doFinal(message.getBytes("UTF-8"));
            String encData = toHex(encstr);
            System.out.println(encData);
        } catch (NoSuchAlgorithmException nsae) {
            throw new Exception("Invalid Java Version");
        } catch (NoSuchPaddingException nse) {
            throw new Exception("Invalid Key");
        }
    }
}

请注意,Java版本的加密结果可能会在细节上略有不同,但它们应该是等效的。

英文:

I'm trying to find the similar java code for the below Node JS code,

Node JS Code:

     var crypto = require('crypto');

     var mykey = crypto.createCipher('aes-128-ecb', 'XXXXXXXX00000000');
     var mystr = mykey.update('HelloWorld', 'utf8', 'hex')
     mystr += mykey.final('hex');

      console.log(mystr);

Encryption Result: ce25d577457cf8113fa4d9eb16379529

Java Code:

 public static String toHex(String arg) throws UnsupportedEncodingException {
	          return String.format("%x", new BigInteger(1, arg.getBytes("UTF-8")));
	    }

 public static void main(String args[]) throws Exception{
 
	byte[] key = "XXXXXXXX".getBytes();
	String message = "HelloWorld";
	  	
	try {
		key = Arrays.copyOf(key, 16); 
		SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
		Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec);    	    
		byte encstr[] = cipher.update(message.getBytes());
		String encData = new String(encstr, "UTF-8");
		encData = toHex(encData);
		byte encstr2[] = cipher.doFinal();
		String encData2 = new String(encstr2);
		encData  = encData + toHex(encData2);           
        System.out.println(encData);
    } catch (NoSuchAlgorithmException nsae) {
        throw new Exception("Invalid Java Version");
    } catch (NoSuchPaddingException nse) {
        throw new Exception("Invalid Key");
    }
	
}

Encryption Result: 056efbfbdefbfbd7c7760efbfbdefbfbdefbfbd39262cefbfbdefbfbd5166

答案1

得分: 0

以下是您提供的代码的翻译部分:

// 导入必要的库
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MainSo {
    public static void main(String[] args) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        System.out.println("https://stackoverflow.com/questions/63263081/node-js-encryption-code-to-java-encryption-code");

        String plaintext = "HelloWorld"; // 明文
        String keyString = "XXXXXXXX00000000"; // 密钥,16个字符
        byte[] key = keyString.getBytes(StandardCharsets.UTF_8);
        
        // 使用不安全的 MD5 哈希算法
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] keyMd5 = md.digest(key);
        
        // 使用不安全的 AES ECB 模式加密
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        SecretKeySpec secretKeySpec = new SecretKeySpec(keyMd5, "AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        byte[] ciphertext = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
        System.out.println("ciphertext Java:   " + bytesToHex(ciphertext));
        System.out.println("ciphertext NodeJS: " + "ce25d577457cf8113fa4d9eb16379529");
    }
    
    // 将字节数组转换为十六进制字符串的辅助方法
    private static String bytesToHex(byte[] bytes) {
        StringBuffer result = new StringBuffer();
        for (byte b : bytes) result.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1));
        return result.toString();
    }
}

请注意,这段代码中包含了一些安全问题,如使用不安全的 MD5 哈希算法和 AES ECB 模式加密。建议使用更安全的算法和模式来加强数据安全性。

英文:

Taking up the comments of @Robert and @Topaco I wrote a simple decryption program that is working for the given password 'XXXXXXXX00000000'.

Please keep in mind that this progrsm is using UNSECURE AES ECB mode and UNSECURE MD5 hash algorithm.
The program does NOT provide any proper exception handling.

This is the result:

ciphertext Java:   ce25d577457cf8113fa4d9eb16379529
ciphertext NodeJS: ce25d577457cf8113fa4d9eb16379529

My code:

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MainSo {
public static void main(String[] args) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
System.out.println("https://stackoverflow.com/questions/63263081/node-js-encryption-code-to-java-encryption-code");
String plaintext = "HelloWorld";
String keyString =  "XXXXXXXX00000000"; // 16 chars
byte[] key = keyString.getBytes(StandardCharsets.UTF_8);
// md5 hashing is unsecure !!
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] keyMd5 = md.digest(key);
// aes ecb mode encryption is unsecure
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(keyMd5, "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] ciphertext = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
System.out.println("ciphertext Java:   " + bytesToHex(ciphertext));
System.out.println("ciphertext NodeJS: " + "ce25d577457cf8113fa4d9eb16379529");
}
private static String bytesToHex(byte[] bytes) {
// service method for displaying a byte array as hex string
StringBuffer result = new StringBuffer();
for (byte b : bytes) result.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1));
return result.toString();
}
}

huangapple
  • 本文由 发表于 2020年8月5日 18:19:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/63263081.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定