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
按赞同
/
按时间
yijuefei

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
相关问题
Path组件绘制线条粗细不一致
146浏览 • 1回复 待解决
签名不一致报错怎么回事?
1110浏览 • 1回复 待解决
napi里面,相同输入输出不一致
130浏览 • 1回复 待解决
文字空行高度与字体高度不一致
365浏览 • 1回复 待解决
redis如何实现双读一致问题?
1332浏览 • 1回复 待解决
移动边缘计算基本想法是怎样
2153浏览 • 1回复 待解决
请问鸿蒙os对科学计算支持怎样?
1040浏览 • 1回复 待解决
有谁知道如何计算文本宽度
432浏览 • 1回复 待解决
对于话题下参与人数如何计算
1348浏览 • 2回复 待解决
redis 缓存和数据库读写一致问题
3395浏览 • 1回复 待解决