最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is there a way to convert a string to a base 10 number for encryption? - Stack Overflow

programmeradmin6浏览0评论

Note: I found a similar question, but it is in python.


I've been trying to think of an algorithm or native method for this, and I'm stumped.

This is what I have so far:

encode=function(n,f){
    return (n).toString(f)
}
decode=function(s,f){
    return parseInt(s,f)
}

Basically, I need a way to convert a string, like 'Hello World!' to a base 10 (hexadecimal will work as well) number, like 14438792758793754875, and I am wondering if there's a proper way to do it before I possibly waste my time with something like:

str='Hello World'
returnString=''
for(var i in str){
    returnString+=(
        str[i]=='A'?'0'
        :str[i]=='B'?'1'
        etc...
    )
}

Not only would that be very time consuming, but I have no idea how I would possibly convert it back, as once I get into numbers like 11 for L, a for loop wouldn't do, and would return BB.

The reason I am asking this is because I plan to use it in the future for more efficient and secure, encrypted storage. for example, something like:

//save
numstr=encodeToNumber(inputElement.value)
b36str=encode(numstr,36)
storage['items'].push(b36str)
localStorage['App Data']=JSON.stringify(storage)

//load
if(localStorage['App Data']){
    storage=JSON.parse(localStorage['App Data'])
}else{
    storage={
        items:[],
        config:{
            etc
        }
    }
}
//Assuming storage.items looks like this: ['rgie', 'zyy', '2il7']
for(i in storage['items']){
    b36str=storage['items']//rgie, zyy, 2il7
    numstr=decode(b36str,36)//1281110, 46618, 117403
    container.innerHTML+='<hr>'+decodeFromNumber(numstr)//Milk, Eggs, Bread
}

//Output
Milk
Eggs
Bread

I actually did spend several minutes manually encrypting 'Milk', 'Eggs', and 'Bread' to their base36 counterparts so it could be accurate.


Update: Aadit M Shaw gave a function that produces hexadecimal strings from strings, and I reverse engineered it to my needs and got this:

en=function(s){
    var s2d=function(s){
        s=s.replace(/ /g,'+').replace(/!/g,'.')
        var n=[]
        for(var i in s){
            n.push(s.charCodeAt(i))
        }
        return n
    }
    var arr=s2d(s)
    var s2=''
    for (var i in arr){
        s2+=arr[i].toString(36)
    }
    return s2
}
de=function(s){
    var arr=s.split(/(..)/)
    var arr2=[]
    var s2=''
    for(var i in arr){
        if(arr[i]){
            arr2.push(parseInt(arr[i],36))
        }
    }
    for(var i in arr2){
        s2+=String.fromCharCode(arr2[i])
    }
    return s2.replace(/\+/g,' ')
}

While the encoded string is larger than I would have liked, it could be useful for protecting cookies from being hacked or something.

For example, using the example I made here, I made this message 21173b2x3030172t2p38173d333936172u2p2r2t as well as this ЎDŽ̺ǦDŽ̌. And if you manage to decode the second one, then decode this too ʒ̴ͻϮ

This isn't very practical, though, so I'll probably end up using the library Ragnarokkr linked me to.

Thank you all for the responses!

Note: I found a similar question, but it is in python.


I've been trying to think of an algorithm or native method for this, and I'm stumped.

This is what I have so far:

encode=function(n,f){
    return (n).toString(f)
}
decode=function(s,f){
    return parseInt(s,f)
}

Basically, I need a way to convert a string, like 'Hello World!' to a base 10 (hexadecimal will work as well) number, like 14438792758793754875, and I am wondering if there's a proper way to do it before I possibly waste my time with something like:

str='Hello World'
returnString=''
for(var i in str){
    returnString+=(
        str[i]=='A'?'0'
        :str[i]=='B'?'1'
        etc...
    )
}

Not only would that be very time consuming, but I have no idea how I would possibly convert it back, as once I get into numbers like 11 for L, a for loop wouldn't do, and would return BB.

The reason I am asking this is because I plan to use it in the future for more efficient and secure, encrypted storage. for example, something like:

