最近做了一个需求,传输数据的时候需要将信息进行按位异或3位进行加密。
实现方法如下:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript 异或加密^_^ </h2>
<p id="demo">^_^</p>
<script>
// 按位异或 加密
var oldPsw = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*(){}[]-=_+,?><:"'
var newPsw = pswEncrypt(oldPsw)
console.log('newPswXor: ', newPsw)
//newPswXor: 0325476981`cbedgfihkjmlonqpsrutwvyx{@CBEDGFIHKJMLONQPSRUTWVYX[ A"%$_'+)(z|Z\,<^*->?=;#
function pswEncrypt(msg) {
var data = msg|| ''
var msgArr = data.split('')
var result = msgArr.map(function (item) {
return pswXor(item)
})
return result.join('')
}
function pswXor(msg) {
var isNum = /[0-9]/.test(msg)
if (isNum) {
return +msg ^ 1
} else {
var notNum = msg.charCodeAt()
var notNumXor = notNum ^ 1
return String.fromCharCode(notNumXor)
}
}
document.getElementById("demo").innerHTML = newPsw;
</script>
</body>
</html>