本文介绍了openssl_encrypt Java中的256个CBC raw_data的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试用Java 6中的OPENSSL_RAW_DATA做一个PHP openssl_encrypt aes-256-cbc,但没有成功.我找到了一些与此相关的主题,但是我仅在没有raw_data的aes-128-cbc中成功完成了此任务.我为此找到的最佳主题是:但是raw_data无法正常工作,并且会随机生成256位密钥.实际上,Php版本是:

I try to do a PHP openssl_encrypt aes-256-cbc with OPENSSL_RAW_DATA in java 6 without success. I found some topic about this, but I'ved successful only to do it in aes-128-cbc without raw_data. The best topic I founded about this it's : AES-256 CBC encrypt in php and decrypt in Java or vice-versaBut the raw_data doesn't work and the 256 bits key is randomly generated.In fact the Php version is :

<?php>
    openssl(
        "hello",
        "aes-256-cbc",
        "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
        OPENSSL_RAW_DATA,
        "aaaaaaaaaaaaaaaa"
    )
?>

我实际上有这个:

public static void main(String[] args) {
    try {
        // 128 bits key
        openssl_encrypt("hello", "bbbbbbbbbbbbbbbb", "aaaaaaaaaaaaaaaa");
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

private static String openssl_encrypt(String data, String strKey, String strIv) throws Exception {
    Base64 base64 = new Base64();
    Cipher ciper = Cipher.getInstance("AES/CBC/PKCS5Padding");
    SecretKeySpec key = new SecretKeySpec(strKey.getBytes("UTF-8"), "AES");
    IvParameterSpec iv = new IvParameterSpec(strIv.getBytes("UTF-8"), 0, ciper.getBlockSize());

    // Encrypt
    ciper.init(Cipher.ENCRYPT_MODE, key, iv);
    byte[] encryptedCiperBytes = base64.encode((ciper.doFinal(data.getBytes())));

    String s = new String(encryptedCiperBytes);
    System.out.println("Ciper : " + s);
    return s;
}

推荐答案

经过一些修改和测试,我发现了它:

After few modification and some testing I found it :

private static String openssl_encrypt(String data, String strKey, String strIv) throws Exception {
    Base64 base64 = new Base64();
    Cipher ciper = Cipher.getInstance("AES/CBC/PKCS5Padding");
    SecretKeySpec key = new SecretKeySpec(strKey.getBytes(), "AES");
    IvParameterSpec iv = new IvParameterSpec(strIv.getBytes(), 0, ciper.getBlockSize());

    // Encrypt
    ciper.init(Cipher.ENCRYPT_MODE, key, iv);
    byte[] encryptedCiperBytes = ciper.doFinal(data.getBytes());

    String s = new String(encryptedCiperBytes);
    System.out.println("Ciper : " + s);
    return s;
}

PHP中的openssl_encrypt不会将其结果转换为base64,并且我也使用了无参数原因的getBytes(),对于某些键,我对键的长度有错误.

openssl_encrypt in PHP don't convert his result in base64, and I also use getBytes() without param cause, for some keys, I had an error about the key's lentgh.

因此,此方法的作用与以下方法相同:

So this method do the same thing than :

<?php>
    openssl_encrypt(data, "aes-256-cbc", key, OPENSSL_RAW_DATA, iv);
?>

这篇关于openssl_encrypt Java中的256个CBC raw_data的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 14:04