AES 128 how to brute force with partial key in python - python

I am beginner in python so I need help
I have encrypted file and partial key file ,the partial key file have 96 bit out of 128 so i need to guess
the rest of the key and decrypt the file ,the hint is the first word is "hello" in the encrypted
my questions:
how to guess the rest of key ?
how to check if the key is the right key and how much time did take?

Sorry that the source code in my answer is in Java but up to now I never wrote a single line in python. As you showed us nearly no self written code I assume you need a path to find a way to do it in python.
Some basics to start with - AES 128 encryption has a 128 bit or 16 bytes long key for encryption and later decryption. You told us that you already know 96 bits = 12 bytes so there are "just" 4 bytes left to guess. Each byte has a "capacity" of (integer) 256 so in maximum you would have to test 256 * 256 * 256 * 256 combinations = 4,294,967,296 combinations. Assuming that the key is of random you need half of this to try to find the real key so in real there are 2,147,483,648 combinations - a todays home computer does this within an hour or less.
Below you find my code and I setup an online compiler with the code - in this code I "restricted" the search for the last 2 bytes (so it assumes that 14 of the
16 bytes are known) because the online compiler would abort the program with a "running too long" runtime error.
The code is well commented and not optimized for speed but for readability. In the end you get an output like this one (as I'm using a random key and
initialization vector for AES in CBC mode your output will be different), the online compiler is available here: https://repl.it/#javacrypto/JavaAesCbc128BruteForce:
AES CBC String Encryption - brute force decryption
key length: 16 data: 0cb878f9da009be3ef487f54aa8c3230
keyGuess length: 16 data: 0cb878f9da009be3ef487f54aa8c0000
*** key found ***
key length: 16 data: 0cb878f9da009be3ef487f54aa8c3230
plaintext: hello this is just plaintext
code:
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
public class Main {
public static void main(String[] args) throws Exception {
System.out.println("AES CBC String Encryption - brute force decryption");
String plaintext = "hello this is just plaintext";
// this plaintext beginning is known
String plaintextKnown = "hello";
byte[] plaintextKnownByte = plaintextKnown.getBytes(StandardCharsets.UTF_8);
// number of known bytes of the key
int numberKeyBytes = 14; // 14 bytes = 112 bit known bits
// random key & iv
SecureRandom random = new SecureRandom();
byte[] key = new byte[16]; // 16 byte = 128 bit keylength
random.nextBytes(key);
byte[] iv = new byte[16];
random.nextBytes(iv);
System.out.println("key length: " + key.length + " data: " + bytesToHex(key));
// setup cbc
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivParameterSpec);
// get plaintext
byte[] plaintextByte = plaintext.getBytes(StandardCharsets.UTF_8);
byte[] ciphertextByte = cipher.doFinal(plaintextByte);
byte[] keyGuessed = new byte[16];
System.arraycopy(key, 0, keyGuessed, 0, numberKeyBytes ); // copy first 14 bytes = 112 bit
System.out.println("keyGuess length: " + keyGuessed.length + " data: " + bytesToHex(keyGuessed));
for (int a = 0; a < 256; a++) {
for (int b = 0; b < 256; b++) {
for (int c = 0; c < 256; c++) {
for (int d = 0; d < 256; d++) {
keyGuessed[15] = (byte) d;
//System.out.println("keyGuess length: " + keyGuessed.length + " data: " + bytesToHex(keyGuessed));
decryptAesCbc128(keyGuessed, iv, ciphertextByte, plaintextKnownByte);
}
keyGuessed[14] = (byte) c;
}
keyGuessed[13] = (byte) b;
}
keyGuessed[12] = (byte) a;
}
}
private static boolean decryptAesCbc128(byte[] key, byte[] iv, byte[] ciphertext, byte[] plaintextbyteKnown) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException {
SecretKeySpec keySpecDecode = new SecretKeySpec(key, "AES");
IvParameterSpec ivParameterSpecDecode = new IvParameterSpec(iv);
Cipher cipherDecrypt = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipherDecrypt.init(Cipher.DECRYPT_MODE, keySpecDecode, ivParameterSpecDecode);
byte[] decryptedtext = new byte[0];
try {
decryptedtext = cipherDecrypt.doFinal(ciphertext);
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
//e.printStackTrace();
return false;
}
// partial array comparison
boolean found = ByteBuffer.wrap(decryptedtext, 0, 5).equals(ByteBuffer.wrap(plaintextbyteKnown, 0, 5));
if (found == false) {return false;}
System.out.println("*** key found ***");
System.out.println("key length: " + key.length + " data: " + bytesToHex(key));
System.out.println("plaintext: " + new String(decryptedtext));
System.exit(0);
return true;
}
private static String bytesToHex(byte[] bytes) {
StringBuffer result = new StringBuffer();
for (byte b : bytes) result.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1));
return result.toString();
}
}

