Commit a64b2907 authored by Egor Dubenetskiy's avatar Egor Dubenetskiy 🚴🏼

Добавить Main

parent b1da36a8
Pipeline #127892021 passed with stage
in 56 seconds
package space.banka.ifmo.infosec.magma.configuration;
import space.banka.ifmo.infosec.magma.features.cipher.BlockCipher;
import space.banka.ifmo.infosec.magma.features.cipher.BlockCipherMode;
import space.banka.ifmo.infosec.magma.features.cipher.modes.CipherBlockChainingMode;
import space.banka.ifmo.infosec.magma.features.magma.MagmaCipher;
import space.banka.ifmo.infosec.magma.features.padding.PKCS7Padding;
import space.banka.ifmo.infosec.magma.features.padding.Padding;
import space.banka.ifmo.infosec.magma.features.substitution.MagmaSubstitutionBlock;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.LongBuffer;
public class Main {
public static final int EXIT_CODE_ERROR = 1;
public static void main(String[] args) throws IOException {
if (args.length != 4) {
System.err.println("Arguments: <command> <input> <key> <iv>");
}
String command = args[0];
String inputFile = args[1];
FileInputStream inputReader = new FileInputStream(inputFile);
byte[] input = inputReader.readAllBytes();
String keyFile = args[2];
FileInputStream keyReader = new FileInputStream(keyFile);
byte[] key = keyReader.readNBytes(32);
String ivFile = args[3];
FileInputStream ivReader = new FileInputStream(ivFile);
byte[] ivBytes = ivReader.readNBytes(8);
long iv = ByteBuffer.wrap(ivBytes).asLongBuffer().get();
String outputFile;
BlockCipher magmaCipher = new MagmaCipher(MagmaSubstitutionBlock.ID_GOST_28147_89_CRYPTOPRO_A_PARAM_SET_1);
BlockCipherMode cipherMode = new CipherBlockChainingMode(iv, magmaCipher);
Padding padding = new PKCS7Padding();
switch (command) {
case "encrypt":
outputFile = inputFile + ".encrypted";
long[] plaintextBlocks = padding.padAndSplit(input);
long[] encrypted = cipherMode.encrypt(plaintextBlocks, key);
try (DataOutputStream dataOutputStream = new DataOutputStream(new FileOutputStream(outputFile))) {
for (long l : encrypted) {
dataOutputStream.writeLong(l);
}
}
break;
case "decrypt":
outputFile = inputFile + ".decrypted";
long[] encryptedBlocks = LongBuffer.allocate(input.length / Long.BYTES).put(ByteBuffer.wrap(input).asLongBuffer()).array();
long[] decryptedBlocks = cipherMode.decrypt(encryptedBlocks, key);
byte[] decryptedBytes = padding.assembleAndClip(decryptedBlocks);
try (FileOutputStream file = new FileOutputStream(outputFile)) {
file.write(decryptedBytes);
}
break;
default:
System.err.println("Unsupported command: " + command);
System.exit(EXIT_CODE_ERROR);
}
}
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment