forked from stacks-network/pybitcoin
-
Notifications
You must be signed in to change notification settings - Fork 4
/
keyspace.py
37 lines (31 loc) · 1.08 KB
/
keyspace.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# -*- coding: utf-8 -*-
"""
Coinkit
~~~~~
:copyright: (c) 2013 by Halfmoon Labs
:license: MIT, see LICENSE for more details.
"""
import re
def int_to_hex(i):
return re.sub(r'^0x|L$', '', hex(i))
def int_to_string(integer, keyspace_chars):
""" Turn a positive integer into a string. """
if not integer > 0:
raise ValueError('integer must be > 0')
output = ""
while integer > 0:
integer, digit = divmod(integer, len(keyspace_chars))
output += keyspace_chars[digit]
return output[::-1]
def string_to_int(string, keyspace_chars):
""" Turn a string into a positive integer. """
output = 0
for char in string:
output = output * len(keyspace_chars) + keyspace_chars.index(char)
return output
def change_keyspace(string, original_keyspace, target_keyspace):
""" Convert a string from one keyspace to another. """
assert isinstance(string, str)
intermediate_integer = string_to_int(string, original_keyspace)
output_string = int_to_string(intermediate_integer, target_keyspace)
return output_string