Rust-Crypto: AES CBC Decryption Failing

I have written a Rust code to decrypt a string/s which is encrypted by a Java program. But I am seeing error when decrypting some strings.

Note: I could not share the encrypted string here as this issue is seen particularity in prod.

In java program, it uses following functions to encrypt and decrypt.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
private static final byte[] IV_BYTES = new byte[16];
private static final IvParameterSpec IV_PARAMETER_SPEC = new IvParameterSpec(IV_BYTES);
protected static final String AES_CBC_PKCS5_PADDING = "AES/CBC/PKCS5Padding";
private static void initEncr() {
try {
cipherEnc.set(Cipher.getInstance(AES_CBC_PKCS5_PADDING));
cipherEnc.get().init(Cipher.ENCRYPT_MODE, getDek(), IV_PARAMETER_SPEC);
} catch (Throwable e) {
throw new UDFException("Error initializing encrypt cipher: " + e.getMessage(), e);
}
}
private static void initDecr() {
try {
cipherDec.set(Cipher.getInstance(AES_CBC_PKCS5_PADDING));
cipherDec.get().init(Cipher.DECRYPT_MODE, getDek(), IV_PARAMETER_SPEC);
} catch (Throwable e) {
throw new UDFException("Error initializing decrypt cipher: " + e.getMessage(), e);
}
}
</code>
<code>import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; private static final byte[] IV_BYTES = new byte[16]; private static final IvParameterSpec IV_PARAMETER_SPEC = new IvParameterSpec(IV_BYTES); protected static final String AES_CBC_PKCS5_PADDING = "AES/CBC/PKCS5Padding"; private static void initEncr() { try { cipherEnc.set(Cipher.getInstance(AES_CBC_PKCS5_PADDING)); cipherEnc.get().init(Cipher.ENCRYPT_MODE, getDek(), IV_PARAMETER_SPEC); } catch (Throwable e) { throw new UDFException("Error initializing encrypt cipher: " + e.getMessage(), e); } } private static void initDecr() { try { cipherDec.set(Cipher.getInstance(AES_CBC_PKCS5_PADDING)); cipherDec.get().init(Cipher.DECRYPT_MODE, getDek(), IV_PARAMETER_SPEC); } catch (Throwable e) { throw new UDFException("Error initializing decrypt cipher: " + e.getMessage(), e); } } </code>
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;


private static final byte[] IV_BYTES = new byte[16];
private static final IvParameterSpec IV_PARAMETER_SPEC = new IvParameterSpec(IV_BYTES);
protected static final String AES_CBC_PKCS5_PADDING = "AES/CBC/PKCS5Padding";

private static void initEncr() {
        try {
            cipherEnc.set(Cipher.getInstance(AES_CBC_PKCS5_PADDING));
            cipherEnc.get().init(Cipher.ENCRYPT_MODE, getDek(), IV_PARAMETER_SPEC);
        } catch (Throwable e) {
            throw new UDFException("Error initializing encrypt cipher: " + e.getMessage(), e);
        }
    }

private static void initDecr() {
        try {
            cipherDec.set(Cipher.getInstance(AES_CBC_PKCS5_PADDING));
            cipherDec.get().init(Cipher.DECRYPT_MODE, getDek(), IV_PARAMETER_SPEC);
        } catch (Throwable e) {
            throw new UDFException("Error initializing decrypt cipher: " + e.getMessage(), e);
        }
    }

There is no problem in decrypting the encrypted string using initDecr function above.

Python implementation to decrypt a string

