md.digest 计算的消息摘要与JDK计算的值不一致-鸿蒙开发者社区-51CTO.COM

md.digest 计算的消息摘要与JDK计算的值不一致

有个特性需要计算文件的摘要信息。使用SHA-256算法做了计算,发现与java代码计算的结果不一致。

let md: cryptoFramework.Md; 
try { 
  md = cryptoFramework.createMd('SHA256'); 
} catch (e) { 
  logger.error(TAG, 'createMd with SHA256 fail:' + JSON.parse(e)); 
  expect(e).assertFail(); 
  return; 
} 
 
let inputStream: fs.Stream | undefined = undefined; 
try { 
// let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY); 
inputStream = await fs.createStream(filePath, 'r+'); 
let readLen = 256; 
let readSize = 0; 
while (readLen > 0) { 
let buf = new ArrayBuffer(readLen); 
readLen = await inputStream.read(buf, { 
offset: readSize 
}); 
readSize += readLen; 
// arkTS 计算的数据类型为 Uint8Array 
let inputDataBlob: cryptoFramework.DataBlob = { 
data: new Uint8Array(buf) 
} 
await md.update(inputDataBlob); 
} 
// 计算结果 
let mdDigest = await md.digest(); 
public static byte[] computeHashOfFile(String fileLocation, String hashType) { 
MessageDigest md; 
byte[] hash = null; 
try { 
md = MessageDigest.getInstance(hashType); 
} catch (NoSuchAlgorithmException e) { 
  return null; 
} 
 
try (InputStream fis = new FileInputStream(fileLocation)) { 
int n = 0; 
int readSize = 0; 
while (n != -1) { 
byte[] buffer = new byte[256]; 
n = fis.read(buffer); 
if (n > 0) { 
md.update(buffer, 0, n); 
readSize += n; 
} 
} 
hash = md.digest(); 
} catch (IOException e) { 
 
} 
return hash; 
}
HarmonyOS
2024-04-29 17:03:38
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
进击的鱼白

ArkTS代码有误,参照以下方式书写

try { 
  // let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY); 
  inputStream = await fs.createStream(filePath, 'r+'); 
  let readLen = 256; 
  let readSize = 0; 
  while (readLen > 0) { 
    let buf = new ArrayBuffer(readLen); 
    readLen = await inputStream.read(buf, { 
      offset: readSize 
    }); 
    if (readLen > 0) { 
      let inputDataBlob: cryptoFramework.DataBlob = { 
        data: new Uint8Array(buf, 0, readLen) 
      } 
      await md.update(inputDataBlob); 
      readSize += readLen; 
    } 
  } 
  let mdDigest = await md.digest();
分享
微博
QQ
微信
回复
2024-04-30 10:51:54
相关问题
启动和调试行为不一致
128浏览 • 1回复 待解决
Path组件绘制线条粗细不一致
1826浏览 • 1回复 待解决
签名不一致报错怎么回事?
2536浏览 • 1回复 待解决
water flow 出现gap不一致问题
619浏览 • 1回复 待解决
napi里面,相同输入输出不一致
1607浏览 • 1回复 待解决
window 全屏操作不同设备表现不一致
310浏览 • 1回复 待解决
HarmonyOS 如何计算文件md5
509浏览 • 1回复 待解决
文字空行高度与字体高度不一致
2023浏览 • 1回复 待解决