JS reverse---National standard hash algorithm (MD5, SHA series, HMAC encryption and related cases detailed explanation)


Preface

The basic implementation method in JavaScript and Python can quickly restore the encryption process when encountering JS encryption. Some websites may also undergo other processing during the encryption process, but the general method is the same.

This article mainly talks about: message digest algorithm/secure hash algorithm/hash message authentication code, key-related hash operation message authentication code: MD5, SHA, HMAC

Statement
All content in this article is only for learning and communication, and is not used for any other purpose. The complete code is not provided. The packet capture content, sensitive URLs, data interfaces, etc. have been processed Desensitization, commercial and illegal use is strictly prohibited, otherwise the author has nothing to do with any consequences arising therefrom!
This article is prohibited from being reproduced without permission, and is prohibited from being redistributed after any modification. The author is not responsible for any accidents caused by the unauthorized use of the technology explained in this article. If there is any infringement, please contact the author immediately Delete

1. MD5 algorithm

  • Introduction: The full name is MD5 message digest algorithm, also known as hash algorithm and hash algorithm. It was designed by American cryptographer Ronald Leviste and was published as RFC 1321 in 1992 to replace the MD4 algorithm. The digest algorithm is a one-way encryption, which means that after the plaintext is encrypted by the digest algorithm, it cannot be decrypted. The second feature of the digest algorithm is that the ciphertext is of fixed length. It converts data of any length into a fixed-length data string (usually represented by a hexadecimal string) through a function. The reason why it is called summary algorithm is that its algorithm extracts important features of plaintext. Therefore, after using the digest algorithm for two different plaintexts, it is possible that their ciphertexts are the same, but this probability is very low.

1.1 Javascript implementation

  • Install the corresponding module
// 在依赖项中添加包: --save
npm install crypto-js  --save
  • Use Cases
// 引用 crypto-js 加密模块
var CryptoJS = require('crypto-js')

function MD5Test() {
    
    
    var text = "I love python!"
    return CryptoJS.MD5(text).toString()
}

console.log(MD5Test()) 

2. python implementation

import hashlib

def md5_test2():
    md5 = hashlib.md5()
    md5.update('python'.encode('utf-8'))
    print(md5.hexdigest())

if __name__ == '__main__':
    md5_test2() 

3. MD5 features

Conclusion:
MD5 Special Expedition:

  1. When the plaintext is the same, the plaintext is also the same
  2. Length 32 bits, size 128b, 16 bytes (fixed)
  3. One-way encryption, irreversible
  4. How to determine whether the algorithm encryption in the website JS file is standard encryption?
    • Use fixed parameters to compare standard algorithm results

2. SHA series algorithms

  • Introduction: The full name is Secure Hash Algorithm, designed by the National Security Agency (NSA) of the United States. It is mainly applicable to the digital signature algorithm defined in the digital signature standard. SHA usually refers to the five algorithms of the SHA family, namely SHA-1, SHA- 224, SHA-256, SHA-384, SHA-512, SHA is a more secure digest algorithm than MD5. The ciphertext of MD5 is 32 bits, while SHA-1 is 40 bits. The stronger the version, the longer the ciphertext. The price is slower speed.

1. Javascript implementation

// 引用 crypto-js 加密模块
var CryptoJS = require('crypto-js')

function SHA1Encrypt() {
    
    
    var text = "I love python!"
    return CryptoJS.SHA1(text).toString();
}

console.log(SHA1Encrypt()) 

2. Python implementation

import hashlib

def sha1_test2():
    sha1 = hashlib.sha1()
    sha1.update('I love python!'.encode('utf-8'))
    prinACt(sha1.hexdigest())

if __name__ == '__main__':
    sha1_test2() 

3. sha series features

Conclusion
sha series special expedition:

  • Belongs to digital signature algorithm
  • sha1 length: 40th place
    sha224 length: 56th place
    sha256 length: 64th place
    sha512 length: 128th place
  • Positioning based on length, the main thing is to set breakpoints in JavaScript for debugging and analysis

3. HMAC encryption algorithm

  • Introduction: The full name is Hash Message Authentication Code and Key-related Hash Operation Message Authentication Code. It was proposed in 1996 and published as RFC 2104 in 1997. The HMAC encryption algorithm is a secure encryption algorithm based on a cryptographic Hash function and a shared key. Message authentication protocol, which requires both communicating parties to share a key, agree on an algorithm, and perform a hash operation on the message to form a fixed-length authentication code. The communicating parties determine the legitimacy of the message through verification of the authentication code.

References:

  • Encyclopedia: https://baike.baidu.com/item/hmac/7307543?fr=aladdin

1. JavaScript implementation

// 引用 crypto-js 加密模块
var CryptoJS = require('crypto-js')

function HMACEncrypt() {
    
    
    var text = "I love python!"
    var key = "secret"   // 密钥文件
    return CryptoJS.HmacMD5(text, key).toString();
    // return CryptoJS.HmacSHA1(text, key).toString();
    // return CryptoJS.HmacSHA256(text, key).toString();
}
console.log(HMACEncrypt())

2. python implementation

import hmac

def hmac_test1():
    message = 'I love python!'.encode()
    key = b'secret'
    md5 = hmac.new(key, message, digestmod='MD5')
    print(md5.hexdigest())