Currently we are using below python program to decrypt the encrypted string(in Java). There is no error/issue decrypting a string with this program as well.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import base64
from typing import Union
from Crypto.Cipher.AES import MODE_CBC, block_size
from Crypto.Cipher.AES import new as aes_new
from Crypto.Util.Padding import unpad
# 16 bytes null array
_iv = bytearray([0] * 16)
def _b64decode(text: str):
text = bytearray(text.encode('ascii')).strip()
return base64.b64decode(text, validate=True)
class AES:
"""
AES object to decrypt cipher text
"""
def __init__(self, key: Union[str, bytes, bytearray], mode=MODE_CBC, iv=_iv):
"""
Args:
key: ASCII/B64 Encoded or Base64 decoded key string to decrypt cipher text
mode: AES mode of operations. `default`: `AES.MODE_CBC`
iv: initialization vector(iv) used during encryption. `default: 16 bytes null array`
"""
if isinstance(key, str) and key.isprintable():
key = _b64decode(key)
self._key = key
self.mode = mode
self.iv = iv
def decrypt(self, cipher_text, decode_output=True) -> Union[str, bytes]:
if isinstance(cipher_text, str) and cipher_text.isprintable():
cipher_text = _b64decode(cipher_text)
if not isinstance(cipher_text, bytes):
raise ValueError('Cipher text should be base64 decoded')
plain_text = aes_new(self._key, self.mode, self.iv).decrypt(cipher_text)
if decode_output:
return unpad(plain_text, block_size).decode()
return unpad(plain_text, block_size)
</code>
<code>import base64 from typing import Union from Crypto.Cipher.AES import MODE_CBC, block_size from Crypto.Cipher.AES import new as aes_new from Crypto.Util.Padding import unpad # 16 bytes null array _iv = bytearray([0] * 16) def _b64decode(text: str): text = bytearray(text.encode('ascii')).strip() return base64.b64decode(text, validate=True) class AES: """ AES object to decrypt cipher text """ def __init__(self, key: Union[str, bytes, bytearray], mode=MODE_CBC, iv=_iv): """ Args: key: ASCII/B64 Encoded or Base64 decoded key string to decrypt cipher text mode: AES mode of operations. `default`: `AES.MODE_CBC` iv: initialization vector(iv) used during encryption. `default: 16 bytes null array` """ if isinstance(key, str) and key.isprintable(): key = _b64decode(key) self._key = key self.mode = mode self.iv = iv def decrypt(self, cipher_text, decode_output=True) -> Union[str, bytes]: if isinstance(cipher_text, str) and cipher_text.isprintable(): cipher_text = _b64decode(cipher_text) if not isinstance(cipher_text, bytes): raise ValueError('Cipher text should be base64 decoded') plain_text = aes_new(self._key, self.mode, self.iv).decrypt(cipher_text) if decode_output: return unpad(plain_text, block_size).decode() return unpad(plain_text, block_size) </code>
import base64
from typing import Union

from Crypto.Cipher.AES import MODE_CBC, block_size
from Crypto.Cipher.AES import new as aes_new
from Crypto.Util.Padding import unpad

# 16 bytes null array
_iv = bytearray([0] * 16)


def _b64decode(text: str):
    text = bytearray(text.encode('ascii')).strip()
    return base64.b64decode(text, validate=True)


class AES:
    """
    AES object to decrypt cipher text
    """

    def __init__(self, key: Union[str, bytes, bytearray], mode=MODE_CBC, iv=_iv):
        """
        Args:
            key: ASCII/B64 Encoded or Base64 decoded key string to decrypt cipher text
            mode: AES mode of operations. `default`: `AES.MODE_CBC`
            iv: initialization vector(iv) used during encryption. `default: 16 bytes null array`
        """
        if isinstance(key, str) and key.isprintable():
            key = _b64decode(key)
        self._key = key
        self.mode = mode
        self.iv = iv

    def decrypt(self, cipher_text, decode_output=True) -> Union[str, bytes]:

        if isinstance(cipher_text, str) and cipher_text.isprintable():
            cipher_text = _b64decode(cipher_text)

        if not isinstance(cipher_text, bytes):
            raise ValueError('Cipher text should be base64 decoded')

        plain_text = aes_new(self._key, self.mode, self.iv).decrypt(cipher_text)
        if decode_output:
            return unpad(plain_text, block_size).decode()
        return unpad(plain_text, block_size)

Rust implementation to decrypt a string

We are planning to move to rust based decryption as it will be fast. So, below decryption code is developed with same config (AES, CBC,etc..). The decrypt method in Decrypt impl is used to decrypt a string. The method was able to decrypt some encrypted strings but it is failing for some with error : Result::unwrap() on an Err value: InvalidByte(1470, 61) at line let result = decryptor.decrypt(&mut read_buffer, &mut write_buffer, true).unwrap();. but I was able to decrypt same string in Python and Java.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>dependencies:
base64 = "0.22.0"
rust-crypto = "^0.2"
</code>
<code>dependencies: base64 = "0.22.0" rust-crypto = "^0.2" </code>
dependencies:
base64 = "0.22.0"
rust-crypto = "^0.2"
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>extern crate crypto;
use crypto::{ buffer, aes, blockmodes };
use crypto::buffer::{ ReadBuffer, WriteBuffer, BufferResult };
use base64::prelude::*;
use crypto::symmetriccipher::Decryptor;
struct Decrypt {
key: Vec<u8>,
iv: [u8; 16],
}
impl Decrypt {
fn new(key: &str) -> Self {
Self {
key: BASE64_STANDARD.decode(key).unwrap(),
iv: [0; 16], // Default value for iv
}
}
fn decryptor(&self) -> Box<dyn Decryptor>{
let mut decryptor = aes::cbc_decryptor(
aes::KeySize::KeySize256,
self.key.as_slice(),
&self.iv,
blockmodes::PkcsPadding);
decryptor
}
fn decrypt(&self, encrypted_data: &str) -> String {
let encrypted_data = BASE64_STANDARD.decode(encrypted_data).unwrap();
let mut decryptor = self.decryptor();
let mut final_result = Vec::<u8>::new();
let mut read_buffer = buffer::RefReadBuffer::new(encrypted_data.as_slice());
let mut buffer = [0; 4096];
let mut write_buffer = buffer::RefWriteBuffer::new(&mut buffer);
loop {
let result = decryptor.decrypt(&mut read_buffer, &mut write_buffer, true).unwrap();
final_result.extend(write_buffer.take_read_buffer().take_remaining().iter().map(|&i| i));
match result {
BufferResult::BufferUnderflow => break,
BufferResult::BufferOverflow => { }
}
}
String::from_utf8(final_result).unwrap()
}
}
</code>
<code>extern crate crypto; use crypto::{ buffer, aes, blockmodes }; use crypto::buffer::{ ReadBuffer, WriteBuffer, BufferResult }; use base64::prelude::*; use crypto::symmetriccipher::Decryptor; struct Decrypt { key: Vec<u8>, iv: [u8; 16], } impl Decrypt { fn new(key: &str) -> Self { Self { key: BASE64_STANDARD.decode(key).unwrap(), iv: [0; 16], // Default value for iv } } fn decryptor(&self) -> Box<dyn Decryptor>{ let mut decryptor = aes::cbc_decryptor( aes::KeySize::KeySize256, self.key.as_slice(), &self.iv, blockmodes::PkcsPadding); decryptor } fn decrypt(&self, encrypted_data: &str) -> String { let encrypted_data = BASE64_STANDARD.decode(encrypted_data).unwrap(); let mut decryptor = self.decryptor(); let mut final_result = Vec::<u8>::new(); let mut read_buffer = buffer::RefReadBuffer::new(encrypted_data.as_slice()); let mut buffer = [0; 4096]; let mut write_buffer = buffer::RefWriteBuffer::new(&mut buffer); loop { let result = decryptor.decrypt(&mut read_buffer, &mut write_buffer, true).unwrap(); final_result.extend(write_buffer.take_read_buffer().take_remaining().iter().map(|&i| i)); match result { BufferResult::BufferUnderflow => break, BufferResult::BufferOverflow => { } } } String::from_utf8(final_result).unwrap() } } </code>
extern crate crypto;

use crypto::{ buffer, aes, blockmodes };
use crypto::buffer::{ ReadBuffer, WriteBuffer, BufferResult };
use base64::prelude::*;
use crypto::symmetriccipher::Decryptor;


struct Decrypt {
    key: Vec<u8>,
    iv: [u8; 16],
}

impl Decrypt {

    fn new(key: &str) -> Self {
        Self {
            key: BASE64_STANDARD.decode(key).unwrap(),
            iv: [0; 16], // Default value for iv
        }
    }

    fn decryptor(&self) -> Box<dyn Decryptor>{
        let mut decryptor = aes::cbc_decryptor(
            aes::KeySize::KeySize256,
            self.key.as_slice(),
            &self.iv,
            blockmodes::PkcsPadding);
        decryptor
    }

    fn decrypt(&self, encrypted_data: &str) -> String {

        let encrypted_data = BASE64_STANDARD.decode(encrypted_data).unwrap();

        let mut decryptor = self.decryptor();

        let mut final_result = Vec::<u8>::new();
        let mut read_buffer = buffer::RefReadBuffer::new(encrypted_data.as_slice());
        let mut buffer = [0; 4096];
        let mut write_buffer = buffer::RefWriteBuffer::new(&mut buffer);

        loop {
            let result = decryptor.decrypt(&mut read_buffer, &mut write_buffer, true).unwrap();
            final_result.extend(write_buffer.take_read_buffer().take_remaining().iter().map(|&i| i));
            match result {
                BufferResult::BufferUnderflow => break,
                BufferResult::BufferOverflow => { }
            }
        }

        String::from_utf8(final_result).unwrap()
    }
}

Another implementation of decryption logic

I tried another implementation as well using aes and cbc crates , but this is also failing with same issue sometimes and Unpad error or Padding issue sometimes.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>dependencies:
aes = "0.8.4"
base64 = "0.22.1"
cbc = "0.1.2"
</code>
<code>dependencies: aes = "0.8.4" base64 = "0.22.1" cbc = "0.1.2" </code>
dependencies:
aes = "0.8.4"
base64 = "0.22.1"
cbc = "0.1.2"
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>use aes::Aes256;
use aes::cipher::{block_padding::Pkcs7, BlockDecryptMut, KeyIvInit};
type Aes256CbcDec = cbc::Decryptor<aes::Aes256>;
use base64::prelude::*;
use cbc::Decryptor;
struct Decrypt {
key: Vec<u8>,
iv: [u8; 16],
}
impl Decrypt {
fn new(key: &str) -> Self {
Self {
key: BASE64_STANDARD.decode(key).unwrap(),
iv: [0; 16], // Default value for iv
}
}
fn decryptor(&self) -> Decryptor<Aes256>{
let decryptor = Aes256CbcDec::new_from_slices(
self.key.as_slice(),
&self.iv,
).unwrap();
decryptor
}
fn decrypt(&self, encrypted_data: &str) -> String {
let encrypted_data = BASE64_STANDARD.decode(encrypted_data).unwrap();
let mut decryptor = self.decryptor();
let mut buf = [0u8; 4096];
let d_str = decryptor.decrypt_padded_b2b_mut::<Pkcs7>(&encrypted_data,
&mut buf);
let res = d_str.unwrap().to_vec();
String::from_utf8(res).unwrap()
}
}
</code>
<code>use aes::Aes256; use aes::cipher::{block_padding::Pkcs7, BlockDecryptMut, KeyIvInit}; type Aes256CbcDec = cbc::Decryptor<aes::Aes256>; use base64::prelude::*; use cbc::Decryptor; struct Decrypt { key: Vec<u8>, iv: [u8; 16], } impl Decrypt { fn new(key: &str) -> Self { Self { key: BASE64_STANDARD.decode(key).unwrap(), iv: [0; 16], // Default value for iv } } fn decryptor(&self) -> Decryptor<Aes256>{ let decryptor = Aes256CbcDec::new_from_slices( self.key.as_slice(), &self.iv, ).unwrap(); decryptor } fn decrypt(&self, encrypted_data: &str) -> String { let encrypted_data = BASE64_STANDARD.decode(encrypted_data).unwrap(); let mut decryptor = self.decryptor(); let mut buf = [0u8; 4096]; let d_str = decryptor.decrypt_padded_b2b_mut::<Pkcs7>(&encrypted_data, &mut buf); let res = d_str.unwrap().to_vec(); String::from_utf8(res).unwrap() } } </code>
use aes::Aes256;
use aes::cipher::{block_padding::Pkcs7, BlockDecryptMut, KeyIvInit};

type Aes256CbcDec = cbc::Decryptor<aes::Aes256>;

use base64::prelude::*;
use cbc::Decryptor;



struct Decrypt {
    key: Vec<u8>,
    iv: [u8; 16],
}

impl Decrypt {

    fn new(key: &str) -> Self {
        Self {
            key: BASE64_STANDARD.decode(key).unwrap(),
            iv: [0; 16], // Default value for iv
        }
    }

    fn decryptor(&self) -> Decryptor<Aes256>{
        let decryptor = Aes256CbcDec::new_from_slices(
            self.key.as_slice(),
            &self.iv,
        ).unwrap();
        decryptor
    }

    fn decrypt(&self, encrypted_data: &str) -> String {

        let encrypted_data = BASE64_STANDARD.decode(encrypted_data).unwrap();

        let mut decryptor = self.decryptor();
        let mut buf = [0u8; 4096];
        let d_str = decryptor.decrypt_padded_b2b_mut::<Pkcs7>(&encrypted_data,
                                                              &mut buf);
        let  res = d_str.unwrap().to_vec();

        String::from_utf8(res).unwrap()
    }
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật