AES暗号化を復号化する方法
7 views (last 30 days)
Show older comments
生成AIでデータのAES暗号化、復号化するコードを作成しました。
復号化されたデータ(data3.csv)を確認すると、ヘッダーからデータまで1文字ずつ改行されたデータとなっていました。
元のデータのとおり、復号化するためには、どのような修正をすればよいでしょうか。
暗号化
% Load the required library
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.spec.IvParameterSpec;
% Read the CSV file
data = fileread('data.csv');
% Convert the data to bytes
dataBytes = uint8(data);
% Define the AES key and IV (Initialization Vector)
key = uint8('1234567890123456'); % 16 bytes for AES-128
iv = uint8('1234567890123456'); % 16 bytes IV
% Create AES cipher
cipher = Cipher.getInstance('AES/CBC/PKCS5Padding');
keySpec = SecretKeySpec(key, 'AES');
ivSpec = IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
% Encrypt the data
encryptedData = cipher.doFinal(dataBytes);
% Save the encrypted data to a file
writematrix(encryptedData,'data2.csv');
復号化
% Load the required library
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.spec.IvParameterSpec;
% Read the CSV file
data2 = readmatrix('data2.csv');
% Define the AES key and IV (Initialization Vector)
key = uint8('1234567890123456'); % 16 bytes for AES-128
iv = uint8('1234567890123456'); % 16 bytes IV
% Create AES cipher for decryption
cipher = Cipher.getInstance('AES/CBC/PKCS5Padding');
keySpec = SecretKeySpec(key,'AES');
ivSpec = IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
% Decrypt the data
decryptedData = cipher.doFinal(data2);
% Convert decrypted bytes back to string
decryptedString = char(decryptedData);
% Display the original data
disp(decryptedString);
% Save the encrypted data to a file
writematrix(decryptedString,'data3.csv');
1 Comment
Walter Roberson
on 16 Dec 2024
Approximate translation:
How to decrypt AES encryption
I created a code to AES encrypt and decrypt data using a generation AI. When I checked the decrypted data (data3.csv), I found that each character was on a new line from the header to the data. What modifications should I make to decrypt the data to the original data?
Answers (1)
Walter Roberson
on 16 Dec 2024
Moved: Walter Roberson
on 16 Dec 2024
Experiment with
decryptedString = reshape(decryptedString, 1, []);
after
decryptedString = char(decryptedData);
3 Comments
Walter Roberson
on 16 Dec 2024
Moved: Walter Roberson
on 16 Dec 2024
Approximate translation:
Thank you! I was able to achieve what I wanted.
One thing, when I checked the decrypted data (data3.csv) at the end, text data was created in the following format. Could you also tell me the modified code to output to a comma-separated csv file?
Thank you in advance.
It may be okay to write this code at the end, but is it difficult to express it using writetable? .
See Also
Categories
Find more on Encryption / Cryptography in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!