mirror of
https://github.com/billbuchanan/appliedcrypto.git
synced 2026-02-21 19:27:58 +00:00
47 lines
1.1 KiB
JavaScript
47 lines
1.1 KiB
JavaScript
!function(globals) {
|
|
'use strict'
|
|
|
|
var convertHex = {
|
|
bytesToHex: function(bytes) {
|
|
/*if (typeof bytes.byteLength != 'undefined') {
|
|
var newBytes = []
|
|
|
|
if (typeof bytes.buffer != 'undefined')
|
|
bytes = new DataView(bytes.buffer)
|
|
else
|
|
bytes = new DataView(bytes)
|
|
|
|
for (var i = 0; i < bytes.byteLength; ++i) {
|
|
newBytes.push(bytes.getUint8(i))
|
|
}
|
|
bytes = newBytes
|
|
}*/
|
|
return arrBytesToHex(bytes)
|
|
},
|
|
hexToBytes: function(hex) {
|
|
if (hex.length % 2 === 1) throw new Error("hexToBytes can't have a string with an odd number of characters.")
|
|
if (hex.indexOf('0x') === 0) hex = hex.slice(2)
|
|
return hex.match(/../g).map(function(x) { return parseInt(x,16) })
|
|
}
|
|
}
|
|
|
|
|
|
// PRIVATE
|
|
|
|
function arrBytesToHex(bytes) {
|
|
return bytes.map(function(x) { return padLeft(x.toString(16),2) }).join('')
|
|
}
|
|
|
|
function padLeft(orig, len) {
|
|
if (orig.length > len) return orig
|
|
return Array(len - orig.length + 1).join('0') + orig
|
|
}
|
|
|
|
|
|
if (typeof module !== 'undefined' && module.exports) { //CommonJS
|
|
module.exports = convertHex
|
|
} else {
|
|
globals.convertHex = convertHex
|
|
}
|
|
|
|
}(this); |