如何将Cryptojs AES转换为Java代码



我想将cryptojs代码转换为Java代码。这是JavaScript代码:

CryptoJS.AES.encrypt('hello',CryptoJS.enc.Utf8.parse(CryptoJS.MD5("http://stackoverflow.com")), {iv: CryptoJS.enc.Utf8.parse("1234567812345678")})

代码结果上方调用字符串为'qtzdsbcgma9 xbvesem70w =='

然后,我从cryptojs.md5(" http://stackoverflow.com"获得键值

这是Java代码:

 try {
        String content = "hello";
        String key = "57f4dad48e7a4f7cd171c654226feb5a";
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128, new SecureRandom(key.getBytes("utf-8")));
        SecretKey secretKey = kgen.generateKey();
        byte[] enCodeFormat = secretKey.getEncoded();

        SecretKeySpec key1 = new SecretKeySpec(enCodeFormat, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] byteContent = content.getBytes("utf-8");

        cipher.init(Cipher.ENCRYPT_MODE, key1,new IvParameterSpec("1234567812345678".getBytes("UTF-8")));
        byte[] result = cipher.doFinal(byteContent);
        System.out.println(new String(result).equals("QtzDsbCgmA9+XBVEsEm70w=="));
    } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (InvalidAlgorithmParameterException e) {
        e.printStackTrace();
    }

但是输出结果是错误的。如何修复Java代码以将结果更改为true。

根据@luka公园的建议,我可以解决我的问题。这是我的解决方案:

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    byte[] raw = sKey.getBytes();
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
    byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
    return new BASE64Encoder().encode(encrypted);

相关内容

  • 没有找到相关文章

最新更新