Related

Change Rijndael decryption logic from C# to Python

I have some already encrypted data which needs to be decrypted using python. The decryption logic in C# looks as given below.
using System.Security.Cryptography;
private const string Url_ENCRYPTION_KEY = "abcd123456";
private readonly static byte[] URL_SALT = Encoding.ASCII.GetBytes(Url_ENCRYPTION_KEY.Length.ToString());
public static string Decrypt(string inputText) {
try {
if (!string.IsNullOrEmpty(inputText)) {
RijndaelManaged rijndaelCipher = new RijndaelManaged();
byte[] encryptedData = Convert.FromBase64String(inputText.Replace(" ", "+"));
PasswordDeriveBytes secretKey = new PasswordDeriveBytes(Url_ENCRYPTION_KEY, URL_SALT);
using (ICryptoTransform decryptor =
rijndaelCipher.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16))) {
using (MemoryStream memoryStream = new MemoryStream(encryptedData)) {
using (CryptoStream cryptoStream =
new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)) {
byte[] plainText = new byte[encryptedData.Length];
int decryptedCount = cryptoStream.Read(plainText, 0, plainText.Length);
return Encoding.Unicode.GetString(plainText, 0, decryptedCount);
}
}
}
}
}
catch(Exception ex) {
//clsErrorHandler.LogError(ex);
}
return inputText;
}
I have tried libs like pprp and python's cryptography but the solutions out there use PBKDF2, while the C# code here supplies the decryptor bytes of key and salt as key and IV values.
From what I looked the PasswordDeriveBytes function basically work as a somewhat modified PBKDF1,
but all of the solutions I tried fail with somekind of esoteric this size doesn't match with that size errors.
Here is one implementation of PasswordDeriveBytes I found floating out there but I am at a loss on how to do something similar to secretKey.GetBytes(32) and creating a decryptor
import hashlib
from base64 import b64decode
def MS_PasswordDeriveBytes(pstring, salt, hashfunc, iterations, keylen):
if iterations > 0:
lasthash = hashlib.sha1(pstring+salt).digest()
iterations -= 1
else:
print("Iterations must be > 0")
#If iterations is 1 then basically the same thing happens as 2 based on my testing
#if iterations == 0 and keylen > len(lasthash):
#print("Dunno what happens here")
#return -1
for i in range(iterations-1):
lasthash = hashlib.sha1(lasthash)
bytes = hashlib.sha1(lasthash).digest()
ctrl = 1
while len(bytes) < keylen:
bytes += hashlib.sha1(str(ctrl)+lasthash).digest()
ctrl += 1
return(bytes[:keylen])
stpass = 'amp4Z0wpKzJ5Cg0GDT5sJD0sMw0IDAsaGQ1Afik6NwXr6rrSEQE='
slt = 'aGQ1Afik6NampDT5sJEQE4Z0wpsMw0IDAD06rrSswXrKzJ5Cg0G='
initv = '#1B2c3D4e5F6g7H8'
enc_str = b64decode('B5YDTLEDBjd+8zy5lzEfjw==')
derbytes = MS_PasswordDeriveBytes(stpass, slt, hashlib.sha1, iterations=2, keylen=32)

Problem with Python 3 AES decryption, IV lenght problem