def hmac_test2():
    key = 'secret'.encode('utf8')
    sha1 = hmac.new(key, digestmod='sha1')
    sha1.update('I love '.encode('utf8'))
    sha1.update('Python!'.encode('utf8'))
    print(sha1.hexdigest())

if __name__ == '__main__':
    hmac_test1()  # 9c503a1f852edcc3526ea56976c38edf
    hmac_test2()  # 2d8449a4292d4bbeed99ce9ea570880d6e19b61a

3. HMAC features

Summarize

  • The basic idea of ​​HMAC is to reuse existing message digest algorithms such as MD5 and SHA-1
  • Has a key file, using symmetric key encryption

4. Case analysis

1. Case sha series analysis

  • Reverse goal: celebrity point collection
  • Reverse main parameters: sign:

Through comparison, you can find that this parameter will switch every time
Insert image description here
Debugging the encryption location
You can choose to globally search for the sign keyword a>
Or follow the stack directly
Insert image description here
Obtain the parameter encryption location
Insert image description here
Analyze the parameter encryption location
Insert image description here
Make it clear that this parameter is the sha256 encryption method
Implement the code for this parameter

import urllib3,requests,time,json
urllib3.disable_warnings()
import hashlib

months = input("请输入查询月份:")
days = input("请输入查询日期,2天以内:")
times = str(int(time.time()) * 1000)
params = {
    
    "no":"dy0002","data":{
    
    "days":1,"rankType":5,"liveDay":f"2023-{
      
      months.zfill(2)}-{
      
      days.zfill(2)}"}}
print(params)
dd = json.dumps(params)
def get_sign():
    data = f'param={
      
      dd}&timestamp={
      
      times}&tenant=1&salt=kbn%&)@<?FGkfs8sdf4Vg1*+;`kf5ndl$'  # 要进行加密的数据
    data_sha = hashlib.sha256(data.encode('utf-8')).hexdigest()
    return data_sha

def get_data():
    headers = {
    
    
        "Content-Type": "application/json;charset=UTF-8",
        "Host": "ucp.hrdjyun.com:60359",
        "Origin": "http://www.hh1024.com",
        "Pragma": "no-cache",
        "sec-ch-ua": "\"Google Chrome\";v=\"107\", \"Chromium\";v=\"107\", \"Not=A?Brand\";v=\"24\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Windows\"",
        "Sec-Fetch-Dest": "empty",
        "Sec-Fetch-Mode": "cors",
        "Sec-Fetch-Site": "cross-site",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36"
    }
    session = requests.session()
    s = get_sign()
    t = "这里面是登陆后的token值"
    datas = {
    
    "param":dd,"sign":s,"tenant":"1","timestamp":times,"token":t}
    url = 'https://ucp.hrdjyun.com:60359/api/dy'
    res = session.post(url,headers=headers,data=json.dumps(datas))
    if res.json().get('status') == 0:
        data = res.json().get('data')['rankList']
        for d in data:
            items = {
    
    }
            items['抖音名'] = d.get('anchorName')
            items['带货销量'] ='%.2f' % (d.get('salesVolume') / 10000) + '万'
            print(items)

if __name__ == '__main__':
    reads = """
        本接口只开放抖音带货销量日榜
        可以根据日期查询
                                --- 夏洛
        """
    print(reads)
    get_data()

Final code implementation effect
Insert image description here

2. Case Hamc series

  • Reverse goal: Qichacha
  • Reverse parameters: E6f8103c1332674be0f3:
    cc136a1acba0ee1caf94f66b637f2ed8fe40be90ad28dc22ba6b131e90815e2d350512c3685ca5b8f790f546d076d97 1a5f92af3e4de3b0a4c70b418e719aaa5
    Header parameters

Through comparison, it can be found that this parameter will switch every time
Insert image description here And after repeated page turning and comparison, it is found that the encryption situation is the same on the same page, and the ciphertext length is 256 bits. The proof is very likely that it is a hash algorithm. Because of its length, it is speculated to be the sha512 series
. Directly search for header parameters headers[
Insert image description here
and perform breakpoints. It can be found that i is the key value and l is the value. Just analyze these two parameters
. First analyze the key value and enter a.default
Insert image description here
The logic is as shown below
and it is found that the return value is the requested key value
Continue to reverse the code
Insert image description here
and analyze it first ( t + n, (0, a.default)(t))
Insert image description here
Found that n is the value we need
Directly organize the logic and convert it into python code. You can
turn around and analyze the o.default part
Insert image description here
and after entering, you will find that it is an r() function
Insert image description here
Continue to enter a>
Insert image description here
Insert image description here
It has been basically determined that the reverse algorithm of this parameter is the Hamcsha512 series. Compare the standard website algorithm to see if it is a standard algorithm, then deduct the JS and convert it into python

Insert image description here

Complete
The subsequent value value and the reverse process and method of the key value are basically the same, so I won’t go into details here (actually because I am lazy)

Write at the end:
My writing level is limited. If there are any explanations that are not in place or wrong, please give me some advice in the comment area and we can make progress together. If there is any If you need code and explanation communication, you can add me on WeChat 18847868809

Guess you like

Origin blog.csdn.net/m0_52336378/article/details/131743841