Skip to content

Instantly share code, notes, and snippets.

@steventux
Created March 12, 2012 20:18
Show Gist options
  • Save steventux/2024426 to your computer and use it in GitHub Desktop.
Save steventux/2024426 to your computer and use it in GitHub Desktop.
Javascript bitwise encoding
var Encryption = (function() {
function generateKey(seed) {
var key = ""
while (key.length < seed) key += Math.srand(seed)
return key
}
/*
* @param 'val' - a String to encode or a byte[] to decode.
* @param 'salt' - (Optional) salt to perform bitwise encode/decode operation.
*/
function xorHash(val, salt) {
var encrypt = typeof val == 'string'
var byteArr = encrypt ? val.toByteArr() : val
var keyBytes = typeof salt == 'undefined' ?
generateKey(byteArr.length).toByteArr() : salt.toByteArr()
for (var i = 0; i < byteArr.length; i++) {
byteArr[i] = byteArr[i] ^ keyBytes[i % keyBytes.length]
}
return (encrypt ? byteArr : String.fromCharCode.apply(String, byteArr))
}
return {
/**
*
*/
encode : function(str, salt) {
var encoded = []
var bytes = xorHash(str, salt)
for (var i = 0; i < bytes.length; i++) encoded.push(bytes[i].toString(16))
return encoded.join(",")
},
/**
*
*/
decode : function(hsh, salt) {
var decoded = []
var hshArr = hsh.split(",")
for (var i = 0; i < hshArr.length; i++) decoded.push(parseInt(hshArr[i], 16))
return xorHash(decoded, salt)
}
}
})()
Math.srand = function(seed) {
if (!seed) seed = new Date().getTime()
seed = (seed*9301+49297) % 233280
return seed/(233280.0)
}
String.prototype.toByteArr = function() {
var arr = []
for (var i = 0;i < this.length; i++) arr.push(this.charCodeAt(i))
return arr
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment