简体   繁体   中英

using CryptoJS with hex-string

I want to connect to a bluetooth device. Communication is via Hex-Strings only. I need to encode a 16 byte value. As a result I also expect a 16 byte value. In my implementation CryptoJS always returns a longer result. According to the documentation the IV is not needed. ("All the 16-byte data must be encrypted with the Customer Master Key currently stored in the device, using AES128 CBC cipher mode") Therefore I set the IV to 00000000000000000000000000000000 because CryptoJS seems to require it. What am I doing wrong?

const CryptoJS = require('crypto-js');
const value =  CryptoJS.enc.Hex.parse('5ff58680541c5a5903f4833dfaa4281f');
const key  = CryptoJS.enc.Hex.parse('41435231323535552d4a312041757458'); // known master key
const ivvar   = CryptoJS.enc.Hex.parse('00000000000000000000000000000000');
const encryptedString = CryptoJS.AES.encrypt(value, key, {iv: ivvar, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.NoPadding}).toString();

// current result is edijc9R7sl3zwZVrBBBrFQ==

Sure, the result is only a string, but it is too long anyway.

For the sake of completeness I would like to add the solution, which works for me. (Thanks to @Topaco)

encrypt(valueStringHex, keyStringHex) {
    const CryptoJS = require('crypto-js');
    const value =  CryptoJS.enc.Hex.parse(valueStringHex);
    const key  = CryptoJS.enc.Hex.parse(keyStringHex);
    const ivvar   = CryptoJS.enc.Hex.parse('00000000000000000000000000000000');
    const encryptedStringHex = CryptoJS.AES.encrypt(value, key, {iv: ivvar, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.NoPadding}).ciphertext.toString();
    return encryptedStringHex;
    }

// encrypt('5ff58680541c5a5903f4833dfaa4281f', '41435231323535552d4a312041757458')
// returns 79d8a373d47bb25df3c1956b04106b15
decrypt(valueStringHex, keyStringHex) {
    const CryptoJS = require('crypto-js');
    const value = CryptoJS.enc.Hex.parse(valueStringHex);
    const key = CryptoJS.enc.Hex.parse(keyStringHex);
    const ivvar   = CryptoJS.enc.Hex.parse('00000000000000000000000000000000');
    const decryptedStringHex = CryptoJS.AES.decrypt({ciphertext: value}, key, {iv: ivvar, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.NoPadding});
    return decryptedStringHex.toString();
    }

// decrypt('79d8a373d47bb25df3c1956b04106b15', '41435231323535552d4a312041757458')
// returns 5ff58680541c5a5903f4833dfaa4281f

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM