HarmonyOS 使用AES GCM模式加密,加密的结果和kotlin的完全不一样,这个写法有问题不?

ArkTS代码:

export async function encryptMessagePromise(plainText:cryptoFramework.DataBlob) {
  let data = new util.TextEncoder().encodeInto(JSON. stringify("1234"))
  let cipher = cryptoFramework.createCipher('AES128|GCMINoPadding');
  let symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128")
  let symKey =
    await symKeyGenerator.convertKey({ data: new util.TextEncoder().encodeInto("abcdefghdklmnopq") });
  let ivArray = new Uint8Array(12)
  for (let index = 0; index <12; index++) {
    ivArray[index]= symkey.getEncoded().data[index]
  }
  let gcmParams: cryptoFramework.GcmParamsSpec = {
    iv: {data:ivArray},
    aad: {data:new Uint8Array(8)},
    authTag: {data:new Uint8A rray(16)},
    algName: "GcmParamsSpec"
  };
  await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, gcmParams);
  let encryptUpdate = await cipher.doFinal({data:data});
  let array = new Uint8Array( [...gcmParams.iv.data, ... encryptUpdate.data])
  return array;
}

kotlin代码:

fun encrypt(encryptKey: String, encryptContent: ByteArray?): ByteArray? {
  val key ="abcdefghdklmnopg"
  val sKeySpec = SecretKeySpec(key. toByteArray(), "AES")
  val cipher = Cipher.getInstance ("AES/GCM/NoPadding")
  val temp = ByteArray(12)
  System.arraycopy(sKeySpec.encoded, 0,temp, 0, 12)
  val gcm = GCMParameterSpec(128,temp)
  cipher.init(Cipher.ENCRYPT_MODE, sKeySpec, gcm)
  val result = cipher.doFinal('"1234".toByteArray())
  val cipherText = ByteArray(12 + result.size)
  System.arraycopy(sKeySpec.encoded,0, cipherText,0,12)
  System.arraycopy(result, 0, cipherText, 12, result.size)
  return cipherText
}
阅读 499
1 个回答

修改为:

let gcmParams: cryptoFramework.GcmParamsSpec = {
  iv: { data: ivArray },
  aad: { data: new Uint8Array() },
  authTag: { data: new Uint8Array() },
  algName: "GcmParamsSpec"
};
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进