Passing hashed data as key to hash again returns incorrect results

被刻印的时光 ゝ 提交于 2019-12-04 17:35:39

How about this modification?

Reason of issue:

Both value and key of Utilities.computeHmacSha256Signature(value, key) are "String" or "Byte[]". In your script, when var kDate = hash( dateStamp, kSecret ); is run, kDate is the byte array. But when var kRegion = hash( regionName, kDate ); is run, regionName and kDate are "String" and "Byte[]", respectively. By this, after var kRegion = hash( regionName, kDate );, the result is not the same with that of jsSHA.

Modification points:

  • In order to avoid this, for example, please convert "String" to "Byte[]".

Modified script:

function sample() {
  var key = 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY';
  var dateStamp = '20150830';
  var regionName = 'us-east-1';
  var serviceName = 'iam';
  var kSecret = 'AWS4' + key;

  regionName = Utilities.newBlob(regionName).getBytes(); // Added
  serviceName = Utilities.newBlob(serviceName).getBytes(); // Added
  var value = Utilities.newBlob('aws4_request').getBytes(); // Added

  var kDate    = hash( dateStamp, kSecret );
  var kRegion  = hash( regionName,  kDate );
  var kService = hash( serviceName, kRegion );
  var kSigning = hash( value, kService );
  return kSigning;
}

function hash( payload, key ) {
  return Utilities.computeHmacSha256Signature(payload, key);
  // return Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_256, payload, key) // You can also use this.
}

Result:

kDate: 0138c7a6cbd60aa727b2f653a522567439dfb9f3e72b21f9b25941a42f04a7cd
kRegion: f33d5808504bf34812e5fade63308b424b244c59189be2a591dd2282c7cb563f
kService: 199e1f48c602a5ae77ce26a46906920e76fc8427aeaa53da643646fcda1ccfb0
kSigning: c4afb1cc5771d871763a393e44b703571b55cc28424d1a5e86da6ed3c154a4b9

References:

If this was not what you want, I'm sorry.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!