【发布时间】:2020-03-22 00:37:37
【问题描述】:
我试图通过 api 从我的逆变器中读取传感器数据。 (Kostal PLENTICORE plus)
由于 Kostal 缺乏文档,我没有让它工作。身份验证是这里的大问题。但我刚刚从 Openhab 找到了代码。
ThirdGenerationEncryptionHelper
ThirdGenerationHandler
现在我试图将它尽可能简单地移植到 python。
我现在的代码:
import requests
import random
import string
import json
import hashlib
import hmac
import hashlib
import binascii
def randomString(stringLength=10):
"""Generate a random string of fixed length """
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(stringLength))
def getPBKDF2Hash(password, salt, rounds):
key = hashlib.pbkdf2_hmac(
'sha256', # The hash digest algorithm for HMAC
password.encode('utf-8'), # Convert the password to bytes
salt, # Provide the salt
rounds # It is recommended to use at least 100,000 iterations of SHA-256
)
return key
def create_sha256_signature(byte_key, message):
#byte_key = binascii.unhexlify(key)
message = message.encode()
return hmac.new(byte_key, message, hashlib.sha256).hexdigest().upper()
def createClientProof(clientSignature, serverSignature):
clientlength = len(clientSignature.encode('utf-8'))
result = []
#for i in range(clientlength):
# result[i] = (0xff & (bytes(clientSignature[i]) ^ bytes(serverSignature[i])))
return result**
username="user"
password= "A123456789"
url = 'http://192.168.1.23/api/v1/'
clientNonce = randomString(16)
reqstart = {"username": username, "nonce": clientNonce}
a = requests.post(url+'auth/start', json=reqstart)
anserstart = json.loads(a.text)
serverNonce = anserstart['nonce']
transactionId = anserstart['transactionId']
salt = anserstart['salt']
rounds = anserstart['rounds']
saltedpassword = getPBKDF2Hash(password, salt, rounds)
clientkey = create_sha256_signature(saltedpassword, "Client Key")
serverkey = create_sha256_signature(saltedpassword, "Server Key")
storedKey = hashlib.sha256(clientkey).hexdigest()
authMessage = "n={},r={},r={},s={},i={},c=biw,r={}"
authMessage.format(username, clientNonce, serverNonce, salt, rounds, serverNonce)
clientSignature = create_sha256_signature(storedKey, authMessage)
serverSignature = create_sha256_signature(storedKey, serverkey)
print(anserstart)
#print(saltedpassword)
#print(clientkey)
#print(serverkey)
#print(storedKey)
print(clientSignature)
print(serverSignature)
print(createClientProof(clientSignature,serverSignature))
#reqfinish = {"proof": "", "transactionId": transactionId}
#b = requests.post(url+'auth/start', json=reqfinish)
#answerfinish = json.loads(b.text)
#print(answerfinish)
现在我的问题:
我坚持创建客户证明(函数 createClientProof)。有人可以帮我像在 java 中那样做 XOR 吗?
除此之外,我在加密或这种身份验证方面没有太多经验。谁能告诉我我做的那个员工是否正确?
原件:
/**
* This method generates the HMACSha256 encrypted value of the given value
*
* @param password Password used for encryption
* @param valueToEncrypt value to encrypt
* @return encrypted value
* @throws InvalidKeyException thrown if the key generated from the password is invalid
* @throws NoSuchAlgorithmException thrown if HMAC SHA 256 is not supported
*/
static byte[] getHMACSha256(byte[] password, String valueToEncrypt)
throws InvalidKeyException, NoSuchAlgorithmException {
SecretKeySpec signingKey = new SecretKeySpec(password, HMAC_SHA256_ALGORITHM);
Mac mac = Mac.getInstance(HMAC_SHA256_ALGORITHM);
mac.init(signingKey);
mac.update(valueToEncrypt.getBytes());
return mac.doFinal();
}
/**
* This methods generates the client proof.
* It is calculated as XOR between the {@link clientSignature} and the {@link serverSignature}
*
* @param clientSignature client signature
* @param serverSignature server signature
* @return client proof
*/
static String createClientProof(byte[] clientSignature, byte[] serverSignature) {
byte[] result = new byte[clientSignature.length];
for (int i = 0; i < clientSignature.length; i++) {
result[i] = (byte) (0xff & (clientSignature[i] ^ serverSignature[i]));
}
return Base64.getEncoder().encodeToString(result);
}
/**
* Create the PBKDF2 hash
*
* @param password password
* @param salt salt
* @param rounds rounds
* @return hash
* @throws NoSuchAlgorithmException if PBKDF2WithHmacSHA256 is not supported
* @throws InvalidKeySpecException if the key specification is not supported
*/
static byte[] getPBKDF2Hash(String password, byte[] salt, int rounds)
throws NoSuchAlgorithmException, InvalidKeySpecException {
PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, rounds, 256);
SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
return skf.generateSecret(spec).getEncoded();
}
/**
* Create the SHA256 hash value for the given byte array
*
* @param valueToHash byte array to get the hash value for
* @return the hash value
* @throws NoSuchAlgorithmException if SHA256 is not supported
*/
static byte[] getSha256Hash(byte[] valueToHash) throws NoSuchAlgorithmException {
return MessageDigest.getInstance(SHA_256_HASH).digest(valueToHash);
}
感谢您的帮助
【问题讨论】:
-
你能发布你的相关代码的sn-ps而不是存储库的链接吗?
-
原因,完成。