//save
numstr=encodeToNumber(inputElement.value)
b36str=encode(numstr,36)
storage['items'].push(b36str)
localStorage['App Data']=JSON.stringify(storage)

//load
if(localStorage['App Data']){
    storage=JSON.parse(localStorage['App Data'])
}else{
    storage={
        items:[],
        config:{
            etc
        }
    }
}
//Assuming storage.items looks like this: ['rgie', 'zyy', '2il7']
for(i in storage['items']){
    b36str=storage['items']//rgie, zyy, 2il7
    numstr=decode(b36str,36)//1281110, 46618, 117403
    container.innerHTML+='<hr>'+decodeFromNumber(numstr)//Milk, Eggs, Bread
}

//Output
Milk
Eggs
Bread

I actually did spend several minutes manually encrypting 'Milk', 'Eggs', and 'Bread' to their base36 counterparts so it could be accurate.


Update: Aadit M Shaw gave a function that produces hexadecimal strings from strings, and I reverse engineered it to my needs and got this:

en=function(s){
    var s2d=function(s){
        s=s.replace(/ /g,'+').replace(/!/g,'.')
        var n=[]
        for(var i in s){
            n.push(s.charCodeAt(i))
        }
        return n
    }
    var arr=s2d(s)
    var s2=''
    for (var i in arr){
        s2+=arr[i].toString(36)
    }
    return s2
}
de=function(s){
    var arr=s.split(/(..)/)
    var arr2=[]
    var s2=''
    for(var i in arr){
        if(arr[i]){
            arr2.push(parseInt(arr[i],36))
        }
    }
    for(var i in arr2){
        s2+=String.fromCharCode(arr2[i])
    }
    return s2.replace(/\+/g,' ')
}

While the encoded string is larger than I would have liked, it could be useful for protecting cookies from being hacked or something.

For example, using the example I made here, I made this message 21173b2x3030172t2p38173d333936172u2p2r2t as well as this ЎDŽ̺ǦDŽ̌. And if you manage to decode the second one, then decode this too ʒ̴ͻϮ

This isn't very practical, though, so I'll probably end up using the library Ragnarokkr linked me to.

Thank you all for the responses!

Share Improve this question edited May 23, 2017 at 12:25 CommunityBot 11 silver badge asked Jan 15, 2013 at 21:00 Braden BestBraden Best 8,9984 gold badges34 silver badges46 bronze badges 13
  • Define "encrypted": Why not just encrypt it? – Dave Newton Commented Jan 15, 2013 at 21:04
  • @Dave I'm not sure I understand your question. If you're asking why I don't just use the encode method I provided, it's because it only accepts base 10 integers. – Braden Best Commented Jan 15, 2013 at 21:05
  • 3 If you want something secure, something trivial like this is useless. I'm asking why don't you just use actual encryption instead of trying to implement something yourself? I don't understand your ment regarding "base 10 integers", you said it could be hex--which is it? – Dave Newton Commented Jan 15, 2013 at 21:07
  • 1 if you need true encryption, I think this library could be really useful. It supports hash and encryption/decryption algorithms as well. – Ragnarokkr Commented Jan 15, 2013 at 21:07
  • 1 @B1KMusic thanks. I'm happy to know that it was helpful to you ;) – Ragnarokkr Commented Jan 15, 2013 at 23:35
 |  Show 8 more ments

2 Answers 2

Reset to default 10

Try this:

function encode(string) {
    var number = "0x";
    var length = string.length;
    for (var i = 0; i < length; i++)
        number += string.charCodeAt(i).toString(16);
    return number;
}

See the demo here: http://jsfiddle/hGKAg/2/

Decoding is just as simple:

function decode(number) {
    var string = "";
    number = number.slice(2);
    var length = number.length;
    for (var i = 0; i < length;) {
        var code = number.slice(i, i += 2);
        string += String.fromCharCode(parseInt(code, 16));
    }
    return string;
}

Try the demo: http://jsfiddle/hGKAg/3/

While I've never used this before, a friend of mine has given this library a good review. Apparently, you can encode strings using any Base standard with this library:

Nibbler.js

发布评论

评论列表(0)

  1. 暂无评论