i was trying to decrypt an AES ciphertext with Python 3.
I know that the key has been encoded as it follows (javascript) :
var k = CryptoJS.SHA256("\x93\x39\x02\x49\x83\x02\x82\xf3\x23\xf8\xd3\x13\x00");
if(u == "\x68\x34\x63\x6b\x33\x72") {
var enc = CryptoJS.AES.encrypt(p, CryptoJS.enc.Hex.parse(k.toString().substring(0,32)), { iv: CryptoJS.enc.Hex.parse(k.toString().substring(32,64)) });
if(enc == "PKhuCrfh3RUw4vie3OMa8z4kcww1i7198ly0Q4rpuyA=") {
t = true;
}
}
Now, as you can see the IV of the encryption is 32 characters long, however in python 3 i can't use a string of length 32 as my IV.
I use the following code :
def decrypt(encrypted, passphrase_full):
half1_passphrase = passphrase_full[0:32]
half2_passphrase = passphrase_full[32:]
print(len(half2_passphrase))
IV = half2_passphrase
aes = AES.new(half1_passphrase, AES.MODE_CBC, IV)
return aes.decrypt(encrypted)
And i get
ValueError: IV must be 16 bytes long
So, how can i decrypt my string correctly ?
Thank you very much

Hashing algorithm Node js vs Python

I was trying to convert a hash algorithm which is written on Python to node.js
The python code looks something as
import uuid
import hashlib
import struct
CLIENT_ID = uuid.UUID('c5f92e0d-e762-32cd-98cb-8c546c410dbe')
SECRET = uuid.UUID('2cf26ff5-bd06-3245-becf-4d5a3baa704f')
data = CLIENT_ID.bytes_le + SECRET.bytes_le + struct.pack("I", 2017) + struct.pack("I", 9) + struct.pack("I", 2)
token = str(uuid.UUID(bytes_le=hashlib.sha256(data).digest()[0:16]))
The token generated is 32d86f00-eb49-2739-e957-91513d2b9969
Here the date values struct.pack values are generated using datetime but for convenient I have hard coded here.
I tried to convert the same by looking at the python doc for the respective libraries and did so far as
let CLIENT_ID = new Buffer('c5f92e0d-e762-32cd-98cb-8c546c410dbe');
let SECRET = new Buffer('2cf26ff5-bd06-3245-becf-4d5a3baa704f');
let d = new Buffer(2);
let m = new Buffer(9);
let y = new Buffer(2017);
let data = CLIENT_ID+SECRET+y+m+d;
const uuidv4 = require('uuid/v4');
const hash = crypto.createHash('sha256');
let token = uuidv4({random: hash.update(data, 'utf8').digest().slice(0, 16)}, 0);
And the hash it generates is b7b82474-eab4-4295-8318-cc258577ff9b
So, basically I am miserably missing something for the nodejs part.
Could you please guide me on where what went wrong. Thanks for the help
There's a lot of missed parts actually it tuned out.
###node parts:
new Buffer('c5')
does not represent <Buffer c5>, but <Buffer 63 35>.
To write c5 you would need to use Buffer.from([0xc5]) or Buffer.from([197]) (dec).
new Buffer(2)
does not represent <Buffer 02>, it just allocates 2 bytes.
CLIENT_ID+SECRET+y+m+d
concatenation of buffers does not work that way.
Use array of buffers and Buffer.concat([buffers]) to concatenate buffers.
###uuid parts:
it turned out that uuid operates modified version of buffers (bytes_le part in python code)
#the most interesting part:
in the python version of uuid, if no version argument is passed to uuid.UUID(...), uuid would generate an ID without fixing bits
According to the RFC-4122 4.4 uuid should fix that bits.
uuid.py skips RFC-4122 4.4
node-uuid/v4.js fixes required bits
that way even with the same results for sha256 hashing, the results between python and node implementation still would differ
python: 32d86f00-eb49-2739-e957-91513d2b9969
node: 32d86f00-eb49-4739-a957-91513d2b9969
^ ^
So, I see here 2 options
to pass version to python uuid (only for the last uuid call uuid.UUID(bytes_le=..., version=4)), that way python would return 32d86f00-eb49-4739-a957-91513d2b9969
if there's no way to change source code in python project, I guess there's an option to fork uuid and remove two lines of code in node-uuid/v4.js?
##See node version of your code below:
const uuidv4 = require('uuid/v4');
const crypto = require('crypto');
const hash = crypto.createHash('sha256');
const client_id_hex_str = "c5f92e0d-e762-32cd-98cb-8c546c410dbe".replace(/-/g, "");
const secret_hex_str = "2cf26ff5-bd06-3245-becf-4d5a3baa704f".replace(/-/g, "");
let CLIENT_ID = Buffer.from(to_bytes_le(to_bytes(client_id_hex_str, null, 16, 'big')));
let SECRET = Buffer.from(to_bytes_le(to_bytes(secret_hex_str, null, 16, 'big')));
let d = Buffer.from(to_bytes(null, 2, 4));
let m = Buffer.from(to_bytes(null, 9, 4));
let y = Buffer.from(to_bytes(null, 2017, 4));
let data = Buffer.concat([CLIENT_ID, SECRET, y, m, d]);
let hashBytes = hash.update(data, 'utf8').digest().slice(0, 16);
hashBytes = [].slice.call(hashBytes, 0);
hashBytes = Buffer.from(to_bytes_le(hashBytes));
let token = uuidv4({random: hashBytes});
console.log(token);
// https://stackoverflow.com/questions/16022556/has-python-3-to-bytes-been-back-ported-to-python-2-7
function to_bytes(hexString, number, length, endianess) {
if (hexString == null && number == null) {
throw new Error("Missing hex string or number.");
}
if (!length || isNaN(length)) {
throw new Error("Missing or invalid bytes array length number.");
}
if (hexString && typeof hexString != "string") {
throw new Error("Invalid format for hex value.");
}
if (hexString == null) {
if (isNaN(number)) {
throw new Error("Invalid number.");
}
hexString = number.toString(16);
}
let byteArray = [];
if (hexString.length % 2 !== 0) {
hexString = '0' + hexString;
}
const bitsLength = length * 2
hexString = ("0".repeat(bitsLength) + hexString).slice(-1 * bitsLength);
for (let i = 0; i < hexString.length; i += 2) {
const byte = hexString[i] + hexString[i + 1];
byteArray.push(parseInt(byte, 16));
}
if (endianess !== "big") {
byteArray = byteArray.reverse();
}
return byteArray;
}
// https://github.com/python/cpython/blob/master/Lib/uuid.py#L258
function to_bytes_le(bytes) {
const p1 = bytes.slice(0, 4).reverse();
const p2 = bytes.slice(4, 6).reverse();
const p3 = bytes.slice(6, 8).reverse();
const p4 = bytes.slice(8);
const bytes_le = [].concat.apply([], [p1, p2, p3, p4]);
return bytes_le;
}
Do you want the hashing of the data to be the same as the Python code above?
If not, you can take a look at the the Sha256 module below in NodeJS
https://www.npmjs.com/package/sha256

