Cryptojs Scala到JS加密并不起作用,但另一种方式效果很好

时间:2015-08-04 04:34:57

标签: javascript scala encryption cryptography cryptojs

Scala到Scala运行良好,JS对Scala运行良好。但它对Scala不适用于JS。但是,如果我在Scala中加密了一个简单的Json,如:{" name":" dung"},它运行良好。

  

Scala代码:

  def encryptData(data: String) = {
    val saltBytes = Array[Int](0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x78, 0x90, 0x12, 0x34, 0x90, 0x12, 0x34, 0x56) map {_.asInstanceOf[Byte]}
    val ivBytes = Array[Int](0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56) map {_.asInstanceOf[Byte]}
    val ivParamSpec = new IvParameterSpec(ivBytes)
    val secretKey = genSecretKey("somekey", saltBytes)
    val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
    cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParamSpec)
    val encryptedData = cipher.doFinal(data.getBytes("UTF-8"))
    val encodedData = (new BASE64Encoder()) encodeBuffer(encryptedData)
    Json.obj(
              "salt" -> DatatypeConverter.printHexBinary(saltBytes),
              "iv" -> DatatypeConverter.printHexBinary(ivBytes),
              "data" -> encodedData
            )
  }

  def decryptData(encryptedData: EncryptedData) = {
    val saltBytes = DatatypeConverter.parseHexBinary(encryptedData.salt)
    val ivBytes = DatatypeConverter.parseHexBinary(encryptedData.iv)
    val ivParamSpec = new IvParameterSpec(ivBytes)
    val secretKey = genSecretKey("somekey", saltBytes)
    val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
    cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParamSpec)
    val decodedValue = (new BASE64Decoder()) decodeBuffer(encryptedData.data)
    val decryptedData = new String(cipher.doFinal(decodedValue))
    decryptedData
  }
  

Javascript代码:

function encrypt(data) {
  var salt = CryptoJS.lib.WordArray.random(128/8);
  var iv = CryptoJS.lib.WordArray.random(128/8);
  var secretKey = "somekey";
  var key128Bits100Iterations = CryptoJS.PBKDF2(secretKey, salt, { keySize: 128/32, iterations: 100 });
  var encrypted = CryptoJS.AES.encrypt(JSON.stringify(data), key128Bits100Iterations, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7  });

  return {
      salt: String(salt),
      iv: String(iv),
      data: String(encrypted)
  };
}

function decrypt(obj) { 
    var salt = CryptoJS.enc.Hex.parse(obj.salt);
    var iv = CryptoJS.enc.Hex.parse(obj.iv);
    var encrypted = obj.data;
    var key = CryptoJS.PBKDF2("somekey", salt, { keySize: 128/32, iterations: 100 });
    var decrypt = CryptoJS.AES.decrypt(encrypted, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
    return decrypt.toString(CryptoJS.enc.Utf8);
}

1 个答案:

答案 0 :(得分:1)

问题是编码的字符串有一个由此问题引起的新行字符。 Carriage return issue decoding Base64 from Java and sending to browser从sun的Base64Encoder切换到org.apache.commons.codec.binary.Base64之后,问题就消失了。