Advertisement
Anton0093

Lab_3 (Sem_2) GammaCode

Mar 5th, 2021
1,224
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.50 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.Scanner;
  3.  
  4. public class gammaCode {
  5.  
  6.     public static void Encode(String path) throws IOException {
  7.  
  8.         FileInputStream fileInputStream = new FileInputStream(new File(path));
  9.  
  10.         byte[] buffer = new byte[fileInputStream.available()];
  11.         byte[] bufferRand = new byte[buffer.length];
  12.  
  13.         // считываем файл в массив байт
  14.         fileInputStream.read(buffer, 0, buffer.length);
  15.  
  16.         // объявляем класс lfsr из прошлой лабораторной
  17.         LFSR lfsr = new LFSR(0xC4, 20);
  18.  
  19.         // заполняем массив рандомными
  20.         for (int i = 0; i < bufferRand.length; i++) {
  21.             bufferRand[i] = (byte) lfsr.next(i);
  22.         }
  23.  
  24.         // шифруем
  25.         for (int i = 0; i < buffer.length; i++) {
  26.             buffer[i] = (byte) (buffer[i] ^ bufferRand[i]);
  27.         }
  28.  
  29.         // записываем обратно в файл
  30.         FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
  31.         fileOutputStream.write(buffer, 0, buffer.length);
  32.     }
  33.  
  34.     public static void Decode(String path) throws IOException {
  35.  
  36.         FileInputStream fileInputStream = new FileInputStream(new File(path));
  37.  
  38.         byte[] buffer = new byte[fileInputStream.available()];
  39.         byte[] bufferRand = new byte[buffer.length];
  40.  
  41.         // считываем файл в массив байт
  42.         fileInputStream.read(buffer, 0, buffer.length);
  43.  
  44.         // объявляем класс lfsr из прошлой лабораторной
  45.         LFSR lfsr = new LFSR(0xC4, 20);
  46.  
  47.         // заполняем массив рандомными
  48.         for (int i = 0; i < bufferRand.length; i++) {
  49.             bufferRand[i] = (byte) lfsr.next(i);
  50.         }
  51.  
  52.         // дешифруем
  53.         for (int i = 0; i < buffer.length; i++) {
  54.             buffer[i] = (byte) (buffer[i] ^ bufferRand[i]);
  55.         }
  56.  
  57.         // записываем обратно в файл
  58.         FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
  59.         fileOutputStream.write(buffer, 0, buffer.length);
  60.     }
  61.  
  62.     public static void main(String[] args) throws IOException {
  63.  
  64.         // вводим путь к файлу
  65.         Scanner scanner = new Scanner(System.in);
  66.         String path = scanner.nextLine();
  67.  
  68.         // кодируем
  69.         Encode(path);
  70.  
  71.         // декодируем
  72.         Decode(path);
  73.     }
  74. }
  75.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement