3

我正在尝试使用 Web Crypto API ( http://www.w3.org/TR/WebCryptoAPI/#SP800-38B ) 在 Java 和 JavaScript 之间进行加密/解密。我在这个论坛上找到了有用的信息,但现在我被困住了......

爪哇:

    String charset = "UTF-8";

    String secret = "hallo1234567890x";
    String salt = "fqpq6V_Vggn-fR_EiEKFBA";
    byte [] iv = "1111111111111111".getBytes(charset);

    // Get Key
    byte[] key = (salt).getBytes(charset);
    key = Arrays.copyOf(key, 16);

    // Generate specs
    SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");

    // Instantiate cipher
    Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
    cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, new IvParameterSpec(iv));

    byte[] encrypted = cipher.doFinal((secret).getBytes());

    //output:
    System.out.print("byte array: ");
    for(int i=0; i<encrypted.length; i++){
        System.out.print(encrypted[i] + "\t");          
    }
    System.out.println("");

    System.out.println("encrypted string Base64: " + new Base64().encodeAsString(encrypted));

输出:

   byte array: -116 101 -89 89  33  8   -42 77  -82 79  -39 38  112 68  44  16  
   encrypted string Base64: jGWnWSEI1k2uT9kmcEQsEA==

JavaScript:

var my_key = "fqpq6V_Vggn-fR_EiEKFBA"; 
var my_counter = new Uint8Array(16); 
for(var i=0;i<16;i++){
    my_counter[i] = 1;
}
var my_data = str2ab("hallo1234567890x");

对于 importKey 我使用以下参数:

    kty: "oct",
    k: my_key,
    alg: "A128CBC",
    ext: true,

    name: "AES-CBC",

对于解密,我使用参数:

    name: "AES-CBC",
    iv: my_counter, 

我得到以下 ArrayBuffer 作为输出: [213, 168, 98, 252, 218, 52, 221, 67, 4, 31, 93, 40, 60, 199, 161, 64, 145, 92, 95, 160, 158, 47, 212, 189, 56, 180, 27, 45, 122, 169, 133, 181, 61, 5, 26, 240, 135, 108, 251, 239, 209, 214, 86, 141, 171, 96, 175, 188]

window.btoa(arraybuffer);它是:"W29iamVjdCBBcnJheUJ1ZmZlcl0="

我使用ab2str(buf)and str2ab(str)frome:在字符串和 ArrayBuffers 之间转换

function ab2str(buf) {
   return String.fromCharCode.apply(null, new Uint16Array(buf));
}

function str2ab(str) {
   var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
   var bufView = new Uint16Array(buf);
   for (var i=0, strLen=str.length; i<strLen; i++) {
       bufView[i] = str.charCodeAt(i);
   }
   return buf;
}

缺少什么以使 Java 和 JavaScript 输出相同?

4

1 回答 1

0

您的 IV 不匹配。1 个字节与 ASCII 中的“1”不同,后者在 ASCII 表中实际上是 49。

于 2015-05-26T14:18:58.833 回答