I'm trying to generate the same password hash using NodeJS crypto library and C# Rfc2898DeriveBytes. The NodeJs implementation doesn't generate the same key when using the salt generated from C#. What am I doing wrong?
In C#:
public static string HashPassword(string password)
{
// random khóa
using (var rngCryp = new RNGCryptoServiceProvider())
{
var salt = new byte[SaltBytes];
rngCryp.GetBytes(salt);
// Hash the password and encode the parameters
byte[] hash = Rfc2898Deriver(password, salt, Pbkdf2Iterations, HashBytes);
return Pbkdf2Iterations + ":" + Convert.ToBase64String(salt) + ":" + Convert.ToBase64String(hash);
}
}
private static byte[] Rfc2898Deriver(string password, byte[] salt, int iterations, int outputMaxByte)
{
using (var deriveBytes = new Rfc2898DeriveBytes(password, salt))
{
deriveBytes.IterationCount = iterations;
return deriveBytes.GetBytes(outputMaxByte);
}
}
In NodeJs:
export const hash = (text, salt) => new Promise((resolve, reject) => {
crypto.pbkdf2(text, salt, iterations, bytes, 'sha256', function (err, derivedKey) {
if (err) { reject(err) }
else {
//return Pbkdf2Iterations + ":" + Convert.ToBase64String(salt) + ":" + Convert.ToBase64String(hash);
var hash = new Buffer(derivedKey).toString('base64');
var pass = `${iterations}:${salt}:${hash}`
resolve(pass);
}});})
and use like that:
var a = Buffer.from("qcMqVYE0EzAU9Uz+mQxBaKFICG1vR1iq", 'base64')
var a0 = new Buffer("qcMqVYE0EzAU9Uz+mQxBaKFICG1vR1iq")
var pas1 = new Buffer('AL7h8Jx4r8a8PjS5', 'base64')
hash(pas1,a0).then(pass => {
console.log("pass: ", pass)
const hashes = crypto.getHashes();
console.log(hashes); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]
res.send(pass + "\n1000:qcMqVYE0EzAU9Uz+mQxBaKFICG1vR1iq:RkdpgAcpijFqYgVxBCvJugMXqnt4j5f3")
})
As you see, hass pass in C# and Nodejs is different.
Node ->
1000:qcMqVYE0EzAU9Uz+mQxBaKFICG1vR1iq:D19SUxg6AQxgSLe7YXISPWPvgIoR6BEw
C# ->
1000:qcMqVYE0EzAU9Uz+mQxBaKFICG1vR1iq:RkdpgAcpijFqYgVxBCvJugMXqnt4j5f3
I had a very similar question and actually your findings helped me a lot.
Looks like the only problem you had is the wrong hashing algorithm that you passed to pbkdf2 function.
Looks like Rfc2898DeriveBytes uses SHA1 by default. So you should have used the smth like that in node:
crypto.pbkdf2(text, salt, iterations, bytes, 'sha1', (err, key) => {
console.log(key.toString('hex'));
});
Here i entered fix salt, you can also generate random string of 16. You can change length also instead of mine "32".
var crypto = require('crypto');
salt = '1234123412341234';
saltString = new Buffer(salt).toString('hex');
var password = 'welcome';
var nodeCrypto = crypto.pbkdf2Sync(new Buffer(password), new Buffer(saltString, 'hex'), 1000, 32, 'sha1');
var hashInHex="00"+saltString+nodeCrypto.toString('hex').toUpperCase();
var FinalHash = Buffer.from(hashInHex, 'hex').toString('base64')
console.log("saltInHex: "+saltString);
console.log("FinalHashInBase64: "+FinalHash);
To match stored hash password with user inpur password use bellow code :
// NodeJS implementation of crypto, I'm sure google's
// cryptoJS would work equally well.
var crypto = require('crypto');
// The value stored in [dbo].[AspNetUsers].[PasswordHash]
var hashedPwd = "AGYzaTk3eldHaXkxbDlkQmn+mVJZEjd+0oOcLTNvSQ+lvUQIF1u1CNMs+WjXEzOYNg==";
var hashedPasswordBytes = new Buffer(hashedPwd, 'base64');
var hexChar = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"];
var saltString = "";
var storedSubKeyString = "";
// build strings of octets for the salt and the stored key
for (var i = 1; i < hashedPasswordBytes.length; i++) {
if (i > 0 && i <= 16) {
saltString += hexChar[(hashedPasswordBytes[i] >> 4) & 0x0f] + hexChar[hashedPasswordBytes[i] & 0x0f]
}
if (i > 0 && i > 16) {
storedSubKeyString += hexChar[(hashedPasswordBytes[i] >> 4) & 0x0f] + hexChar[hashedPasswordBytes[i] & 0x0f];
}
}
// password provided by the user
var password = 'vish#123';
// TODO remove debug - logging passwords in prod is considered
// tasteless for some odd reason
console.log('cleartext: ' + password);
console.log('saltString: ' + saltString);
console.log('storedSubKeyString: ' + storedSubKeyString);
// This is where the magic happens.
// If you are doing your own hashing, you can (and maybe should)
// perform more iterations of applying the salt and perhaps
// use a stronger hash than sha1, but if you want it to work
// with the [as of 2015] Microsoft Identity framework, keep
// these settings.
var nodeCrypto = crypto.pbkdf2Sync(new Buffer(password), new Buffer(saltString, 'hex'), 1000, 256, 'sha1');
// get a hex string of the derived bytes
var derivedKeyOctets = nodeCrypto.toString('hex').toUpperCase();
console.log("hex of derived key octets: " + derivedKeyOctets);
// The first 64 bytes of the derived key should
// match the stored sub key
if (derivedKeyOctets.indexOf(storedSubKeyString) === 0) {
console.info("passwords match!");
} else {
console.warn("passwords DO NOT match!");
}
Related
I’m encrypting sensitive data using the C# AES class, Aes.Create() method before saving to an SQLite DB. My base round trip is:
*Saving/retrieving each Byte[ ] without converting threw “The specified key is not a valid size for this algorithm.” when decrypting.
The process leverages the MSDN example and is working well:
I’m concerned, however, that cipher, key & IV values must all be stored/retrieved together and am attempting to disguise the values stored in the DB. I’ve tried three procedures to disguise/revert the relevant string values. Unfortunately adding a disguise/revert procedure throws the following error when decrypting:
System.Security.Cryptography.CryptographicException
HResult=0x80131430 Message=Padding is invalid and cannot be removed.
Source=System.Core
I've tried:
switching from Aes.Create to AesManaged; result: no change
setting Padding = PaddingMode.None; result: threw "'System.Security.Cryptography.CryptographicException' occurred in mscorlib.dll 'Length of the data to encrypt is invalid.'"
setting Padding = PaddingMode.Zeros; result: ran with no error but round trips returned incorrect & unreadable values (see image):
A number of posts (of the many, most of the issues are base process round trip failures) in this forum regarding this error state that the Padding error can be thrown for a variety of reasons only one of which is actually a Padding error. One post ( Padding is invalid and cannot be removed?, 4th reply sorted by Trending) states:
If the same key and initialization vector are used for encoding and
decoding, this issue does not come from data decoding but from data
encoding.
Since my keys & IVs are the same this looked hopeful. However, as the above image implies if I'm interpreting it correctly, changing encoding doesn't seem to help.
Since my base processs by itself works I suspect my case fall into the "not really a Padding error" category.
The disguise/revert procedures
First procedure
Remove the “=” character(s) at the end of each string since it’s a blatant indicator of “something important”
Split cipher, key & IV strings based on a random number into two halves
Swap the two halves’ positions and insert unique random text of random length between the halves
Create a random length “reversion code” capturing randomized split indices and resultant string lengths
Second procedure: same as the first but leave “=” character(s) intact.
Third procedure
Split the random text of three different random length strings
“Wrap” them around the cipher, key & IV strings
Create the “reversion code”
For all three procedures: upon retrieval from the DB reverse the process using the “reversion code”. In the third procedure the original strings should, theoretically, be “untouched”.
In all three cases output indicates Original and Reverted are identical (single run testing output sample):
The disguise/revert code
Code for the third procedure since it probably has the greatest probability of working. The Encrypt & Decrypt methods are included in case they're relevant:
private static string _cipherText = "", _keyText = "", _vectorText = "";
// Prior to saving: third procedure
public static void SaveSensitivePrep(string input, bool parent)
{
input = "secretID";
Console.WriteLine($"\nOriginal: {input}");
string startString = default, extractor = default;
int disguiseLen = 0, startStringLen = 0, doneStringLen = 0;
for (int i = 0; i < 3; i++)
{
using (Aes toEncrypt = Aes.Create())
{
byte[] cypherBytes = Encrypt(input, toEncrypt.Key, toEncrypt.IV);
string cipherText = Convert.ToBase64String(cypherBytes);
string keyText = Convert.ToBase64String(toEncrypt.Key);
string vectorText = Convert.ToBase64String(toEncrypt.IV);
if (i == 0) _cipherText = startString = cipherText;
else if (i == 1) _keyText = startString = keyText;
else if (i == 2) _vectorText = startString = vectorText;
int disguiseSelector = new Random().Next(101);
string disguiseTxt = default;
List<Disguises> disguise_DB = DBconnect.Disguises_Load();
for (int c = 0; c < disguise_DB.Count; c++)
{
if (c == disguiseSelector) { disguiseTxt = disguise_DB[c].Linkages; break; }
}
disguiseLen = disguiseTxt.Length;
int disguiseSplitIndex = new Random().Next(10, 22);
string startTxt = disguiseTxt.Substring(0, disguiseSplitIndex);
string endTxt = disguiseTxt.Substring(disguiseSplitIndex);
string doneString = $"{startTxt}{startString}{endTxt}";
doneStringLen = doneString.Length;
extractor = $"{disguiseSplitIndex}{disguiseLen}{startStringLen}" +
$"{disguiseSelector + new Random().Next(5000000)}";
if (i == 0) DBconnect.Encrypted_Update_CT(Host, extractor, doneString);
else if (i == 1) DBconnect.Encrypted_Update_CK(Host, extractor, doneString);
else if (i == 2) DBconnect.Encrypted_Update_CV(Host, extractor, doneString);
}
}
}
// After retrieval: third procedure
public static string LoadSensitive(string input, bool parent)
{
string cipherText = "", keyText = "", vectorText = "";
for (int i = 0; i < 3; i++)
{
string extractor = "";
int disguiseLeft, disguiseRight;
List<EncryptedClass> host = DBconnect.Encrypted_Load(Host);
string doneString = "";
if (i == 0) { extractor = host[0].RCC; doneString = host[0].cipherText; }
else if (i == 1) { extractor = host[0].RCK; doneString = host[0].keyText; }
else if (i == 2) { extractor = host[0].RCV; doneString = host[0].vectorText; }
string disguiseSplitter = extractor.Substring(0, 2);
string disguiseLen_t = extractor.Substring(2, 2);
string startStringLen_t = extractor.Substring(4, 2);
int.TryParse(disguiseSplitter, out int indx);
int.TryParse(disguiseLen_t, out int disguiseLen);
int.TryParse(startStringLen_t, out int startStringLen);
disguiseRight = disguiseLen - indx;
disguiseLeft = disguiseLen - disguiseRight;
string e_extrctd = doneString.Substring(disguiseLeft, startStringLen);
if (i == 0) cipherTxt = revertedString;
else if (i == 1) keyTxt = revertedString;
else vectorTxt = revertedString;
}
byte[] cypher = Convert.FromBase64String(cipherText);
byte[] key = Convert.FromBase64String(keyText);
byte[] vector = Convert.FromBase64String(vectorText);
return Decrypt(cypher, key, vector);
}
static byte[] Encrypt(string input, byte[] key, byte[] iv)
{
// NULL/Length > 0 checks.
byte[] encrypted;
using (Aes input_e = Aes.Create())
{
input_e.Key = key;
input_e.IV = iv;
ICryptoTransform ict = input_e.CreateEncryptor(input_e.Key, input_e.IV);
using (MemoryStream msInput = new MemoryStream())
{
using (CryptoStream csInput = new CryptoStream(msInput, ict, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csInput))
{
swEncrypt.Write(input);
}
encrypted = msInput.ToArray();
}
}
}
return encrypted;
}
static string Decrypt(byte[] cipherText, byte[] keyText, byte[] vectorText)
{
// NULL/Length > 0 checks.
string roundtrip = null;
using (Aes output_e = Aes.Create())
{
output_e.Key = keyText;
output_e.IV = vectorText;
ICryptoTransform ict = output_e.CreateDecryptor(output_e.Key, output_e.IV);
using (MemoryStream msOutput = new MemoryStream(cipherText))
{
using (CryptoStream csOutput = new CryptoStream(msOutput, ict, CryptoStreamMode.Read))
{
using (StreamReader srOutput = new StreamReader(csOutput))
{
roundtrip = srOutput.ReadToEnd();
}
}
}
}
return roundtrip;
}
Any guidance on how/why the disguise/revert is getting deformed will be appreciated.
EDIT: scope clarification: the security functionality in this instance is for a Winforms/SQLite app which has an FTP component (WinSCP). The app's high level objective is a desktop tool streamlining TLS/SSL Certificate request/issuance via Let's Encrypt. The primary security objective is protecting FTP session credentials should an unauthorized & semi-knowledgeable person gain access to the DB. The secondary security objective is to keep it as simple as possible.
I am sending requests to Kraken api using a private key. The problem is, generated signature is not as expected.
Please note that the key you can see below it's just a sample. But it should generate the expected output. If so, that means the code is correct and it would work with an actual key.
The goal is to perform the following encryption:
HMAC-SHA512 of (URI path + SHA256(nonce + POST data)) and base64 decoded secret API key
So far, I've written this code:
public class KrakenApi
{
private static string ApiPrivateKey = "kQH5HW/8p1uGOVjbgWA7FunAmGO8lsSUXNsu3eow76sz84Q18fWxnyRzBHCd3pd5nE9qa99HAZtuZuj6F1huXg==";
public static string GetKrakenSignature(string urlPath, ulong nonce, Dictionary<string,string> data)
{
var hash256 = new SHA256Managed();
var postData = string.Join("&", data.Select(e => e.Key + "=" + e.Value).ToArray());
var encoded = Encoding.UTF8.GetBytes(nonce + postData);
var message = Encoding.UTF8.GetBytes(urlPath).Concat(hash256.ComputeHash(encoded).ToArray());
var secretDecoded = (System.Convert.FromBase64String(ApiPrivateKey));
var hmacsha512 = new HMACSHA512(secretDecoded);
var hash = hmacsha512.ComputeHash(secretDecoded.Concat(message).ToArray());
return System.Convert.ToBase64String(hash);
}
}
Usage:
var data = new Dictionary<string, string> {
{ "nonce", "1616492376594" },
{ "ordertype", "limit" },
{ "pair", "XBTUSD" },
{ "price", "37500" },
{ "type", "buy" },
{ "volume", "1.25" }
};
var signature = KrakenApi.GetKrakenSignature("/0/private/AddOrder", ulong.Parse(data["nonce"]), data);
Console.WriteLine(signature);
Output should be:
4/dpxb3iT4tp/ZCVEwSnEsLxx0bqyhLpdfOpc6fn7OR8+UClSV5n9E6aSS8MPtnRfp32bAb0nmbRn6H8ndwLUQ==
There are a number of code samples for Phyton, Node and Golang here that work correctly. But above code in C# not generating expected output.
This generates the expected output. Finally I've read Python documentation for each method used in the code sample and reproduced the same steps in C#.
public static string GetKrakenSignature(string urlPath, ulong nonce, Dictionary<string,string> data)
{
var hash256 = new SHA256Managed();
var postData = string.Join("&", data.Select(e => e.Key + "=" + e.Value).ToArray());
var encoded = Encoding.UTF8.GetBytes(nonce + postData);
var message = Encoding.UTF8.GetBytes(urlPath).Concat(hash256.ComputeHash(encoded)).ToArray();
var mac = new HMACSHA512(Convert.FromBase64String(ApiPrivateKey));
return Convert.ToBase64String(mac.ComputeHash(message));
}
Here's what I have so far. The commented out parts are C# code from Microsofts website that I have been trying to convert.
import CryptoKit
func GenerateSasToken(resourceUri: String, key: String, policyName: String = "", expiryInSeconds: Int = 3600) -> String?
{
// TimeSpan sinceEpoch = DateTime.UtcNow - new DateTime(1970, 1, 1);
let fromEpochStart = Date().timeIntervalSince1970
let expiry = Int(fromEpochStart) + expiryInSeconds
// string stringToSign = HttpUtility.UrlEncode(resourceUri) + "\n" + expiry;
guard let encodedResourceUri = resourceUri.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) else { return nil }
let stringToSign = "\(encodedResourceUri)\n\(expiry)"
// HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key));
guard let base64Key = key.data(using: .utf8) else { return nil }
let symmetricKey = SymmetricKey(data: base64Key)
let hmac = HMAC<SHA256>.init(key: symmetricKey)
// var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
// var sasToken = String.Format(CultureInfo.InvariantCulture, "SharedAccessSignature sr={0}&sig={1}&se={2}&skn={3}", HttpUtility.UrlEncode(resourceUri), HttpUtility.UrlEncode(signature), expiry, keyName);
// return sasToken;
return ""
}
https://learn.microsoft.com/en-us/rest/api/eventhub/generate-sas-token
I'm slowly converting through the C# code and was just wondering if someone has this converted to swift already.
Its bad idea to generate sas token on client side since you will need to compile with your storage keys then attacker decompile your app and get keys which will give them access to your storage/event hub and so on. That's is actually idea behind SAS token, so client app request short living and limited token to perform operation usually just a single one.
I managed to convert the code to Swift but, I was informed that this is a bad idea due to security reasons and it makes sense. I'll still provide the converted code here for anyone that needs it.
import UIKit
import CryptoKit
extension String {
var hex: Data? {
var value = self
var data = Data()
while value.count > 0 {
let subIndex = value.index(value.startIndex, offsetBy: 2)
let c = String(value[..<subIndex])
value = String(value[subIndex...])
var char: UInt8
if #available(iOS 13.0, *) {
guard let int = Scanner(string: c).scanInt32(representation: .hexadecimal) else { return nil }
char = UInt8(int)
} else {
var int: UInt32 = 0
Scanner(string: c).scanHexInt32(&int)
char = UInt8(int)
}
data.append(&char, count: 1)
}
return data
}
}
func generateSasToken(resourceUri: String, key: String, policyName: String = "", expiryInSeconds: Int = 3600) -> String? {
let fromEpochStart = Date().timeIntervalSince1970
let expiry = Int(fromEpochStart) + expiryInSeconds
guard let encodedResourceUri = resourceUri.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) else { return nil }
let stringToSign = "\(encodedResourceUri)\n\(expiry)"
guard let stringToSignData = stringToSign.data(using: .utf8) else { return nil }
guard let keyData = Data(base64Encoded: key) else { return nil }
let symmetricKey = SymmetricKey(data: keyData)
let hmac = HMAC<SHA256>.authenticationCode(for: stringToSignData, using: symmetricKey)
guard let hexString = hmac.description.split(separator: " ", maxSplits: .max, omittingEmptySubsequences: true).last?.description else { return nil }
let hex = hexString.hex
let unreserved = "-._~&"
let allowed = NSMutableCharacterSet.alphanumeric()
allowed.addCharacters(in: unreserved)
guard let signature = hex?.base64EncodedString().addingPercentEncoding(withAllowedCharacters: allowed as CharacterSet) else { return nil }
let SasUrl = "sr=\(encodedResourceUri)&sig=\(signature)&se=\(expiry)"
let sasToken = "SharedAccessSignature " + SasUrl
return sasToken
}
I have to rewrite this php code to c#
$sign_params = ['name'=>"John", 'age'=>18];
$client_secret = 'test secret key';
ksort($sign_params); // Sort array by keys
$sign_params_query = http_build_query($sign_params); // Forming string like "param_name1=value¶m_name2=value"
$sign = rtrim(strtr(base64_encode(hash_hmac('sha256', $sign_params_query, $client_secret, true)), '+/', '-_'), '='); // get hash code
return $sign;
Here what I try:
public class apiHelper : MonoBehaviour
{
const string client_secret = "test secret key";
public static string checkSign(Dictionary<string, dynamic> fields)
{
//* sort by keys
var list = fields.Keys.ToList();
list.Sort();
string sign_params_query = "";
//* forming string like "param_name1=value¶m_name2=value"
foreach (var key in list)
{
sign_params_query = sign_params_query + key + "=" + fields[key];
if (key != list.Last()) sign_params_query = sign_params_query + "&";
}
//* get hash code
string sign = System.Convert.ToBase64String(GetHash(sign_params_query, client_secret));
char[] charsToTrim = { '=' };
return sign.Replace("+", "-").TrimEnd(charsToTrim);
}
static byte[] GetHash(string url, string key)
{
using (HMACSHA256 hmac = new HMACSHA256(Encoding.ASCII.GetBytes(key)))
{
byte[] data = hmac.ComputeHash(Encoding.UTF8.GetBytes(url));
return data;
}
}
}
Well, finally I get different hash than in php example ._. What did I wrong? Its my 1st time with cryptho or smth like that
Well, problem wath with strings which have special chars. I have to use url_encode c# equivalent to solve it.
I'm trying to decrypt a message using Elliptic Curve Cryptograph ECDiffieHellman using KDFX963 as a key derivation function (KDF) (defined in ANSI-X9.63-KDF http://www.secg.org/sec1-v2.pdf)
But I'm struggling to get this done.
I pretty much need a method like :
DecryptMessage(string tokenFromPayload, string publicKeyStr, string privateKeyStr){
// Generate an ephemeral key from the public and private key
// Decrypt payload with the ephemeral key
}
Some extra information about the algorithm to decrypt the message :
Elliptic Curve : SECP384R1 ; NamedCurves.brainpoolP384r1
Cipher : AES Mode:GCM
Cipher Key Size : 32
Mac Size = 16
Key Derivation Function : ANSI-X9.63-KDF
Hash : Sha256 (lenght 32)
I have the Python code below that is doing what I need to decrypt the message, but I need this in C#.
import base64
import binascii
import json
import os
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.ciphers import algorithms, Cipher, modes
from cryptography import utils
from hashlib import sha256
from math import ceil
class BCAuthCrypto:
"""A class containing a number of handlers for the secp384r1 ECC algorithm in Python"""
curve = ec.SECP384R1()
cipher_key_size = 32
mac_size = 16
backend = default_backend()
def ITOSP(self, longint, length):
"""ITOSP, short for Integer-to-Octet-String Primitive, converts a non-negative integer
to an octet string of a specified length. This particular function is defined in the
PKCS #1 v2.1: RSA Cryptography Standard (June 14, 2002)
https://www.cryptrec.go.jp/cryptrec_03_spec_cypherlist_files/PDF/pkcs-1v2-12.pdf"""
hex_string = "%X" % longint
assert len(hex_string) <= 2 * length, "ITOSP function: Insufficient length for encoding"
return binascii.a2b_hex(hex_string.zfill(2 * length))
def KDFX963(self, inbyte_x, shared_data, key_length, hashfunct=sha256, hash_len=32):
"""KDFX963 is a key derivation function (KDF) that takes as input byte sequence inbyte_x
and additional shared data shared_data and outputs a byte sequence key of length
key_length. This function is defined in ANSI-X9.63-KDF, and this particular flavor of
KDF is known as X9.63. You can read more about it from:
http://www.secg.org/sec1-v2.pdf"""
assert key_length >= 0, "KDFX963 function: key_length should be positive integer"
k = key_length / float(hash_len)
k = int(ceil(k))
acc_str = ""
for i in range(1, k+1):
h = hashfunct()
h.update(inbyte_x)
h.update(self.ITOSP(i, 4))
h.update(shared_data)
acc_str = acc_str + h.hexdigest()
return acc_str[:key_length * 2]
def decrypt(self, cipher_text_b64, private_key):
"""Decrypt takes input base64-encoded data input cipher_text_b64 and private key
private_key and outputs plain text data, throws exception on error"""
cipher = base64.b64decode(cipher_text_b64)
ephemeral_key_len = ((self.curve.key_size + 7) // 8) * 2 + 1
ephemeral_key_numbers = ec.EllipticCurvePublicNumbers.from_encoded_point(self.curve, cipher[:ephemeral_key_len])
ephemeral_key = ephemeral_key_numbers.public_key(self.backend)
shared_key = private_key.exchange(ec.ECDH(), ephemeral_key)
V = cipher[:ephemeral_key_len]
K = binascii.unhexlify(self.KDFX963(shared_key, V, self.cipher_key_size + self.mac_size))
K1 = K[:self.cipher_key_size]
K2 = K[self.cipher_key_size:]
T = cipher[ephemeral_key_len:]
enc_data = T[:len(T) - self.mac_size]
tag = T[-self.mac_size:]
decryptor = Cipher(algorithms.AES(K1), modes.GCM(K2, tag), backend=self.backend).decryptor()
plain_text = decryptor.update(enc_data) + decryptor.finalize()
return plain_text
def decrypt_auth_token(tokenFromPayload, public_key_str, private_key_str):
"""Retrive the auth token and decrypt it, in a way that does not specify the name of the service."""
bc_crypto = BCAuthCrypto()
public_number = ec.EllipticCurvePublicNumbers.from_encoded_point(bc_crypto.curve, base64.b64decode(public_key_str))
private_number = ec.EllipticCurvePrivateNumbers(utils.int_from_bytes(base64.b64decode(private_key_str), "big"), public_number)
private_key = private_number.private_key(bc_crypto.backend)
token = bc_crypto.decrypt(tokenFromPayload, private_key)
print "token (decrypted): %s" % token
return token
Hoping there is a cryptography genius guy out there to help me, or a "Python To C#" expert.
Thanks.
Got my answer there Decrypt Apple Business Chat auth token
namespace AppleBusinessChat45
{
class Program
{
static void Main(string[] args)
{
var privateKey = "pX/BvdXXUdpC79mW/jWi10Z6PJb5SBY2+aqkR/qYOjqgakKsqZFKnl0kz10Ve+BP";
var token = "BDiRKNnPiPUb5oala31nkmCaXMB0iyWy3Q93p6fN7vPxEQSUlFVsInkJzPBBqmW1FUIY1KBA3BQb3W3Qv4akZ8kblqbmvupE/EJzPKbROZFBNvxpvVOHHgO2qadmHAjHSmnxUuxrpKxopWnOgyhzUx+mBUTao0pcEgqZFw0Y/qZIJPf1KusCMlz5TAhpjsw=";
// #####
// ##### Step 1
// #####
var decodedToken = Convert.FromBase64String(token);
var decodedEphemeralPublicKey = decodedToken.Take(97).ToArray();
var encodedEphemeralPublicKeyCheck = Convert.ToBase64String(decodedEphemeralPublicKey);
if (encodedEphemeralPublicKeyCheck != "BDiRKNnPiPUb5oala31nkmCaXMB0iyWy3Q93p6fN7vPxEQSUlFVsInkJzPBBqmW1FUIY1KBA3BQb3W3Qv4akZ8kblqbmvupE/EJzPKbROZFBNvxpvVOHHgO2qadmHAjHSg==")
throw new Exception("Public key check failed");
X9ECParameters curveParams = ECNamedCurveTable.GetByName("secp384r1");
ECPoint decodePoint = curveParams.Curve.DecodePoint(decodedEphemeralPublicKey);
ECDomainParameters domainParams = new ECDomainParameters(curveParams.Curve, curveParams.G, curveParams.N, curveParams.H, curveParams.GetSeed());
ECPublicKeyParameters ecPublicKeyParameters = new ECPublicKeyParameters(decodePoint, domainParams);
var x = ecPublicKeyParameters.Q.AffineXCoord.ToBigInteger();
var y = ecPublicKeyParameters.Q.AffineYCoord.ToBigInteger();
if (!x.Equals(new BigInteger("8706462696031173094919866327685737145866436939551712382591956952075131891462487598200779332295613073905587629438229")))
throw new Exception("X coord check failed");
if (!y.Equals(new BigInteger("10173258529327482491525749925661342501140613951412040971418641469645769857676705559747557238888921287857458976966474")))
throw new Exception("Y coord check failed");
Console.WriteLine("Step 1 complete");
// #####
// ##### Step 2
// #####
var privateKeyBytes = Convert.FromBase64String(privateKey);
var ecPrivateKeyParameters = new ECPrivateKeyParameters("ECDHC", new BigInteger(1, privateKeyBytes), domainParams);
var privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(ecPrivateKeyParameters);
var ecPrivateKey = (ECPrivateKeyParameters) PrivateKeyFactory.CreateKey(privateKeyInfo);
IBasicAgreement agree = AgreementUtilities.GetBasicAgreement("ECDHC");
agree.Init(ecPrivateKey);
BigInteger sharedKey = agree.CalculateAgreement(ecPublicKeyParameters);
var sharedKeyBytes = sharedKey.ToByteArrayUnsigned();
var sharedKeyBase64 = Convert.ToBase64String(sharedKeyBytes);
if (sharedKeyBase64 != "2lvSJsBO2keUHRfvPG6C1RMUmGpuDbdgNrZ9YD7RYnvAcfgq/fjeYr1p0hWABeif")
throw new Exception("Shared key check failed");
Console.WriteLine("Step 2 complete");
// #####
// ##### Step 3
// #####
var kdf2Bytes = Kdf2(sharedKeyBytes, decodedEphemeralPublicKey);
var kdf2Base64 = Convert.ToBase64String(kdf2Bytes);
if (kdf2Base64 != "mAzkYatDlz4SzrCyM23NhgL/+mE3eGgfUz9h1CFPhZOtXequzN3Q8w+B5GE2eU5g")
throw new Exception("Kdf2 failed");
Console.WriteLine("Step 3 complete");
// #####
// ##### Step 4
// #####
var decryptionKeyBytes = kdf2Bytes.Take(32).ToArray();
var decryptionIvBytes = kdf2Bytes.Skip(32).ToArray();
var decryptionKeyBase64 = Convert.ToBase64String(decryptionKeyBytes);
var decryptionIvBase64 = Convert.ToBase64String(decryptionIvBytes);
if (decryptionKeyBase64 != "mAzkYatDlz4SzrCyM23NhgL/+mE3eGgfUz9h1CFPhZM=")
throw new Exception("Decryption key check failed");
if (decryptionIvBase64 != "rV3qrszd0PMPgeRhNnlOYA==")
throw new Exception("Decryption iv check failed");
var encryptedDataBytes = decodedToken.Skip(97).Take(decodedToken.Length - 113).ToArray();
var tagBytes = decodedToken.Skip(decodedToken.Length - 16).ToArray();
var encryptedDataBase64 = Convert.ToBase64String(encryptedDataBytes);
var tagBase64 = Convert.ToBase64String(tagBytes);
if (encryptedDataBase64 != "afFS7GukrGilac6DKHNTH6YFRNqjSlwSCpkXDRj+")
throw new Exception("Encrypted data check failed");
if (tagBase64 != "pkgk9/Uq6wIyXPlMCGmOzA==")
throw new Exception("Tag check failed");
KeyParameter keyParam = ParameterUtilities.CreateKeyParameter("AES", decryptionKeyBytes);
ParametersWithIV parameters = new ParametersWithIV(keyParam, decryptionIvBytes);
IBufferedCipher cipher = CipherUtilities.GetCipher("AES/GCM/NoPadding");
cipher.Init(false, parameters);
var resultBytes = cipher.DoFinal(encryptedDataBytes.Concat(tagBytes).ToArray());
var resultBase64 = Convert.ToBase64String(resultBytes);
var resultString = Strings.FromByteArray(resultBytes);
if (resultString != "xXTi32iZwrQ6O8Sy6r1isKwF6Ff1Py")
throw new Exception("Decryption failed");
Console.WriteLine("Step 4 complete");
Console.WriteLine(resultString);
Console.WriteLine();
Console.WriteLine("Done... press any key to finish");
Console.ReadLine();
}
static byte[] Kdf2(byte[] sharedKeyBytes, byte[] ephemeralKeyBytes)
{
var gen = new Kdf2BytesGenerator(new Sha256Digest());
gen.Init(new KdfParameters(sharedKeyBytes, ephemeralKeyBytes));
byte[] encryptionKeyBytes = new byte[48];
gen.GenerateBytes(encryptionKeyBytes, 0, encryptionKeyBytes.Length);
return encryptionKeyBytes;
}
}
}