JAVA to Python MD5 hashlib - python

I am trying to convert java code into python for doing some encryption using md5. Can you please help me to solve this.
public static void main(String args[]){
String result = "";
JSONObject o1 = new JSONObject();
o1.put("stationId","1298491919448667556");
String body = o1.toJSONString();
System.out.println(body);
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(body.getBytes());
byte[] b = md.digest();
result = java.util.Base64.getEncoder().encodeToString(b);
System.out.println("ContentMD5:"+result);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
Output: 5pxCd9dmyPR/V2jerFJdXQ==
Python code sample:
import json
import base64, hashlib
body_content = {}
body_content["stationId"] = "1298491919448667556"
body = json.dumps(body_content, sort_keys=True).encode()
hash = hashlib.md5()
hash.update(body)
content_md5 = base64.b64encode(hash.digest()).decode()
print("content-md5",content_md5)
Output: nc9o/UcyLURh7uEbz6A+8w==
Please help me to get same output as java.

Related

Different results in AES encryption between Python and Java

I am trying to encrypt the communications between a java and a python app and the problem is I'm getting different result in decrypting the encrypted string from the other side in both apps.
I searched a lot but I didn't found any problem in the code and I will be much appreciated if you guide me in this.
Here is the encryption function in java side:
public static String encrypt(String value) {
try {
String privateKey = "1234567887654321";
String stringIV = getRandomIV();
IvParameterSpec iv = new IvParameterSpec(stringIV.getBytes());
SecretKeySpec skeySpec = new SecretKeySpec(privateKey.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(value.getBytes(StandardCharsets.UTF_8));
String encryptedString = new String(encrypted)
String toEncrypt = stringIV + encryptedString;
return android.util.Base64.encodeToString(toEncrypt.getBytes("UTF-8"), android.util.Base64.DEFAULT);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
static String getRandomIV() {
UUID randomUUID = UUID.randomUUID();
return randomUUID.toString().replaceAll("_", "").replaceAll("-", "").substring(0,16);
}
and here is the decryption part in python:
msg_bytes=bytes(msg, encoding="utf8").decode("utf-8",'ignore')
b64decoded=base64.b64decode(msg_bytes)
cipher = AES.new('1234567887654321'.encode("utf8"), AES.MODE_CBC, b64decoded[0:16])
decoded = cipher.decrypt(b64decoded[16:48])
decoded = bytes(decoded).decode("utf-8",'ignore')
I'm testing this with a 32 byte message and I'm getting different results with AES part, alse here is my java decryption function:
public static String decrypt(String encrypted) {
try {
String privateKey = "1234567887654321";
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
byte[] base64decoded = new byte[0];
base64decoded = android.util.Base64.decode(encrypted, android.util.Base64.DEFAULT);
String base64decodedString = new String(base64decoded);
byte[] byteiv = Arrays.copyOfRange(base64decoded, 0, 16);
IvParameterSpec iv = new IvParameterSpec(byteiv);
SecretKeySpec skeySpec = new SecretKeySpec(privateKey.getBytes(), "AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] bytes = Hex.decodeHex(hex(base64decodedString.substring(16,48).getBytes()).toCharArray());
byte[] original = new byte[0];
byte[] bytemsg = Arrays.copyOfRange(base64decoded, 16, base64decoded.length);
original = cipher.doFinal(bytemsg);
return new String(original.toString());
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
and also python's encryption:
data = str(json.dumps(data))
iv = Random.get_random_bytes(16)
cipher = AES.new('1234567887654321'.encode("utf8"), AES.MODE_CBC, iv)
byte_iv = bytearray(iv)
encrypted = bytearray(cipher.encrypt(self.pad(data).encode("utf8")))
data = base64.b64encode(bytes(byte_iv + encrypted))
data = list(data)
data = bytes(data)
Any help will be much appreciated.

Share Plex library in Dart

Hi I’m figuring out how to share Plex library in dart.
I'm helping myself with this working script in python ( it works)
https://gist.github.com/JonnyWong16/f8139216e2748cb367558070c1448636
unfortunately my code returns an http error 400, bad request
note: When I run the dart code there are no shared library.
maybe the payload is not correct :|
Thank for any help
import 'package:http/http.dart' as http;
class Server {
String token, ip, port;
Server(this.ip, this.port, this.token);
share() async {
var server_id = '00000000000000000000000000000000'; fake id
var library_section_ids = '97430074'; // right id , it works in python
var invited_id = '50819899'; // right id , it works in python
var headers = {
'Accept': 'application/json',
'X-Plex-Token': token,
};
var data =
'["server_id": $server_id,'
' "shared_server":["library_section_ids":[$library_section_ids],'
' "invited_id":$invited_id]';
var res = await http.post(
Uri.parse(
'https://plex.tv/api/servers/$server_id/shared_servers/'),
headers: headers,
body: data);
if (res.statusCode != 200) {
throw Exception('http.post error: statusCode= ${res.statusCode}');
}
print(res.body);
}
}
void main(List<String> arguments) async {
var srv = Server('xxx.yyy.xxx.yyy', '32400', '000000000-1111');
await srv.share();
}
The old code has a few bug and don't encode perfectly the data
I solved with 'dio' package and this link helped me a lot https://reqbin.com/
If the user has no shared library this code add a new one
import 'package:dio/dio.dart';
class Server {
String token;
Server(this.token);
test() async {
var serverId = '';
var librarySectionIds = ;
var invitedId = ;
var dio = Dio();
var data = {
"server_id": serverId,
"shared_server": {
"library_section_ids": librarySectionIds,
"invited_id": invitedId
}
};
dio.options.headers['Accept'] = 'application/json';
dio.options.headers["authorization"] = "Bearer $token";
var response = await dio.post(
'https://plex.tv/api/servers/$serverId/shared_servers/',
data: data);
print(response);
}

How to convert C# password hashing with salt to python for windows

How to convert below code in Python so that it gives same value on Windows even when executed multiple times.
Basically, it hashing password using sha512 and salt with 1000 iterations.
Here is the code:
using System;
using System.Security.Cryptography;
using System.Text;
namespace CheckHashing
{
class Program
{
protected static string CreateSHA512Hash(string Password, string Salt)
{
try
{
byte[] bytes_password = Encoding.UTF8.GetBytes(Password);
byte[] bytes_salt = Encoding.UTF8.GetBytes(Salt);
HashAlgorithm sha512hash = (HashAlgorithm)new SHA512CryptoServiceProvider();
for (int index = 0; index < 1000; ++index)
{
byte[] bytes_iteration = Encoding.UTF8.GetBytes(Convert.ToBase64String(bytes_password) + Convert.ToBase64String(bytes_salt));
bytes_password = sha512hash.ComputeHash(bytes_iteration);
}
return Convert.ToBase64String(bytes_password);
}
catch (Exception ex)
{
return "Exception"+ex.Message;
}
}
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
string hash_pwd = CreateSHA512Hash("Pass#21", "SALT(}");
Console.WriteLine(hash_pwd);
// Answer => HoCg9kKAl5WY0lWzvH7hdW+cTQGUfknALKDw49rvzUVUTt9X9fuggGpDIRfCdotR/kVU8m7gj2xzRzwIfDc5Xw==
}
}
}
Already tried below code which gives different values. Below output gives Invalid Password as error in the function.
import hashlib
from base64 import b64encode
password = "Pass#21"
salt = "SALT(}"
h = hashlib.pbkdf2_hmac('sha512', password.encode('utf-8'), salt.encode('utf-8'), 1000)
print(b64encode(h).decode())
# and below as well
hex_hash = hashlib.sha512(password.encode('utf-8') + salt.encode('utf-8')).digest()
for i in range(1000):
hex_hash = hashlib.sha512(hex_hash + salt.encode('utf-8')).digest()
print(b64encode(hex_hash).decode())
from passlib.hash import sha512_crypt as sha512
sha512_passwd = sha512.hash(password, rounds=1000)
print(sha512_passwd)
They don't start out the same.
If you add some prints to the C#
protected static string CreateSHA512Hash(string Password, string Salt)
{
try
{
byte[] bytes_password = Encoding.UTF8.GetBytes(Password);
byte[] bytes_salt = Encoding.UTF8.GetBytes(Salt);
HashAlgorithm sha512hash = (HashAlgorithm)new SHA512CryptoServiceProvider();
for (int index = 0; index < 1000; ++index)
{
if (index < 10)
Console.WriteLine(Convert.ToBase64String(bytes_password));
byte[] bytes_iteration = Encoding.UTF8.GetBytes(Convert.ToBase64String(bytes_password) + Convert.ToBase64String(bytes_salt));
bytes_password = sha512hash.ComputeHash(bytes_iteration);
}
Console.WriteLine("...");
return Convert.ToBase64String(bytes_password);
}
catch (Exception ex)
{
return "Exception" + ex.Message;
}
}
Here's my python port of the same code, with the same debug prints, so you can compare the first 10 values.
import hashlib
from base64 import b64encode
password = "Pass#21"
salt = "SALT(}"
bytes_password = password.encode('utf-8')
bytes_salt = salt.encode('utf-8')
for i in range(1000):
if i < 10:
print(b64encode(bytes_password).decode())
b64pw = b64encode(bytes_password).decode()
b64sa = b64encode(bytes_salt).decode()
bytes_iteration = (b64pw + b64sa).encode('utf-8')
bytes_password = hashlib.sha512(bytes_iteration).digest()
print('...')
print(b64encode(bytes_password).decode())
Your original code wasn't consistent on when it hex encoded and when it computed the hash, and it computed a hash prior to entering the loop.

converting python dict to protobuf

How can I convert the following dict to protobuf ?
I have to send a protobuf as a payload to an mqtt broker.
I'm using python 3.8
publish_msg = {
"token":"xxxxxxxx",
"parms":{
"fPort":8,
"data":b"MDQzYzAwMDE=",
"confirmed":False,
"devEUI":"8CF9572000023509"
}
}
My protobuf is defined as follows:
syntax = "proto3";
package publish;
message DLParams{
string DevEUI = 1;
int32 FPort = 2;
bytes Data = 3;
bool Confirm = 4;
}
message DeviceDownlink {
string Token = 1;
DLParams Params = 2;
}
How about this?
import json
from google.protobuf import json_format
# Create an empty message
dl = DeviceDownlink_pb2.DeviceDownlink()
# Get the json string for your dict
json_string = json.dumps(publish_msg)
# Put the json contents into your message
json_format.Parse(json_string, dl)

python AES Encrypt

I am new in python/django. I want to use AES Encryption.
after search I found some libraries like this: https://gist.github.com/jeetsukumaran/1291836
but I could not use them because of I have IV but this dont have IV code.
I have sample code in c#. any one may help me to convert this code to python code?
using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace AESUtility {
public class AES {
string AES_Key = string.Empty;
string AES_IV = string.Empty;
public AES(string AES_Key, string AES_IV) {
this.AES_Key = AES_Key;
this.AES_IV = AES_IV;
}
public bool Encrypt(String Input, out string encryptedString) {
try {
var aes = new RijndaelManaged();
aes.KeySize = 256;
aes.BlockSize = 256;
aes.Padding = PaddingMode.PKCS7;
aes.Key = Convert.FromBase64String(this.AES_Key);
aes.IV = Convert.FromBase64String(this.AES_IV);
var encrypt = aes.CreateEncryptor(aes.Key, aes.IV);
byte[] xBuff = null;
using(var ms = new MemoryStream()) {
using(var cs = new CryptoStream(ms, encrypt, CryptoStreamMode.Write)) {
byte[] xXml = Encoding.UTF8.GetBytes(Input);
cs.Write(xXml, 0, xXml.Length);
}
xBuff = ms.ToArray();
}
encryptedString = Convert.ToBase64String(xBuff);
return true;
} catch (Exception ex) {
encryptedString = string.Empty;
return false;
}
}
public bool Decrypt(String Input, out string decodedString) {
try {
RijndaelManaged aes = new RijndaelManaged();
aes.KeySize = 256;
aes.BlockSize = 256;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
aes.Key = Convert.FromBase64String(this.AES_Key);
aes.IV = Convert.FromBase64String(this.AES_IV);
var decrypt = aes.CreateDecryptor();
byte[] xBuff = null;
using(var ms = new MemoryStream()) {
using(var cs = new CryptoStream(ms, decrypt, CryptoStreamMode.Write)) {
byte[] xXml = Convert.FromBase64String(Input);
cs.Write(xXml, 0, xXml.Length);
}
xBuff = ms.ToArray();
}
decodedString = Encoding.UTF8.GetString(xBuff);
return true;
} catch (Exception ex) {
decodedString = string.Empty;
return false;
}
}
}
}
EDIT 2022
pycrypto is now probably unmaintained. Latest release was in Oct 2013 (see https://pypi.org/project/pycrypto/#history)
In modern projects, use pycryptodome instead. The official documentation gives example of AES encryption: https://www.pycryptodome.org/en/latest/src/examples.html#encrypt-data-with-aes
Original answer:
Here is an example of AES encryption using well known pycrypto library:
>>> from Crypto.Cipher import AES
>>> obj = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
>>> message = "The answer is no"
>>> ciphertext = obj.encrypt(message)
>>> ciphertext
'\xd6\x83\x8dd!VT\x92\xaa`A\x05\xe0\x9b\x8b\xf1'
>>> obj2 = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
>>> obj2.decrypt(ciphertext)
'The answer is no'
AES 256 in OFB mode:
from Crypto.Cipher import AES
from Crypto.Random import new as Random
from hashlib import sha256
from base64 import b64encode,b64decode
class AESCipher:
def __init__(self,data,key):
self.block_size = 16
self.data = data
self.key = sha256(key.encode()).digest()[:32]
self.pad = lambda s: s + (self.block_size - len(s) % self.block_size) * chr (self.block_size - len(s) % self.block_size)
self.unpad = lambda s: s[:-ord(s[len(s) - 1:])]
def encrypt(self):
plain_text = self.pad(self.data)
iv = Random().read(AES.block_size)
cipher = AES.new(self.key,AES.MODE_OFB,iv)
return b64encode(iv + cipher.encrypt(plain_text.encode())).decode()
def decrypt(self):
cipher_text = b64decode(self.data.encode())
iv = cipher_text[:self.block_size]
cipher = AES.new(self.key,AES.MODE_OFB,iv)
return self.unpad(cipher.decrypt(cipher_text[self.block_size:])).decode()
Usage:
AESCipher("data to encrypt","key to use").encrypt()
AESCipher("encrypted data","key to use").decrypt()

Categories

Resources