Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
555 views
in Technique[技术] by (71.8m points)

How to decrypt password from JavaScript CryptoJS.AES.encrypt(password, passphrase) in Python

I have a password which is encrypt from JavaScript via

  var password = 'sample'
  var passphrase ='sample_passphrase'
  CryptoJS.AES.encrypt(password, passphrase)

Then I tried to decrypt the password comes from JavaScript in Python:

  from Crypto.Cipher import AES
  import base64

  PADDING = ''

  pad_it = lambda s: s+(16 - len(s)%16)*PADDING
  key = 'sample_passphrase'
  iv='11.0.0.101'        #------> here is my question, how can I get this iv to restore password, what should I put here?
  key=pad_it(key)        #------> should I add padding to keys and iv?
  iv=pad_it(iv)          ##
  source = 'sample'
  generator = AES.new(key, AES.MODE_CFB,iv)
  crypt = generator.encrypt(pad_it(source))
  cryptedStr = base64.b64encode(crypt)
  print cryptedStr
  generator = AES.new(key, AES.MODE_CBC,iv)
  recovery = generator.decrypt(crypt)
  print recovery.rstrip(PADDING)

I checked JS from browser console, it shows IV in CryptoJS.AES.encrypt(password, passphrase) is a object with some attributes( like sigBytes:16, words: [-44073646, -1300128421, 1939444916, 881316061]). It seems generated randomly.

From one web page, it tells me that JS has two way to encrypt password (reference link ):

  • a. crypto.createCipher(algorithm, password)
  • b. crypto.createCipheriv(algorithm, key, iv)

What I saw in JavaScript should be option a. However, only option b is equivalent to AES.new() in python.

The questions are:

  1. How can I restore this password in Python without changing JavaScript code?

  2. If I need IV in Python, how can I get it from the password that is used in JavaScript?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You will have to implement OpenSSL's EVP_BytesToKey, because that is what CryptoJS uses to derive the key and IV from the provided password, but pyCrypto only supports the key+IV type encryption. CryptoJS also generates a random salt which also must be send to the server. If the ciphertext object is converted to a string, then it uses automatically an OpenSSL-compatible format which includes the random salt.

var data = "Some semi-long text for testing";
var password = "some password";
var ctObj = CryptoJS.AES.encrypt(data, password);
var ctStr = ctObj.toString();

out.innerHTML = ctStr;
<script src="https://cdn.rawgit.com/CryptoStore/crypto-js/3.1.2/build/rollups/aes.js"></script>
<div id="out"></div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...