Decrypting in Python and Objective C

I am decrypting a data using python and getting succeed, but when i try to decrypt same data using objective c then decryption get success but when convert decrypted NSData to NSString Returns Null. I have decoded retrieved NSData by applying different encoding but returns null or unreadable data.
Please see below code.
Python
salt = b'saltysalt'
my_val = ‘TGIF40)volubly’
iv = b' ' * 16
iterations = 1003
# Generate key from values above
key = PBKDF2(my_pass, salt, length, iterations)
encrypted_value = \225O\373\235Y\363\265\326\341\206\352\214O\270\343u\300/k;e7\202;\215d\230\364
cipher = AES.new(key, AES.MODE_CBC, IV=iv)
decrypted = cipher.decrypt(encrypted_value)
print(decrypted)
Output : 5105105105105100
Objective C
NSString * my_val = #“TGIF40)volubly”
NSData* myValdata = [my_val dataUsingEncoding:NSUTF8StringEncoding];
NSMutableData *derivedKey = [NSMutableData dataWithLength:kCCKeySizeAES128];
NSData *encrypted_inputData = <00954ffb 9d59f3b5 d60ce186 ea8c4f14 b804e375 c02f6b3b 6537823b 8d6498f4>
NSData *saltbytes = [#“saltysalt”dataUsingEncoding:NSUTF8StringEncoding];
CCKeyDerivationPBKDF(kCCPBKDF2, myValdata.bytes, myValdata.length, saltbytes.bytes, saltbytes.length, kCCPRFHmacAlgSHA1, 1003, derivedKey.mutableBytes, derivedKey.length);
NSLog(#"%#",derivedKey);
size_t outLength;
NSMutableData *outputData = [NSMutableData dataWithLength:(encrypted_inputData.length + kCCKeySizeAES128)];
Printing description of key:
derivedKey = <dfbf16cc 449619be b57b0aba eb92de70>
CCCryptorStatus result = kCCSuccess;
result = CCCrypt(kCCDecrypt, // kCCEncrypt or kCCDecrypt
kCCAlgorithmAES,
kCCOptionPKCS7Padding | kCCModeCBC,
derivedKey.bytes,
kCCKeySizeAES256,
NULL,
encrypted_inputData.bytes,
encrypted_inputData.length,
outputData.mutableBytes,
outputData.length,
&outLength);
if (result != kCCSuccess) {
if (error != NULL) {
*error = [NSError errorWithDomain:#"com.your_domain.your_project_name.your_class_name."
code:result
userInfo:nil];
}
return nil;
}
[outputData setLength:outLength];
NSString* retStr = [NSString stringWithUTF8String:[outputData bytes]];
Printing description of outputData:
<0a0df388 cf535290 0b1d2712 343e3c69 d633cab7 7cf5382a 92d88207 1f5347bd>
Can anyone help please ?
1.
Do not specify kCCModeCBC, it is not used with CCCrypt. CCCrypt has CBC mode as the default.
CCCrypt options are:
enum {
/* options for block ciphers */
kCCOptionPKCS7Padding = 0x0001,
kCCOptionECBMode = 0x0002
/* stream ciphers currently have no options */
};
typedef uint32_t CCOptions;
kCCModeCBC is only used with CCCryptorCreateWithMode and has a value of 2 which if used in place of kCCModeCBC will actually specify ECB mode. This was a bad choice made by Apple.
2.
You are providing a 16-byte key but specifying a 256-bit (32-byte) key:
derivedKey = <dfbf16cc 449619be b57b0aba eb92de70> // 16-bytes
kCCKeySizeAES256, // 32-bytes
When specifying the output data size use kCCBlockSizeAES128.

Different Results in Go and Pycrypto when using AES-CFB

I am adding a go application to an already existing python codebase. I've been having trouble dealing with encryption between the languages. This is using go 1.2.1 and Python 2.7.x / PyCrypto 2.7a1.
Here is the Python sample:
import Crypto.Cipher
import Crypto.Hash.HMAC
import Crypto.Hash.SHA256
import Crypto.PublicKey.RSA
from binascii import hexlify, unhexlify
#encrypt
payload = unhexlify("abababababababababababababababababababababababababababababababab")
password = unhexlify("0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF")
iv = unhexlify("00000000000000000000000000000000")
print "IV: ", hexlify(iv), "len: ", len(iv)
print "Password length: ", len(password)
cipher = Crypto.Cipher.AES.new(
key=password,
mode=Crypto.Cipher.AES.MODE_CFB,
IV=iv)
payload = cipher.encrypt(payload)
print hexlify(payload) #dbf6b1877ba903330cb9cf0c4f530d40bf77fe2bf505820e993741c7f698ad6b
And this is the Go sample:
package main
import (
"fmt"
"crypto/cipher"
"crypto/aes"
"encoding/hex"
)
// encrypt
func main() {
payload, err1 := hex.DecodeString("abababababababababababababababababababababababababababababababab")
password, err2 := hex.DecodeString("0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF")
iv, err3 := hex.DecodeString("00000000000000000000000000000000")
if err1 != nil {
fmt.Printf("error 1: %v", err1)
return
}
if err2 != nil {
fmt.Printf("error 2: %v", err2)
return
}
if err3 != nil {
fmt.Printf("error 3: %v", err3)
return
}
aesBlock, err4 := aes.NewCipher(password)
fmt.Printf("IV length:%v\n", len(iv))
fmt.Printf("password length:%v\n", len(password))
if err4 != nil {
fmt.Printf("error 4: %v", err4)
return
}
cfbDecrypter := cipher.NewCFBEncrypter(aesBlock, iv)
cfbDecrypter.XORKeyStream(payload, payload)
fmt.Printf("%v\n", hex.EncodeToString(payload)) // db70cd9e6904359cb848410bfa38d7d0a47b594f7eff72d547d3772c9d4f5dbe
}
Here is the golang link, I could not find a Python pastebin that had PyCrypto installed.
As suggested by the title & source, the two snippets produce different cyphertext:
Python: dbf6b1877ba903330cb9cf0c4f530d40bf77fe2bf505820e993741c7f698ad6b
Golang: db70cd9e6904359cb848410bfa38d7d0a47b594f7eff72d547d3772c9d4f5dbe
Both languages can decrypt their 'native' cypthertext, but neither can decrypt the others'. Because the python implementation already exists, I'm looking for a solution that will allow Go to decrypt cyphertext encrypted with the example PyCrypto AES settings & key size.
Research on the current system has revealed that our python system uses CFB8 (8 bit segments). Go does not support this out of the box, but the source code used in the current CFBDecrypter / CFBEncrypter looks like it can be adapted fairly easily.
If anyone is looking for Go implementation of CFB mode with segment size = 8 you can use this:
import "crypto/cipher"
// CFB stream with 8 bit segment size
// See http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf
type cfb8 struct {
b cipher.Block
blockSize int
in []byte
out []byte
decrypt bool
}
func (x *cfb8) XORKeyStream(dst, src []byte) {
for i := range src {
x.b.Encrypt(x.out, x.in)
copy(x.in[:x.blockSize-1], x.in[1:])
if x.decrypt {
x.in[x.blockSize-1] = src[i]
}
dst[i] = src[i] ^ x.out[0]
if !x.decrypt {
x.in[x.blockSize-1] = dst[i]
}
}
}
// NewCFB8Encrypter returns a Stream which encrypts with cipher feedback mode
// (segment size = 8), using the given Block. The iv must be the same length as
// the Block's block size.
func newCFB8Encrypter(block cipher.Block, iv []byte) cipher.Stream {
return newCFB8(block, iv, false)
}
// NewCFB8Decrypter returns a Stream which decrypts with cipher feedback mode
// (segment size = 8), using the given Block. The iv must be the same length as
// the Block's block size.
func newCFB8Decrypter(block cipher.Block, iv []byte) cipher.Stream {
return newCFB8(block, iv, true)
}
func newCFB8(block cipher.Block, iv []byte, decrypt bool) cipher.Stream {
blockSize := block.BlockSize()
if len(iv) != blockSize {
// stack trace will indicate whether it was de or encryption
panic("cipher.newCFB: IV length must equal block size")
}
x := &cfb8{
b: block,
blockSize: blockSize,
out: make([]byte, blockSize),
in: make([]byte, blockSize),
decrypt: decrypt,
}
copy(x.in, iv)
return x
}
It seems that the cipher can be made compatible to Go's crypto/cipher if we change segment_size of AES object from the default 8 to AES.block_size*8 (which is 128), like this:
Crypto.Cipher.AES.new(
key=password,
mode=Crypto.Cipher.AES.MODE_CFB,
IV=iv,
segment_size=AES.block_size*8
)
I found that easiest way to deal with this from Python side is to use M2Crypto library.
Final code looks like:
import M2Crypto.EVP
iv = ciphertext[:16]
ciphertext = ciphertext[16:]
cipher = M2Crypto.EVP.Cipher('aes_256_cfb', t, iv, 0)
text = cipher.update(ciphertext)
print text
Works perfect without need to change something in Go.
i solve by adapt python code like this (golang encode and python decode):
# golang encode
padNum := len(data) % 16
if padNum != 0 {
for i := 0; i < 16-padNum; i++ {
data = append(data, ',')
}
}
# python decode
cipher = AES.new(key=self.key, mode=AES.MODE_CFB, IV=iv,segment_size=128)

Categories