def run(s): mm = s.encode("utf8") output = "" output += "base16:" + base64.b16encode(mm).decode("utf8") try: output += "\r\nbase24:" + pybase24.encode24(mm) except: output += "\r\nbase24:失败" output += "\r\nbase32:" + base64.b32encode(mm).decode("utf8") try: output += "\r\nbase36:" + str(base36.loads(mm)) except: output += "\r\nbase36:失败" output += "\r\nbase58:" + base58.b58encode(mm).decode("utf8") output += "\r\nbase62:" + base62.encodebytes(mm) output += "\r\nbase64:" + base64.b64encode(mm).decode("utf8") output += "\r\nbase85:" + base64.b85encode(mm).decode("utf8") output += "\r\nbase91:" + base91.encode(mm) try: output += "\r\nbase92:" + base92.b92encode(mm).decode("utf8") except: output += "\r\nbase92:失败" try: output += "\r\nbase128:" + base128.encode(mm).decode("utf8") except: output += "\r\nbase128:失败" return output
def encrypt(plainText): private_key = hashlib.sha256(PASSWORD.encode("utf-8")).digest() plainText = pad(plainText) iv = Random.new().read(AES.block_size) cipher = AES.new(private_key, AES.MODE_CBC, iv) return base62.encodebytes(iv + cipher.encrypt(plainText))
def test_roundtrip(input_bytes): """Ensures type consistency. Suggested by @dhimmel""" base62_encoded = base62.encodebytes(input_bytes) assert isinstance(base62_encoded, str) output_bytes = base62.decodebytes(base62_encoded) assert isinstance(output_bytes, bytes) assert input_bytes == output_bytes
def post(self): # Get posted data arg = self.parser.parse_args() url = arg["url"] if len(url) > config.MAX_URL_LENGTH: abort(400, status=400, message='This url is too long') else: # Encrypt url urlWithTimestemp = url + str(time.time()) encodeUrl = url.encode() shortCode = base62.encodebytes( hashlib.md5(encodeUrl).digest()[-5:]) # Insert record to database urls = UrlModel.UrlModel(db) result = urls.insertUrl(url, shortCode) # Return successful result retJosn = { "status": 200, "short_code": shortCode, "short_url": config.API_BASE_URL + config.API_PORT + shortCode } app.logger.info("Register url success") return jsonify(retJosn)
def encode_domain(data: bytes) -> str: assert len(data) <= 180, "plain data is longer than 180 bytes" enc_data = base62.encodebytes(data) segments = list(filter(lambda it: len(it) > 0, [enc_data[0:60], enc_data[60:120], enc_data[120:180], enc_data[180:240]])) enc_str = "x" + ".x".join(segments) assert len(enc_str) <= 230, "enc data is longer than 230 bytes" return enc_str
def get_citation_id(standard_citation): """ Get the citation_id for a standard_citation. """ assert '@' not in standard_citation as_bytes = standard_citation.encode() blake_hash = hashlib.blake2b(as_bytes, digest_size=6) digest = blake_hash.digest() citation_id = base62.encodebytes(digest) return citation_id
def _short(self, url, count): """ MD5 hash and take first 40bit encdoe with base62 """ if count + 3 < len(hashlib.md5(url.encode('utf-8')).digest()): result = base62.encodebytes(hashlib.md5(url.encode('utf-8')).digest()[count:count+3]) self.logger.debug(f"shorten hash url: {url}, count: {count}, result: {result}") return result else: self.logger.debug("shorten hash url count > md5 bits") return None
def citation_to_metadata(citation, cache={}, override={}): """ Return a dictionary with citation metadata """ source, identifer = citation.split(':', 1) identifer = standardize_identifier(source, identifer) standard_citation = f'{source}:{identifer}' if standard_citation not in override and standard_citation in cache: return cache[standard_citation] result = { 'source': source, 'identifer': identifer, 'standard_citation': standard_citation } if standard_citation in override: print('Found standard citation...') result['citeproc'] = override[standard_citation] elif source == 'doi': print('Getting citation from DOI...') result['citeproc'] = metadata.get_doi_citeproc(identifer) # result['bibtex'] = metadata.get_doi_bibtex(identifer) elif source == 'pmid': print('Getting citation from PMID...') result['citeproc'] = metadata.get_pubmed_citeproc(identifer) elif source == 'arxiv': print('Getting citation from arXiv...') result['bibtex'] = metadata.get_arxiv_bibtex(identifer) elif source == 'url': print('Getting citation from URL...') result['citeproc'] = metadata.get_url_citeproc(identifer) elif source == 'grey': print('Getting citation from URL via Greycite...') result['citeproc'] = metadata.get_url_citeproc_greycite(identifer) else: msg = f'Unsupported citation source {source} in {citation}' raise ValueError(msg) digest = blake2b(standard_citation.encode(), digest_size=6).digest() citation_id = base62.encodebytes(digest) result['citation_id'] = citation_id if 'citeproc' in result: result['citeproc'] = citeproc_passthrough( result['citeproc'], set_id=citation_id) if 'bibtex' in result: result['bibtex'] = bibtex_passthrough( result['bibtex'], set_id=citation_id) cache[standard_citation] = result return result
def encode(txt): print("[+]input is ", end="") print(txt) print( "==============================================================================" ) #base16 print("[成功]base16 encode: ", end="") print(base64.b16encode(txt)) #base32 print("[成功]base32 encode: ", end="") print(base64.b32encode(txt)) #base36 try: base36_m_str = bytes.decode(txt) base36_m_int = int(base36_m_str) base36_cipher = base36.dumps(base36_m_int) print("[成功]base36 encode: ", end="") print(base36_cipher) except Exception as e: print("[失败]base36 encode: ", end="") print("base36加密只支持整数数字") #base58 print("[成功]base58 encode: ", end="") print(base58.b58encode(txt)) #base62 print("[成功]base62 encode: ", end="") print(base62.encodebytes(txt)) #base64 print("[成功]base64 encode: ", end="") print(base64.b64encode(txt)) #base85 print("[成功]base85 encode: ", end="") print(base64.b85encode(txt)) #base91 print("[成功]base91 encode: ", end="") print(base91.encode(txt)) #base92 print("[成功]base92 encode: ", end="") print(py3base92.encode(txt))
def get_citation_short_id(standard_id): """ Get the short_id derived from a citation's standard_id. Short IDs are generated by converting the standard_id to a 6 byte hash, and then converting this digest to a base62 ASCII str. The output short_id consists of characters in the following ranges: 0-9, a-z and A-Z. """ import hashlib import base62 assert '@' not in standard_id as_bytes = standard_id.encode() blake_hash = hashlib.blake2b(as_bytes, digest_size=6) digest = blake_hash.digest() short_id = base62.encodebytes(digest) return short_id
def shorten_citekey(standard_citekey): """ Return a shortened citekey derived from the input citekey. The input citekey should be standardized prior to this function, since differences in the input citekey will result in different shortened citekeys. Short citekeys are generated by converting the input citekey to a 6 byte hash, and then converting this digest to a base62 ASCII str. Shortened citekeys consist of characters in the following ranges: 0-9, a-z and A-Z. """ import hashlib import base62 assert not standard_citekey.startswith('@') as_bytes = standard_citekey.encode() blake_hash = hashlib.blake2b(as_bytes, digest_size=6) digest = blake_hash.digest() short_citekey = base62.encodebytes(digest) return short_citekey
def encode(self, payload, timestamp=None): if not isinstance(payload, bytes): payload = payload.encode() if timestamp is None: timestamp = calendar.timegm(datetime.utcnow().timetuple()) version = struct.pack("B", self.VERSION) time = struct.pack(">L", timestamp) if self._nonce is None: nonce = generate_nonce() else: nonce = self._nonce header = version + time + nonce ciphertext = crypto_aead_xchacha20poly1305_ietf_encrypt(payload, header, nonce, self._key) return base62.encodebytes(header + ciphertext)
def test_encodebytes(b, i): assert base62.encodebytes(b) == base62.encode(i)
def test_invalid_string(): with pytest.raises(TypeError): base62.encodebytes({})
def member_list(request): # 키 발급 if request.method == 'GET': if not 'key' in request.GET: # key를 파라미터로 주지 않는다면, return JsonResponse({'msg': 'params error'}, status=400) api_key = request.GET.get('key', None) # key 파라미터 추출 if api_key != hashlib.sha256(temp_key.encode()).hexdigest(): # key 파라미터가 올바르지 않으면, return JsonResponse({'msg': 'key params error'}, status=400) student_db = Member.objects.all() # Member 테이블의 모든 튜플 추출 std_num = request.GET.get('std_num', None) # 전달 받은 학번 추출 major = request.GET.get('major', None) # 전달 받은 전공 추출 name = request.GET.get('name', None) # 전달 받은 이름 추출 email = request.GET.get('email', None) # 전달 받은 이메일 추출 if student_db.filter(email=email).exists(): # params로 전달받은 이메일이 DB에 존재하는지 확인 return JsonResponse({'msg': 'Email is already exists'}, status=400) # info_dump에 전달 받은 정보 concat info_dump = str(std_num) + str(major) + str(email) # 학번 + 전공 + 이메일 info_hash = hashlib.sha256(info_dump.encode('utf-8')).hexdigest() # sha256 해쉬 container_num = check_container_id() # container_id_list 인덱스 번호 추출 command = ["sh", "../indy/start_docker/sh_check_attrib.sh", container_id_list[container_num], master_did, info_hash, std_num] # did발급 명령어 try: # 명령어 인자로 하여 Popen 실행 process = Popen(command, stdout=PIPE, stderr=PIPE) process.wait() with open('../../deploy/' + std_num + '_check_attrib.json')as f: json_data = json.load(f) error = json_data['error'] if error == 'Error': # 생성된 JSON파일의 error 키 값이 Error이라면, os.remove('/home/deploy/' + std_num + '_check_attrib.json') # 생성된 파일 삭제 return JsonResponse({'msg': 'user info is not exists in blockchain'}, status=400) os.remove('/home/deploy/' + std_num + '_check_attrib.json') # 생성된 파일 삭제 # user_key 해시 하는 부분 salt = base62.encodebytes(os.urandom(16)) # salt값 생성 salt = bytes(salt, encoding="utf-8") email_dump = info_dump + str(name) + str(salt) # 학번 + 전공 + 이메일 + 이름 + 솔트 user_key = hashlib.sha256(email_dump.encode('utf-8')).hexdigest() # user_key 해쉬 user_key_json = {'user_key': ''} user_key_json['user_key'] = user_key return JsonResponse(user_key_json, status=201) # user_key 값 반환 except Exception as e: return JsonResponse({'msg': 'failed_Exception', 'error': str(e)}, status=400) # 회원가입 요청 + did 발급 if request.method == 'POST': email = request.GET.get('email', None) # 전달 받은 이메일 값 추출 student_db = Member.objects.all() # Member 테이블의 모든 튜플 추출 user_key = request.GET.get('key', None) # 전달 받은 key 추출 std_num = request.GET.get('std_num', None) # 전달 받은 학번 추출 major = request.GET.get('major', None) # 전달 받은 전공 추출 time_stamp = int(time.time()) # 타임스탬프 # wallet_name (이메일 + timestamp) 생성 wallet_name = hashlib.sha256((email + str(time_stamp)).encode()).hexdigest() wallet_key = request.GET.get('simple_password', None) # 간편 pwd 추출 container_num = check_container_id() # container_id_list 인덱스 번호 추출 command = ["sh", "../indy/start_docker/sh_generate_did.sh", container_id_list[container_num], wallet_name, wallet_key, std_num] # did발급 명령어 try: # 명령어 인자로 하여 Popen 실행 process = Popen(command, stdout=PIPE, stderr=PIPE) process.wait() # did 재발급까지 대기 with open('../../deploy/' + wallet_name + '_gen_did.json')as f: # server로 복사된 did 열기 json_data = json.load(f) # json_data에 json으로 저장 error = json_data['error'] if error == 'Error': # 생성된 json파일의 error 키 값이 Error 이라면, os.remove('/home/deploy/' + wallet_name + '_gen_did.json') # 생성된 파일 삭제 return JsonResponse({'msg': 'DID generate error'}, status=400) os.remove('/home/deploy/' + wallet_name + '_gen_did.json') # 생성된 파일 삭제 did = json_data['did'] # Did 저장 cmp1 = str(did) + str(wallet_key) did_time_hash = hashlib.sha256(cmp1.encode('utf-8')).hexdigest() position = request.GET.get('position', None) # 관리자 인지 여부 추출 if position == 'admin': # 관리자 회원가입 이라면, data = {'email': '', 'user_key': '', 'wallet_id': '', 'did': '', # json 형태로 저장 'did_time_hash': '', 'position': '', 'container_id': ''} data['email'] = email data['user_key'] = user_key data['wallet_id'] = wallet_name data['did'] = did data['did_time_hash'] = did_time_hash data['position'] = position data['container_id'] = container_id_list[container_num] else: # 일반 사용자 회원 가입이라면 data = {'email': '', 'user_key': '', 'wallet_id': '', 'did': '', 'did_time_hash': '', 'container_id':''} data['email'] = email data['user_key'] = user_key data['wallet_id'] = wallet_name data['did'] = did data['did_time_hash'] = did_time_hash data['container_id'] = container_id_list[container_num] serializer = MemberSerializer(data=data) if serializer.is_valid(): # 입력 data들 포맷 일치 여부 확인 serializer.save() # 해당 data를 Member 테이블에 저장 return JsonResponse({'did': did, 'error': error}, status=201) except Exception as e: # 예외 처리 return JsonResponse({'msg': 'failed_Exception', 'error': str(e)}, status=400)
def encode_base62(self, plain_text): return base62.encodebytes(plain_text.encode('ascii'))
def encrypt(message): message = json.dumps(message).encode('utf-8') space = (int(len(message) / 8) + 1) * 8 code = blowfish.encrypt(message.ljust(space)) return base62.encodebytes(code)
def BASE(): cypher_text = '' plain_text = '' #接收post的数据 data = request.get_data() data = data.decode('utf-8') data = json.loads(data) text = data['text'] #输入字符串 typed = data['typed'] #输入base(num),即base的类型 operator = data['operator'] #加密或者解密 # print(text) try: if text and typed and operator: if operator == 'encode': #加密算法 plain_text = text.encode(encoding='utf-8') if typed == 'BASE64': cypher_text = base64.b64encode(plain_text) elif typed == 'BASE32': cypher_text = base64.b32encode(plain_text) elif typed == 'BASE58': cypher_text = base58.b58encode(plain_text) elif typed == 'BASE91': cypher_text = base91.encode(plain_text) # elif num_of_base == '92': # cypher_text = base92.encode(plain_text) elif typed == 'BASE36': cypher_text = base36.loads(plain_text) # elif num_of_base=='16': # cypher_text = hex(plain_text) elif typed == 'BASE62': cypher_text = base62.encodebytes(plain_text) elif typed == 'BASE85': cypher_text = base64.a85encode(plain_text) if type(cypher_text) == bytes: resu = { 'code': 200, 'result': cypher_text.decode('utf-8'), 'length': len(cypher_text.decode('utf-8')) } #如果输出是字节流格式 else: resu = { 'code': 200, 'result': cypher_text, 'length': len(cypher_text) } #如果输出是字符串形式 return json.dumps(resu, ensure_ascii=False) elif operator == 'decode': #解密算法 cypher_text = text if typed == 'BASE64': plain_text = base64.b64decode(cypher_text) elif typed == 'BASE32': plain_text = base64.b32decode(cypher_text) elif typed == 'BASE58': plain_text = base58.b58decode(cypher_text) elif typed == 'BASE91': plain_text = base91.decode(cypher_text) # elif num_of_base == '92': # plain_text = base92.decode(cypher_text) elif typed == 'BASE36': plain_text = base36.dumps(cypher_text) # elif num_of_base=='16': # plain_text = int(cypher_text) elif typed == 'BASE62': plain_text = base62.decodebytes(cypher_text) elif typed == 'BASE85': plain_text = base64.a85decode(cypher_text) if type(plain_text) == bytes: resu = { 'code': 200, 'result': plain_text.decode('utf-8'), 'length': len(plain_text.decode('utf-8')) } # 如果输出是字节流格式 else: resu = { 'code': 200, 'result': plain_text, 'length': len(plain_text) } # 如果输出是字符串形式 #resu = {'code': 200, 'cypher_text':plain_text.decode('utf-8') } return json.dumps(resu, ensure_ascii=False) else: resu = {'code': 10001, 'result': '参数不能为空!'} return json.dumps(resu, ensure_ascii=False) except: resu = {'code': 10000, 'result': '输入字符集错误。'} return json.dumps(resu, ensure_ascii=False)
def short(url): hashStr = base62.encodebytes( hashlib.md5(url.encode(encoding='utf-8')).digest()[-5:]) return hashStr
def __init__(self, operation: str, config: Optional[Config] = None) -> None: self.request_status = STATUSOP.PREPARE self.request_id = None self.operation = None self.request_command = None self.config = None self.request_timestamp = None self.request_version = None self.response_status = None self.response_nsmap = dict() self.request_xml = None self.request_signature_string = "" if operation in self.__operation_mapping: self.request_command = operation + 'Request' self.operation = self.__operation_mapping[operation] else: raise CheckError( "Error:Invalid:Command", f"{operation} is not within [{', '.join(self.__operation_mapping)}]" ) if not config: if Config: config = Config() else: raise CheckError("Error:No:Configuration", 'No config defined') self.config = config self.request_id = base62.encodebytes(secrets.token_bytes(25))[:30] self.request_timestamp = datetime.now(timezone.utc).isoformat( timespec="milliseconds").replace("+00:00", "Z") self.request_version = self.config.apiversion COMMON = self.config.ns('common') APINS = self.config.ns('api') NSMAP = {None: APINS[1:-1], 'common': COMMON[1:-1]} self.request_xml = etree.Element(f"{APINS}{self.request_command}", nsmap=NSMAP) # Header header = etree.SubElement(self.request_xml, f"{COMMON}header") etree.SubElement(header, f"{COMMON}requestId").text = self.request_id etree.SubElement(header, f"{COMMON}timestamp").text = self.request_timestamp etree.SubElement(header, f"{COMMON}requestVersion").text = self.request_version etree.SubElement(header, f"{COMMON}headerVersion").text = '1.0' # User user = etree.SubElement(self.request_xml, f"{COMMON}user") etree.SubElement(user, f"{COMMON}login").text = self.config.user['login'] etree.SubElement(user, f"{COMMON}passwordHash", cryptoType='SHA-512').text = self.config.passwordHash etree.SubElement( user, f"{COMMON}taxNumber").text = self.config.user['taxNumber'] self.request_signature_xml = etree.SubElement( user, f"{COMMON}requestSignature", cryptoType='SHA3-512') # Software software = etree.SubElement(self.request_xml, f"{APINS}software") for k, v in self.config.software.items(): etree.SubElement(software, f"{APINS}{k}").text = v self.request_signature_xml.text = self.signature super().__init__()
def generate_string(url: str) -> str: return base62.encodebytes(hashlib.sha256(f'{url}{random.random()}'.encode()).digest())[:10]
def to_string(data: bytes) -> str: return base62.encodebytes(data)
def get_rsa_str(key): if type(key) == str: return key return base62.encodebytes(key.export_key('DER'))
def rc4_encrypt(message, key): # result = str(base64.b64encode(result.encode("utf-8")), "utf-8") result = rc4_process(message, rc4_init_vector(key)) result = base62.encodebytes(result.encode()) return result
def generate_short_url(long_url=None, length=7): hs = sha256(long_url.encode('utf-8')).digest() short_url = base62.encodebytes(hs)[:length] return short_url
def test_encodebytes_type(): with pytest.raises(TypeError): base62.encodebytes("1234")
def test_encodebytes_rtype(): """Make sure the return type of encodebytes() is string.""" encoded = base62.encodebytes(b"1234") assert isinstance(encoded, str)
import base62 as b img=open(input("Images file: "), "rb") imgEnc=b.decode(b.encodebytes(img.read())) img.close() f=open(input("Dangerous file: "), "rb") fEnc=b.decode(b.encodebytes(f.read())) f.close() f.open("diff", "w") f.write(imgEnc-fEnc)
def base_all(): cypher_text = '' plain_text = '' text = request.values.get('text') #输入字符串 num_of_base = request.values.get('num_of_base') #输入base(num),即base的类型 encode_or_decode = request.values.get('encode_or_decode') #加密或者解密 try: if text and num_of_base and encode_or_decode: if encode_or_decode == 'encode': #加密算法 plain_text = text.encode(encoding='utf-8') if num_of_base == '64': cypher_text = base64.b64encode(plain_text) elif num_of_base == '32': cypher_text = base64.b32encode(plain_text) elif num_of_base == '58': cypher_text = base58.b58encode(plain_text) elif num_of_base == '91': cypher_text = base91.encode(plain_text) # elif num_of_base == '92': # cypher_text = base92.encode(plain_text) elif num_of_base == '36': cypher_text = base36.loads(plain_text) # elif num_of_base=='16': # cypher_text = hex(plain_text) elif num_of_base == '62': cypher_text = base62.encodebytes(plain_text) elif num_of_base == '85': cypher_text = base64.a85encode(plain_text) if type(cypher_text) == bytes: resu = { 'code': 200, 'result': cypher_text.decode('utf-8'), 'length': len(cypher_text.decode('utf-8')) } #如果输出是字节流格式 else: resu = { 'code': 200, 'result': cypher_text, 'length': len(cypher_text) } #如果输出是字符串形式 return json.dumps(resu, ensure_ascii=False) elif encode_or_decode == 'decode': #解密算法 cypher_text = text if num_of_base == '64': plain_text = base64.b64decode(cypher_text) elif num_of_base == '32': plain_text = base64.b32decode(cypher_text) elif num_of_base == '58': plain_text = base58.b58decode(cypher_text) elif num_of_base == '91': plain_text = base91.decode(cypher_text) # elif num_of_base == '92': # plain_text = base92.decode(cypher_text) elif num_of_base == '36': plain_text = base36.dumps(cypher_text) # elif num_of_base=='16': # plain_text = int(cypher_text) elif num_of_base == '62': plain_text = base62.decodebytes(cypher_text) elif num_of_base == '85': plain_text = base64.a85decode(cypher_text) if type(plain_text) == bytes: resu = { 'code': 200, 'result': plain_text.decode('utf-8'), 'length': len(plain_text.decode('utf-8')) } # 如果输出是字节流格式 else: resu = { 'code': 200, 'result': plain_text, 'length': len(plain_text) } # 如果输出是字符串形式 #resu = {'code': 200, 'cypher_text':plain_text.decode('utf-8') } return json.dumps(resu, ensure_ascii=False) else: resu = {'code': 10001, 'message': '参数不能为空!'} return json.dumps(resu, ensure_ascii=False) except: resu = {'code': 10000, 'message': '输入字符集错误。'} return json.dumps(resu, ensure_ascii=False)
def getShort(url): return base62.encodebytes(hashlib.md5(url.encode('utf-8')).digest()[-5:])