Encrypted Packets

Краен срок
17.12.2019 17:00

Срокът за предаване на решения е отминал

Encrypted Packets

Така и така сме тръгнали да пращаме пакети напред-назад, защо и да не ги криптираме, да сме сигурни, че ако някой по средата ги прихване, няма да разбере за какво си говорим. Разбира се, трябва да използваме супер-сигурен алгоритъм, така че ще XOR-нем всеки байт с някакво число (note: това е шега, не "криптирайте" неща с XOR-ване).

Криптирането работи така:

  • Имаме някакъв slice от байтове ("payload").
  • Имаме 32-битов шифър ("cypher").
  • Разбиваме 32-битовото число на 4 байта, big endian.
  • Вземаме първите 4 байта на payload-a.
  • XOR-ваме байтовете на шифъра с тези на payload-а, един по един
  • Вземаме току-що криптираните 4 байта (резултата от криптирането) и използваме тях за нов шифър
  • И така докрай

Ако в който и да е момент няма 4 байта в остатъка от payload-а -- колкото има.

За декриптирането единствено ще ви кажем, че XOR-ването два пъти с едно и също число се неутрализира, тоест (a ^ b) ^ b ви дава просто a.

Интерфейса очакваме да изглежда така:

pub struct Packet {
    pub payload: Vec<u8>,
}

impl Packet {
    pub fn new(source: &[u8]) -> Self {
        Self { payload: source.to_vec() }
    }

    pub fn encrypt(&self, cypher: u32) -> EncryptedPacket {
        unimplemented!()
    }
}

pub struct EncryptedPacket {
    pub payload: Vec<u8>,
}

impl EncryptedPacket {
    pub fn decrypt(&self, cypher: u32) -> Packet {
        unimplemented!()
    }
}

Вече нямаме дължини и чексуми за опростяване, приемаме, че ги оправихме тия работи вече в домашното. Примерно извикване може да изглежда така:

let packet = Packet::new(b"Secret message, plz don't hack");
assert_eq!(packet.encrypt(0xDEADBEEF).decrypt(0xDEADBEEF).payload, packet.payload);

Решения

Андрей
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Андрей
pub struct Packet {
pub payload: Vec<u8>,
}
impl Packet {
pub fn new(source: &[u8]) -> Self {
Self { payload: source.to_vec() }
}
pub fn encrypt(&self, cypher: u32) -> EncryptedPacket {
let mut payload = self.payload.as_slice();
let mut result = Vec::with_capacity(payload.len());
let mut cypher_bytes: Vec<u8> = cypher.to_be_bytes().into_iter().cloned().collect();
while payload.len() > 0 {
let (chunk, remainder) = payload.split_at(4.min(payload.len()));
let encrypted_chunk = chunk.into_iter().zip(cypher_bytes.into_iter()).
map(|(pb, cb)| *pb ^ cb).
collect();
result.extend(&encrypted_chunk);
cypher_bytes = encrypted_chunk;
payload = remainder;
}
EncryptedPacket { payload: result }
}
}
pub struct EncryptedPacket {
pub payload: Vec<u8>,
}
impl EncryptedPacket {
pub fn decrypt(&self, cypher: u32) -> Packet {
let mut payload = self.payload.as_slice();
let mut result = Vec::with_capacity(payload.len());
let mut cypher_bytes: Vec<u8> = cypher.to_be_bytes().into_iter().cloned().collect();
while payload.len() > 0 {
let (chunk, remainder) = payload.split_at(4.min(payload.len()));
let decrypted_chunk = chunk.into_iter().zip(cypher_bytes.into_iter()).
map(|(pb, cb)| *pb ^ cb).
collect::<Vec<u8>>();
result.extend(&decrypted_chunk);
cypher_bytes = chunk.to_vec();
payload = remainder;
}
Packet { payload: result }
}
}
Compiling solution v0.1.0 (/tmp/d20191217-2173579-xaogs4/solution)
    Finished dev [unoptimized + debuginfo] target(s) in 1.93s
     Running target/debug/deps/solution-28d77f5ef5bfec2e

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

     Running target/debug/deps/solution_test-b0ad3c2037f2314d

running 4 tests
test solution_test::test_exact_cyphers ... ok
test solution_test::test_full_roundtrip ... ok
test solution_test::test_roundtrip_with_specific_length ... ok
test solution_test::test_several_iterations ... ok

test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

   Doc-tests solution

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Стефан Чолаков
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Стефан Чолаков
pub struct Packet {
pub payload: Vec<u8>,
}
pub fn helper(payload: &Vec<u8>, cypher:u32, encrypt:bool)-> Vec<u8>{
let mut cypher_as_bytes = cypher.to_be_bytes();
let mut result: Vec<u8> = Vec::new();
let mut cypher_index = 0;
let mut payload_index = 0;
while payload_index < payload.len() {
let current_byte = payload[payload_index] ^ cypher_as_bytes[cypher_index];
result.push(current_byte);
if encrypt {
cypher_as_bytes[cypher_index] = current_byte;
}else{
cypher_as_bytes[cypher_index] = payload[payload_index];
}
payload_index +=1;
cypher_index+=1;
if cypher_index==4 { cypher_index = 0; }
}
result
}
impl Packet {
pub fn new(source: &[u8]) -> Self {
Self { payload: source.to_vec() }
}
pub fn encrypt(&self, cypher: u32) -> EncryptedPacket {
let payload = helper(&self.payload,cypher,true);
EncryptedPacket{payload}
}
}
pub struct EncryptedPacket {
pub payload: Vec<u8> ,
}
impl EncryptedPacket {
pub fn decrypt(&self, cypher: u32) -> Packet {
let payload = helper(&self.payload,cypher,false);
Packet{payload}
}
}
Compiling solution v0.1.0 (/tmp/d20191217-2173579-1ft4wft/solution)
    Finished dev [unoptimized + debuginfo] target(s) in 1.94s
     Running target/debug/deps/solution-28d77f5ef5bfec2e

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

     Running target/debug/deps/solution_test-b0ad3c2037f2314d

running 4 tests
test solution_test::test_exact_cyphers ... ok
test solution_test::test_full_roundtrip ... ok
test solution_test::test_roundtrip_with_specific_length ... ok
test solution_test::test_several_iterations ... ok

test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

   Doc-tests solution

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Антонио Миндов
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Антонио Миндов
use std::cmp::min;
fn xor_encryption(bytes: &[u8], cypher: u32, decrypt: bool) -> Vec<u8> {
let mut result = Vec::with_capacity(bytes.len());
let mut current_cypher: Vec<u8> = cypher.to_be_bytes().to_vec();
let mut bytes = bytes;
while bytes.len() > 0 {
let (current_bytes, rest) = bytes.split_at(min(4, bytes.len()));
let encrypted_bytes: Vec<u8> = current_bytes.iter().zip(current_cypher)
.map(|bytes| bytes.0 ^ bytes.1)
.collect();
current_cypher = if decrypt { current_bytes.to_vec() }
else { encrypted_bytes.clone() };
result.extend(encrypted_bytes);
bytes = rest;
}
result
}
pub struct Packet {
pub payload: Vec<u8>
}
impl Packet {
pub fn new(source: &[u8]) -> Self {
Self { payload: source.to_vec() }
}
pub fn encrypt(&self, cypher: u32) -> EncryptedPacket {
EncryptedPacket { payload: xor_encryption(&self.payload, cypher, false) }
}
}
pub struct EncryptedPacket {
pub payload: Vec<u8>
}
impl EncryptedPacket {
pub fn decrypt(&self, cypher: u32) -> Packet {
Packet { payload: xor_encryption(&self.payload, cypher, true) }
}
}
Compiling solution v0.1.0 (/tmp/d20191217-2173579-wmvwr6/solution)
    Finished dev [unoptimized + debuginfo] target(s) in 2.14s
     Running target/debug/deps/solution-28d77f5ef5bfec2e

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

     Running target/debug/deps/solution_test-b0ad3c2037f2314d

running 4 tests
test solution_test::test_exact_cyphers ... ok
test solution_test::test_full_roundtrip ... ok
test solution_test::test_roundtrip_with_specific_length ... ok
test solution_test::test_several_iterations ... ok

test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

   Doc-tests solution

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Петър Петров
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Петър Петров
pub struct Packet {
pub payload: Vec<u8>,
}
impl Packet {
pub fn new(source: &[u8]) -> Self {
Self { payload: source.to_vec() }
}
pub fn encrypt(&self, cypher: u32) -> EncryptedPacket {
let mut len=self.payload.len();
let mut count=0;
let mut b1 : u8 = ((cypher >> 24) & 0xff) as u8;
let mut b2 : u8 = ((cypher >> 16) & 0xff) as u8;
let mut b3 : u8 = ((cypher >> 8) & 0xff) as u8;
let mut b4 : u8 = (cypher & 0xff) as u8;
let mut vec = Vec::new();
loop {
if len >= 4 {
let x1=b1^self.payload[count];
b1=x1;
vec.push(x1);
count+=1;
let x2=b2^self.payload[count];
b2=x2;
vec.push(x2);
count+=1;
let x3=b3^self.payload[count];
b3=x3;
vec.push(x3);
count+=1;
let x4=b4^self.payload[count];
b4=x4;
vec.push(x4);
count+=1;
len=len-4;
}
else
{
break;
}
}
if len > 0 {
if len == 1 {
let x1=b1^self.payload[count];
b1=x1;
vec.push(x1);
}
else if len == 2 {
let x1=b1^self.payload[count];
b1=x1;
vec.push(x1);
count+=1;
let x2=b2^self.payload[count];
b2=x2;
vec.push(x2);
count+=1;
}
else {
let x1=b1^self.payload[count];
b1=x1;
vec.push(x1);
count+=1;
let x2=b2^self.payload[count];
b2=x2;
vec.push(x2);
count+=1;
let x3=b3^self.payload[count];
b3=x3;
vec.push(x3);
count+=1;
}
}
EncryptedPacket { payload:vec}
}
}
pub fn toVector(payload:&Vec<u8>,cypher: u32) -> Vec<u8> {
let mut len=payload.len();
let mut count=0;
let mut b1 : u8 = ((cypher >> 24) & 0xff) as u8;
let mut b2 : u8 = ((cypher >> 16) & 0xff) as u8;
let mut b3 : u8 = ((cypher >> 8) & 0xff) as u8;
let mut b4 : u8 = (cypher & 0xff) as u8;
let mut vec = Vec::new();
loop {
if len >= 4 {
let x1=b1^payload[count];
b1=payload[count];
vec.push(x1);
count+=1;
let x2=b2^payload[count];
b2=payload[count];
vec.push(x2);
count+=1;
let x3=b3^payload[count];
b3=payload[count];
vec.push(x3);
count+=1;
let x4=b4^payload[count];
b4=payload[count];
vec.push(x4);
count+=1;
len=len-4;
}
else
{
break;
}
}
if len > 0 {
if len == 1 {
let x1=b1^payload[count];
b1=x1;
vec.push(x1);
}
else if len == 2 {
let x1=b1^payload[count];
b1=x1;
vec.push(x1);
count+=1;
let x2=b2^payload[count];
b2=x2;
vec.push(x2);
count+=1;
}
else {
let x1=b1^payload[count];
b1=x1;
vec.push(x1);
count+=1;
let x2=b2^payload[count];
b2=x2;
vec.push(x2);
count+=1;
let x3=b3^payload[count];
b3=x3;
vec.push(x3);
count+=1;
}
}
vec
}
pub struct EncryptedPacket {
pub payload: Vec<u8>,
}
impl EncryptedPacket {
pub fn decrypt(&self, cypher: u32) -> Packet {
let mut vec=toVector(&self.payload,cypher);
Packet { payload:vec}
}
}
Compiling solution v0.1.0 (/tmp/d20191217-2173579-6aljaj/solution)
warning: value assigned to `b1` is never read
   --> src/lib.rs:114:17
    |
114 |                 b1=x1;
    |                 ^^
    |
    = note: `#[warn(unused_assignments)]` on by default
    = help: maybe it is overwritten before being read?

warning: value assigned to `b1` is never read
   --> src/lib.rs:119:16
    |
119 |                b1=x1;
    |                ^^
    |
    = help: maybe it is overwritten before being read?

warning: value assigned to `b2` is never read
   --> src/lib.rs:123:16
    |
123 |                b2=x2;
    |                ^^
    |
    = help: maybe it is overwritten before being read?

warning: value assigned to `count` is never read
   --> src/lib.rs:125:16
    |
125 |                count+=1;
    |                ^^^^^
    |
    = help: maybe it is overwritten before being read?

warning: value assigned to `b1` is never read
   --> src/lib.rs:129:16
    |
129 |                b1=x1;
    |                ^^
    |
    = help: maybe it is overwritten before being read?

warning: value assigned to `b2` is never read
   --> src/lib.rs:133:16
    |
133 |                b2=x2;
    |                ^^
    |
    = help: maybe it is overwritten before being read?

warning: value assigned to `b3` is never read
   --> src/lib.rs:137:16
    |
137 |                b3=x3;
    |                ^^
    |
    = help: maybe it is overwritten before being read?

warning: value assigned to `count` is never read
   --> src/lib.rs:139:16
    |
139 |                count+=1;
    |                ^^^^^
    |
    = help: maybe it is overwritten before being read?

warning: value assigned to `b1` is never read
  --> src/lib.rs:46:17
   |
46 |                 b1=x1;
   |                 ^^
   |
   = help: maybe it is overwritten before being read?

warning: value assigned to `b1` is never read
  --> src/lib.rs:51:16
   |
51 |                b1=x1;
   |                ^^
   |
   = help: maybe it is overwritten before being read?

warning: value assigned to `b2` is never read
  --> src/lib.rs:55:16
   |
55 |                b2=x2;
   |                ^^
   |
   = help: maybe it is overwritten before being read?

warning: value assigned to `count` is never read
  --> src/lib.rs:57:16
   |
57 |                count+=1;
   |                ^^^^^
   |
   = help: maybe it is overwritten before being read?

warning: value assigned to `b1` is never read
  --> src/lib.rs:61:16
   |
61 |                b1=x1;
   |                ^^
   |
   = help: maybe it is overwritten before being read?

warning: value assigned to `b2` is never read
  --> src/lib.rs:65:16
   |
65 |                b2=x2;
   |                ^^
   |
   = help: maybe it is overwritten before being read?

warning: value assigned to `b3` is never read
  --> src/lib.rs:69:16
   |
69 |                b3=x3;
   |                ^^
   |
   = help: maybe it is overwritten before being read?

warning: value assigned to `count` is never read
  --> src/lib.rs:71:16
   |
71 |                count+=1;
   |                ^^^^^
   |
   = help: maybe it is overwritten before being read?

warning: variable does not need to be mutable
   --> src/lib.rs:150:12
    |
150 |        let mut vec=toVector(&self.payload,cypher);
    |            ----^^^
    |            |
    |            help: remove this `mut`
    |
    = note: `#[warn(unused_mut)]` on by default

warning: function `toVector` should have a snake case name
  --> src/lib.rs:78:8
   |
78 | pub fn toVector(payload:&Vec<u8>,cypher: u32) -> Vec<u8> {
   |        ^^^^^^^^ help: convert the identifier to snake case: `to_vector`
   |
   = note: `#[warn(non_snake_case)]` on by default

warning: value assigned to `b1` is never read
   --> src/lib.rs:114:17
    |
114 |                 b1=x1;
    |                 ^^
    |
    = note: `#[warn(unused_assignments)]` on by default
    = help: maybe it is overwritten before being read?

warning: value assigned to `b1` is never read
   --> src/lib.rs:119:16
    |
119 |                b1=x1;
    |                ^^
    |
    = help: maybe it is overwritten before being read?

warning: value assigned to `b2` is never read
   --> src/lib.rs:123:16
    |
123 |                b2=x2;
    |                ^^
    |
    = help: maybe it is overwritten before being read?

warning: value assigned to `count` is never read
   --> src/lib.rs:125:16
    |
125 |                count+=1;
    |                ^^^^^
    |
    = help: maybe it is overwritten before being read?

warning: value assigned to `b1` is never read
   --> src/lib.rs:129:16
    |
129 |                b1=x1;
    |                ^^
    |
    = help: maybe it is overwritten before being read?

warning: value assigned to `b2` is never read
   --> src/lib.rs:133:16
    |
133 |                b2=x2;
    |                ^^
    |
    = help: maybe it is overwritten before being read?

warning: value assigned to `b3` is never read
   --> src/lib.rs:137:16
    |
137 |                b3=x3;
    |                ^^
    |
    = help: maybe it is overwritten before being read?

warning: value assigned to `count` is never read
   --> src/lib.rs:139:16
    |
139 |                count+=1;
    |                ^^^^^
    |
    = help: maybe it is overwritten before being read?

warning: value assigned to `b1` is never read
  --> src/lib.rs:46:17
   |
46 |                 b1=x1;
   |                 ^^
   |
   = help: maybe it is overwritten before being read?

warning: value assigned to `b1` is never read
  --> src/lib.rs:51:16
   |
51 |                b1=x1;
   |                ^^
   |
   = help: maybe it is overwritten before being read?

warning: value assigned to `b2` is never read
  --> src/lib.rs:55:16
   |
55 |                b2=x2;
   |                ^^
   |
   = help: maybe it is overwritten before being read?

warning: value assigned to `count` is never read
  --> src/lib.rs:57:16
   |
57 |                count+=1;
   |                ^^^^^
   |
   = help: maybe it is overwritten before being read?

warning: value assigned to `b1` is never read
  --> src/lib.rs:61:16
   |
61 |                b1=x1;
   |                ^^
   |
   = help: maybe it is overwritten before being read?

warning: value assigned to `b2` is never read
  --> src/lib.rs:65:16
   |
65 |                b2=x2;
   |                ^^
   |
   = help: maybe it is overwritten before being read?

warning: value assigned to `b3` is never read
  --> src/lib.rs:69:16
   |
69 |                b3=x3;
   |                ^^
   |
   = help: maybe it is overwritten before being read?

warning: value assigned to `count` is never read
  --> src/lib.rs:71:16
   |
71 |                count+=1;
   |                ^^^^^
   |
   = help: maybe it is overwritten before being read?

warning: variable does not need to be mutable
   --> src/lib.rs:150:12
    |
150 |        let mut vec=toVector(&self.payload,cypher);
    |            ----^^^
    |            |
    |            help: remove this `mut`
    |
    = note: `#[warn(unused_mut)]` on by default

warning: function `toVector` should have a snake case name
  --> src/lib.rs:78:8
   |
78 | pub fn toVector(payload:&Vec<u8>,cypher: u32) -> Vec<u8> {
   |        ^^^^^^^^ help: convert the identifier to snake case: `to_vector`
   |
   = note: `#[warn(non_snake_case)]` on by default

    Finished dev [unoptimized + debuginfo] target(s) in 1.73s
     Running target/debug/deps/solution-28d77f5ef5bfec2e

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

     Running target/debug/deps/solution_test-b0ad3c2037f2314d

running 4 tests
test solution_test::test_exact_cyphers ... ok
test solution_test::test_full_roundtrip ... ok
test solution_test::test_roundtrip_with_specific_length ... ok
test solution_test::test_several_iterations ... ok

test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

   Doc-tests solution

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Димитър Иринков
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Димитър Иринков
use std::mem::size_of;
pub struct Packet {
pub payload: Vec<u8>,
}
pub struct EncryptedPacket {
pub payload: Vec<u8>,
}
fn encrypt_step(bytes: &mut [u8], cypher: &mut [u8;4]) {
for (a,b) in bytes.iter_mut().zip(cypher.iter_mut()) {
*a = *a ^ *b;
*b = *a;
}
}
fn decrypt_step(bytes: &mut [u8], cypher: &mut [u8;4]) {
for (a,b) in bytes.iter_mut().zip(cypher.iter_mut()) {
let temp = *a;
*a = *a ^ *b;
*b = temp;
}
}
fn de_en_crypt(payload: &[u8], cypher: u32, step: fn(&mut [u8], &mut [u8;4])) -> Vec<u8> {
let mut v = payload.to_vec();
let mut cypher = cypher.to_be_bytes();
v
.chunks_mut(size_of::<u32>())
.for_each(|bytes| {
step(bytes, &mut cypher);
});
v
}
impl Packet {
pub fn new(source: &[u8]) -> Self {
Self { payload: source.to_vec() }
}
pub fn encrypt(&self, cypher: u32) -> EncryptedPacket {
let encrypted = de_en_crypt(&self.payload, cypher, encrypt_step);
EncryptedPacket{ payload: encrypted}
}
}
impl EncryptedPacket {
pub fn decrypt(&self, cypher: u32) -> Packet {
let decrypted = de_en_crypt(&self.payload, cypher, decrypt_step);
Packet{ payload: decrypted}
}
}
Compiling solution v0.1.0 (/tmp/d20191217-2173579-7mtap4/solution)
    Finished dev [unoptimized + debuginfo] target(s) in 1.76s
     Running target/debug/deps/solution-28d77f5ef5bfec2e

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

     Running target/debug/deps/solution_test-b0ad3c2037f2314d

running 4 tests
test solution_test::test_exact_cyphers ... ok
test solution_test::test_full_roundtrip ... ok
test solution_test::test_roundtrip_with_specific_length ... ok
test solution_test::test_several_iterations ... ok

test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

   Doc-tests solution

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Йоан Стоянов
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Йоан Стоянов
pub struct Packet {
pub payload: Vec<u8>,
}
impl Packet {
pub fn new(source: &[u8]) -> Self {
Self { payload: source.to_vec() }
}
pub fn encrypt(&self, cypher: u32) -> EncryptedPacket {
let mut bytes = cypher.to_be_bytes();
let mut encrypted: Vec<u8> = Vec::new();;
let mut current;
let mut i:usize = 0;
for element in &self.payload{
current = bytes[i]^element;
encrypted.push(current);
bytes[i]=current;
i+=1; i=i%4;
}
EncryptedPacket{payload: encrypted}
}
}
pub struct EncryptedPacket {
pub payload: Vec<u8>,
}
impl EncryptedPacket {
pub fn decrypt(&self, cypher: u32) -> Packet {
let mut bytes = cypher.to_be_bytes();
let mut encrypted: Vec<u8> = Vec::new();;
let mut current;
let mut i:usize = 0;
for element in &self.payload{
current = bytes[i]^element;
encrypted.push(current);
bytes[i]=*element;
i+=1; i=i%4;
}
Packet{payload: encrypted}
}
}
#[test]
fn test_basic_iteration() {
let packet = Packet::new(b"Secret message, plz don't hack");
assert_eq!(packet.encrypt(0xDEADBEEF).decrypt(0xDEADBEEF).payload, packet.payload);
}
Compiling solution v0.1.0 (/tmp/d20191217-2173579-t7rc18/solution)
warning: unnecessary trailing semicolon
  --> src/lib.rs:12:49
   |
12 |         let mut encrypted: Vec<u8> = Vec::new();;
   |                                                 ^ help: remove this semicolon
   |
   = note: `#[warn(redundant_semicolon)]` on by default

warning: unnecessary trailing semicolon
  --> src/lib.rs:32:49
   |
32 |         let mut encrypted: Vec<u8> = Vec::new();;
   |                                                 ^ help: remove this semicolon

warning: unnecessary trailing semicolon
  --> src/lib.rs:12:49
   |
12 |         let mut encrypted: Vec<u8> = Vec::new();;
   |                                                 ^ help: remove this semicolon
   |
   = note: `#[warn(redundant_semicolon)]` on by default

warning: unnecessary trailing semicolon
  --> src/lib.rs:32:49
   |
32 |         let mut encrypted: Vec<u8> = Vec::new();;
   |                                                 ^ help: remove this semicolon

    Finished dev [unoptimized + debuginfo] target(s) in 1.90s
     Running target/debug/deps/solution-28d77f5ef5bfec2e

running 1 test
test test_basic_iteration ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

     Running target/debug/deps/solution_test-b0ad3c2037f2314d

running 4 tests
test solution_test::test_exact_cyphers ... ok
test solution_test::test_full_roundtrip ... ok
test solution_test::test_roundtrip_with_specific_length ... ok
test solution_test::test_several_iterations ... ok

test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

   Doc-tests solution

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Стоян Ефтимов
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Стоян Ефтимов
pub struct Packet {
pub payload: Vec<u8>,
}
impl Packet {
const CIPHER_SIZE: u8 = 4;
pub fn new(source: &[u8]) -> Self {
Self { payload: source.to_vec() }
}
pub fn encrypt(&self, cipher: u32) -> EncryptedPacket {
let mut cipher = cipher.to_be_bytes();
let mut encrypted_payload: Vec<u8> = vec![];
let mut payload: &[u8] = &self.payload;
loop {
let n = payload.len().min(Packet::CIPHER_SIZE as usize);
if n == 0 {
return EncryptedPacket { payload: encrypted_payload };
}
let (bytes, rest) = payload.split_at(n);
let ciphered: Vec<u8> = bytes.iter().
zip(cipher.iter()).
map(|(byte, cipher)| byte ^ cipher).
collect();
encrypted_payload.extend(&ciphered);
payload = rest;
for (i, &byte) in ciphered.iter().enumerate() {
cipher[i] = byte;
}
}
}
}
pub struct EncryptedPacket {
pub payload: Vec<u8>,
}
impl EncryptedPacket {
pub fn decrypt(&self, cipher: u32) -> Packet {
let mut cipher = cipher.to_be_bytes();
let mut payload: Vec<u8> = vec![];
let mut encrypted_payload: &[u8] = &self.payload;
loop {
let n = encrypted_payload.len().min(Packet::CIPHER_SIZE as usize);
if n == 0 {
return Packet { payload };
}
let (bytes, rest) = encrypted_payload.split_at(n);
let decrypted: Vec<u8> = bytes.iter().
zip(cipher.iter()).
map(|(byte, cipher)| byte ^ cipher).
collect();
payload.extend(&decrypted);
encrypted_payload = rest;
for (i, &byte) in bytes.iter().enumerate() {
cipher[i] = byte;
}
}
}
}
#[test]
fn basic_test() {
let packet = Packet::new(b"Secret message, please don't hack");
assert_eq!(packet.encrypt(0xDEADBEEF).decrypt(0xDEADBEEF).payload, packet.payload);
assert_eq!(packet.encrypt(0xDEAD).decrypt(0xDEAD).payload, packet.payload);
assert_eq!(packet.encrypt(1024).decrypt(1024).payload, packet.payload);
assert_ne!(packet.encrypt(1024).decrypt(1023).payload, packet.payload);
}
Compiling solution v0.1.0 (/tmp/d20191217-2173579-gzl0ac/solution)
    Finished dev [unoptimized + debuginfo] target(s) in 2.41s
     Running target/debug/deps/solution-28d77f5ef5bfec2e

running 1 test
test basic_test ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

     Running target/debug/deps/solution_test-b0ad3c2037f2314d

running 4 tests
test solution_test::test_exact_cyphers ... ok
test solution_test::test_full_roundtrip ... ok
test solution_test::test_roundtrip_with_specific_length ... ok
test solution_test::test_several_iterations ... ok

test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

   Doc-tests solution

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Любослав Карев
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Любослав Карев
pub struct Packet {
pub payload: Vec<u8>,
}
impl Packet {
pub fn new(source: &[u8]) -> Self {
Self { payload: source.to_vec() }
}
pub fn encrypt(&self, cypher: u32) -> EncryptedPacket {
let mut cypher_as_bytes: [u8; 4] = cypher.to_be_bytes();
let mut result: EncryptedPacket = EncryptedPacket { payload: vec![] };
for offset in 0..self.payload.len()/4{
for i in 0..4 {
let current_bytes_xor = self.payload[(offset*4) + i] ^ cypher_as_bytes[i];
result.payload.push(current_bytes_xor);
cypher_as_bytes[i] = current_bytes_xor;
}
}
for i in 0..self.payload.len() % 4 {
///Малко е нелогично, но така взимаме последните байтове
let offset = ((self.payload.len() / 4) * 4);
let current_bytes_xor = self.payload[offset + i] ^ cypher_as_bytes[i];
result.payload.push(current_bytes_xor);
cypher_as_bytes[i] = current_bytes_xor;
}
result
}
}
pub struct EncryptedPacket {
pub payload: Vec<u8>,
}
impl EncryptedPacket {
pub fn decrypt(&self, cypher: u32) -> Packet {
let mut cypher_as_bytes: [u8;4] = cypher.to_be_bytes();
let mut result: Packet = Packet{payload: vec![]};
for offset in 0..self.payload.len()/4{
for i in 0..4{
let current_bytes_xor = self.payload[(offset*4) + i] ^ cypher_as_bytes[i];
result.payload.push(current_bytes_xor);
cypher_as_bytes[i] = self.payload[(offset*4) + i];
}
}
for i in 0..self.payload.len() % 4 {
///Малко е нелогично, но така взимаме последните байтове
let offset = ((self.payload.len() / 4) * 4);
let current_bytes_xor = self.payload[offset + i] ^ cypher_as_bytes[i];
result.payload.push(current_bytes_xor);
cypher_as_bytes[i] = current_bytes_xor;
}
result
}
}
#[cfg(test)]
mod tests {
use crate::Packet;
#[test]
fn basic_test_1(){
let packet = Packet::new(b"a");
let encrypted_packet = packet.encrypt(10);
let decrypted_packet = encrypted_packet.decrypt(10);
assert_eq!(decrypted_packet.payload, packet.payload);
}
#[test]
fn basic_test_2(){
let packet = Packet::new(b"Secret message, plz don't hack");
assert_eq!(packet.encrypt(0xDEADBEEF).decrypt(0xDEADBEEF).payload, packet.payload);
}
#[test]
fn basic_test_3(){
let packet = Packet::new(b"abcde");
let encrypted_packet = packet.encrypt(10);
let decrypted_packet = encrypted_packet.decrypt(10);
assert_eq!(decrypted_packet.payload, packet.payload);
}
#[test]
fn basic_test_4(){
let packet = Packet::new(b"Hello, this is a non-hackable message");
let encrypted_packet = packet.encrypt('1' as u32);
let decrypted_packet = encrypted_packet.decrypt('2' as u32);
assert_ne!(decrypted_packet.payload, packet.payload);
}
}
Compiling solution v0.1.0 (/tmp/d20191217-2173579-hrhm42/solution)
warning: unused doc comment
  --> src/lib.rs:24:13
   |
24 |             ///Малко е нелогично, но така взимаме последните байтове
   |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
25 |             let offset = ((self.payload.len() / 4) * 4);
   |             -------------------------------------------- rustdoc does not generate documentation for statements
   |
   = note: `#[warn(unused_doc_comments)]` on by default

warning: unused doc comment
  --> src/lib.rs:50:13
   |
50 |             ///Малко е нелогично, но така взимаме последните байтове
   |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
51 |             let offset = ((self.payload.len() / 4) * 4);
   |             -------------------------------------------- rustdoc does not generate documentation for statements

warning: unnecessary parentheses around assigned value
  --> src/lib.rs:25:26
   |
25 |             let offset = ((self.payload.len() / 4) * 4);
   |                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: remove these parentheses
   |
   = note: `#[warn(unused_parens)]` on by default

warning: unnecessary parentheses around assigned value
  --> src/lib.rs:51:26
   |
51 |             let offset = ((self.payload.len() / 4) * 4);
   |                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: remove these parentheses

warning: unused doc comment
  --> src/lib.rs:24:13
   |
24 |             ///Малко е нелогично, но така взимаме последните байтове
   |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
25 |             let offset = ((self.payload.len() / 4) * 4);
   |             -------------------------------------------- rustdoc does not generate documentation for statements
   |
   = note: `#[warn(unused_doc_comments)]` on by default

warning: unused doc comment
  --> src/lib.rs:50:13
   |
50 |             ///Малко е нелогично, но така взимаме последните байтове
   |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
51 |             let offset = ((self.payload.len() / 4) * 4);
   |             -------------------------------------------- rustdoc does not generate documentation for statements

warning: unnecessary parentheses around assigned value
  --> src/lib.rs:25:26
   |
25 |             let offset = ((self.payload.len() / 4) * 4);
   |                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: remove these parentheses
   |
   = note: `#[warn(unused_parens)]` on by default

warning: unnecessary parentheses around assigned value
  --> src/lib.rs:51:26
   |
51 |             let offset = ((self.payload.len() / 4) * 4);
   |                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: remove these parentheses

    Finished dev [unoptimized + debuginfo] target(s) in 2.17s
     Running target/debug/deps/solution-28d77f5ef5bfec2e

running 4 tests
test tests::basic_test_1 ... ok
test tests::basic_test_2 ... ok
test tests::basic_test_3 ... ok
test tests::basic_test_4 ... ok

test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

     Running target/debug/deps/solution_test-b0ad3c2037f2314d

running 4 tests
test solution_test::test_exact_cyphers ... ok
test solution_test::test_full_roundtrip ... ok
test solution_test::test_roundtrip_with_specific_length ... ok
test solution_test::test_several_iterations ... ok

test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

   Doc-tests solution

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Николай Захаров
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Николай Захаров
pub struct Packet {
pub payload: Vec<u8>,
}
impl Packet {
pub fn new(source: &[u8]) -> Self {
Self {
payload: source.to_vec(),
}
}
pub fn encrypt(&self, cypher: u32) -> EncryptedPacket {
let cypher = cypher.to_be_bytes().to_vec();
let mut encrypted_message = Vec::<u8>::new();
Self::encrypt_recursive(&self.payload, cypher, &mut encrypted_message);
EncryptedPacket {
payload: encrypted_message,
}
}
fn encrypt_recursive(remaining_message: &[u8], cypher: Vec<u8>, encrypted: &mut Vec<u8>) {
if remaining_message.len() >= 4 {
let xored = xor_slices(&remaining_message[..4], &cypher);
encrypted.extend(&xored);
Self::encrypt_recursive(&remaining_message[4..], xored, encrypted);
} else {
let xored = xor_slices(&remaining_message, &cypher[..remaining_message.len()]);
encrypted.extend(&xored);
}
}
}
pub struct EncryptedPacket {
pub payload: Vec<u8>,
}
impl EncryptedPacket {
pub fn decrypt(&self, cypher: u32) -> Packet {
let payload_cpy = self.payload.clone();
let mut iterator_cpy = payload_cpy.chunks(4);
let first_element = match iterator_cpy.next() {
Some(x) => x,
None => return Packet::new(&[]), // just in case
};
let remaining_elements: Vec<u8> = self.payload
.chunks(4)
.zip(iterator_cpy)
.flat_map(|(a, b)| xor_slices(b, a))
.collect();
let result = vec![
xor_slices(first_element, &cypher.to_be_bytes()),
remaining_elements,
]
.concat();
Packet { payload: result }
}
}
fn xor_slices(slice1: &[u8], slice2: &[u8]) -> Vec<u8> {
slice1
.iter()
.zip(slice2.iter())
.map(|(a, b)| a ^ b)
.collect()
}
Compiling solution v0.1.0 (/tmp/d20191217-2173579-k2yzf7/solution)
    Finished dev [unoptimized + debuginfo] target(s) in 2.04s
     Running target/debug/deps/solution-28d77f5ef5bfec2e

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

     Running target/debug/deps/solution_test-b0ad3c2037f2314d

running 4 tests
test solution_test::test_exact_cyphers ... ok
test solution_test::test_full_roundtrip ... ok
test solution_test::test_roundtrip_with_specific_length ... ok
test solution_test::test_several_iterations ... ok

test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

   Doc-tests solution

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Антон Чернев
  • Некоректно
  • 3 успешни тест(а)
  • 1 неуспешни тест(а)
Антон Чернев
use std::convert::TryInto;
pub struct Packet {
pub payload: Vec<u8>,
}
impl Packet {
pub fn new(source: &[u8]) -> Self {
Self { payload: source.to_vec() }
}
pub fn encrypt(&self, mut cypher: u32) -> EncryptedPacket {
let mut ciphertext: Vec<u8> = Vec::new();
let mut plaintext = &self.payload[..];
let length = plaintext.len();
while plaintext.len() > 0 {
let mut bytes = [0u8; 4];
for i in 0..4 {
bytes[i] = match plaintext.split_first() {
Some((first, rest)) => {
plaintext = rest;
*first
},
None => 0
}
}
let encrypted = u32::from_be_bytes(bytes) ^ cypher;
ciphertext.extend_from_slice(
&(encrypted).to_be_bytes()
);
cypher = encrypted;
}
EncryptedPacket { payload: ciphertext, length }
}
}
pub struct EncryptedPacket {
pub payload: Vec<u8>,
length: usize
}
impl EncryptedPacket {
pub fn decrypt(&self, mut cypher: u32) -> Packet {
let mut ciphertext = &self.payload[..];
let mut plaintext = Vec::new();
while ciphertext.len() > 0 {
let (bytes, rest) = ciphertext.split_at(4);
ciphertext = rest;
let encrypted = u32::from_be_bytes(bytes.try_into().unwrap());
plaintext.extend_from_slice(
&(encrypted ^ cypher).to_be_bytes()
);
cypher = encrypted;
}
plaintext.truncate(self.length);
Packet { payload: plaintext }
}
}
Compiling solution v0.1.0 (/tmp/d20191217-2173579-1am3ifd/solution)
    Finished dev [unoptimized + debuginfo] target(s) in 1.76s
     Running target/debug/deps/solution-28d77f5ef5bfec2e

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

     Running target/debug/deps/solution_test-b0ad3c2037f2314d

running 4 tests
test solution_test::test_exact_cyphers ... ok
test solution_test::test_full_roundtrip ... ok
test solution_test::test_roundtrip_with_specific_length ... ok
test solution_test::test_several_iterations ... FAILED

failures:

---- solution_test::test_several_iterations stdout ----
thread 'main' panicked at 'assertion failed: `(left == right)`
  left: `[0, 0, 0, 0, 160, 15, 241, 85, 84, 15, 241, 85]`,
 right: `[0, 0, 0, 0, 160, 15, 241, 85, 84]`', tests/solution_test.rs:49:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace.


failures:
    solution_test::test_several_iterations

test result: FAILED. 3 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out

error: test failed, to rerun pass '--test solution_test'
Мирослав Лалев
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Мирослав Лалев
#[derive(Debug, PartialEq)]
pub struct Packet {
pub payload: Vec<u8>,
}
impl Packet {
pub fn new(source: &[u8]) -> Self {
Self {
payload: source.to_vec(),
}
}
pub fn encrypt(&self, cypher: u32) -> EncryptedPacket {
let be_bytes = cypher.to_be_bytes();
EncryptedPacket {
payload: self.encrypt_mask(be_bytes.as_ref()),
}
}
fn encrypt_mask(&self, mask: &[u8]) -> Vec<u8> {
let mut payload_it = self.payload.iter();
let mut mask = Vec::from(mask);
let mut result = Vec::new();
loop {
let bytes = payload_it
.by_ref()
.enumerate()
.take(mask.len())
.map(|(i, &val)| val ^ mask[i])
.collect::<Vec<_>>();
result.extend(&bytes);
if bytes.len() < mask.len() {
break;
}
mask = bytes;
}
result
}
}
#[derive(Debug, PartialEq)]
pub struct EncryptedPacket {
pub payload: Vec<u8>,
}
impl EncryptedPacket {
pub fn decrypt(&self, cypher: u32) -> Packet {
let be_bytes = cypher.to_be_bytes();
Packet {
payload: self.decrypt_mask(be_bytes.as_ref()),
}
}
fn decrypt_mask(&self, mask: &[u8]) -> Vec<u8> {
let mut payload_it = self.payload.iter();
let mut mask = Vec::from(mask);
let mut result = Vec::new();
loop {
let bytes = payload_it
.by_ref()
.take(mask.len())
.map(|&v| v)
.collect::<Vec<_>>();
result.extend((&bytes).iter().enumerate().map(|(i, &v)| v ^ mask[i]));
if bytes.len() < mask.len() {
break;
}
mask = bytes;
}
result
}
}
#[cfg(test)]
mod tests {
use super::*;
// [1, 1, 1, 1]
const TEST_CYPHER: u32 = (1 << 24) | (1 << 16) | (1 << 8) | (1 << 0);
#[test]
fn test_encrypt_decrypt() {
let v = (1..=10000)
.collect::<Vec<u32>>()
.iter()
.map(|&v| (v % 256) as u8)
.collect::<Vec<u8>>();
assert_eq!(
Packet::new(&v).encrypt(TEST_CYPHER).decrypt(TEST_CYPHER),
Packet { payload: v }
);
}
}
Compiling solution v0.1.0 (/tmp/d20191217-2173579-eug13b/solution)
    Finished dev [unoptimized + debuginfo] target(s) in 2.69s
     Running target/debug/deps/solution-28d77f5ef5bfec2e

running 1 test
test tests::test_encrypt_decrypt ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

     Running target/debug/deps/solution_test-b0ad3c2037f2314d

running 4 tests
test solution_test::test_exact_cyphers ... ok
test solution_test::test_full_roundtrip ... ok
test solution_test::test_roundtrip_with_specific_length ... ok
test solution_test::test_several_iterations ... ok

test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

   Doc-tests solution

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Иво Стефанов
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Иво Стефанов
pub struct Packet {
pub payload: Vec<u8>,
}
impl Packet {
pub fn new(source: &[u8]) -> Self {
Self { payload: source.to_vec() }
}
pub fn encrypt(&self, cypher: u32) -> EncryptedPacket {
let mut cypher_bytes = cypher.to_be_bytes();
let mut encrypted_vec = self.payload.to_vec();
let mut count = 0;
for i in 0..encrypted_vec.len(){
encrypted_vec[i] ^= cypher_bytes[count];
count+=1;
if count == 4 {
cypher_bytes[3] = encrypted_vec[i];
cypher_bytes[2] = encrypted_vec[i-1];
cypher_bytes[1] = encrypted_vec[i-2];
cypher_bytes[0] = encrypted_vec[i-3];
count = 0;
}
}
EncryptedPacket{payload: encrypted_vec}
}
}
pub struct EncryptedPacket {
pub payload: Vec<u8>,
}
impl EncryptedPacket {
pub fn decrypt(&self, cypher: u32) -> Packet {
let mut cypher_bytes = cypher.to_be_bytes();
let mut decrypted_vec = self.payload.to_vec();
let mut next_cypher_bytes: Vec<u8> = Vec::with_capacity(4);
let mut count = 0;
for i in 0..decrypted_vec.len(){
next_cypher_bytes.push(decrypted_vec[i]);
decrypted_vec[i] ^= cypher_bytes[count];
count+=1;
if count == 4 {
for k in 0..cypher_bytes.len(){
cypher_bytes[k] = next_cypher_bytes[k];
}
next_cypher_bytes = Vec::with_capacity(4);
count = 0;
}
}
Packet{payload: decrypted_vec}
}
}
Compiling solution v0.1.0 (/tmp/d20191217-2173579-10y1va0/solution)
    Finished dev [unoptimized + debuginfo] target(s) in 1.79s
     Running target/debug/deps/solution-28d77f5ef5bfec2e

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

     Running target/debug/deps/solution_test-b0ad3c2037f2314d

running 4 tests
test solution_test::test_exact_cyphers ... ok
test solution_test::test_full_roundtrip ... ok
test solution_test::test_roundtrip_with_specific_length ... ok
test solution_test::test_several_iterations ... ok

test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

   Doc-tests solution

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Ангел Беширов
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Ангел Беширов
pub struct Packet {
pub payload: Vec<u8>,
}
impl Packet {
pub fn new(source: &[u8]) -> Self {
Self { payload: source.to_vec() }
}
pub fn encrypt(&self, cypher: u32) -> EncryptedPacket {
let mut encrypted_result = Vec::new();
let mut payload_index: usize = 0;
let mut encryption_index: usize;
let mut cypher_bytes: [u8; 4] = cypher.to_be_bytes();
while payload_index < self.payload.len() {
encryption_index = payload_index % 4;
let encrypted_byte = cypher_bytes[encryption_index] ^ self.payload[payload_index];
cypher_bytes[encryption_index] = encrypted_byte;
encrypted_result.push(encrypted_byte);
payload_index = payload_index + 1;
}
EncryptedPacket::new(&encrypted_result)
}
}
pub struct EncryptedPacket {
pub payload: Vec<u8>,
}
impl EncryptedPacket {
pub fn new(source: &[u8]) -> Self {
Self { payload: source.to_vec() }
}
pub fn decrypt(&self, cypher: u32) -> Packet {
let mut decrypted_result = Vec::new();
let mut payload_index: usize = 0;
let mut decryption_index: usize;
let mut cypher_bytes: [u8; 4] = cypher.to_be_bytes();
while payload_index < self.payload.len() {
decryption_index = payload_index % 4;
let decrypted_byte = cypher_bytes[decryption_index] ^ self.payload[payload_index];
cypher_bytes[decryption_index] = self.payload[payload_index];
decrypted_result.push(decrypted_byte);
payload_index = payload_index + 1;
}
Packet::new(&decrypted_result)
}
}
Compiling solution v0.1.0 (/tmp/d20191217-2173579-120lf7g/solution)
    Finished dev [unoptimized + debuginfo] target(s) in 1.73s
     Running target/debug/deps/solution-28d77f5ef5bfec2e

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

     Running target/debug/deps/solution_test-b0ad3c2037f2314d

running 4 tests
test solution_test::test_exact_cyphers ... ok
test solution_test::test_full_roundtrip ... ok
test solution_test::test_roundtrip_with_specific_length ... ok
test solution_test::test_several_iterations ... ok

test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

   Doc-tests solution

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Парашкев Катерски
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Парашкев Катерски
pub struct Packet {
pub payload: Vec<u8>,
}
fn ivancho(payload: &Vec<u8>, cypher: u32, decrypt: bool) -> Vec<u8> {
let (acc, _) = payload.chunks(4).fold(
(Vec::<u8>::new(), cypher.to_be_bytes().to_vec()),
|(mut acc, cypher), x| {
let res = x
.iter()
.zip(cypher.iter())
.fold(Vec::<u8>::new(), |mut acc, (x, y)| {
acc.push(x ^ y);
acc
});
acc.extend(&res);
(acc, if decrypt { x.to_vec() } else { res })
},
);
acc
}
impl Packet {
pub fn new(source: &[u8]) -> Self {
Self { payload: source.to_vec(), }
}
pub fn encrypt(&self, cypher: u32) -> EncryptedPacket {
EncryptedPacket { payload: ivancho(&self.payload, cypher, false), }
}
}
pub struct EncryptedPacket {
pub payload: Vec<u8>,
}
impl EncryptedPacket {
pub fn decrypt(&self, cypher: u32) -> Packet {
Packet { payload: ivancho(&self.payload, cypher, true), }
}
}
Compiling solution v0.1.0 (/tmp/d20191217-2173579-4vx477/solution)
    Finished dev [unoptimized + debuginfo] target(s) in 1.74s
     Running target/debug/deps/solution-28d77f5ef5bfec2e

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

     Running target/debug/deps/solution_test-b0ad3c2037f2314d

running 4 tests
test solution_test::test_exact_cyphers ... ok
test solution_test::test_full_roundtrip ... ok
test solution_test::test_roundtrip_with_specific_length ... ok
test solution_test::test_several_iterations ... ok

test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

   Doc-tests solution

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Христина Христова
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Христина Христова
pub struct Packet
{
pub payload: Vec<u8>,
}
impl Packet
{
pub fn new(source: &[u8]) -> Self
{
Self { payload: source.to_vec() }
}
pub fn encrypt(&self, cypher: u32) -> EncryptedPacket
{
let mut c = cypher.to_be_bytes();
let mut b:u8;
let mut vec = Vec::new();
let mut i=0;
for item in self.payload.iter()
{
if i==4
{
i=0;
}
b=*item^c[i];
c[i]=b;
vec.push(b);
i+=1;
}
EncryptedPacket { payload: vec }
}
}
pub struct EncryptedPacket
{
pub payload: Vec<u8>,
}
impl EncryptedPacket
{
pub fn decrypt(&self, cypher: u32) -> Packet
{
let mut c = cypher.to_be_bytes();
let mut b:u8;
let mut vec = Vec::new();
let mut i=0;
for item in self.payload.iter()
{
if i==4
{
i=0;
}
b=*item^c[i];
c[i]=*item;
vec.push(b);
i+=1;
}
Packet { payload: vec }
}
}
Compiling solution v0.1.0 (/tmp/d20191217-2173579-1ndrl7w/solution)
    Finished dev [unoptimized + debuginfo] target(s) in 1.67s
     Running target/debug/deps/solution-28d77f5ef5bfec2e

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

     Running target/debug/deps/solution_test-b0ad3c2037f2314d

running 4 tests
test solution_test::test_exact_cyphers ... ok
test solution_test::test_full_roundtrip ... ok
test solution_test::test_roundtrip_with_specific_length ... ok
test solution_test::test_several_iterations ... ok

test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

   Doc-tests solution

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Станимира Влаева
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Станимира Влаева
pub struct Packet {
pub payload: Vec<u8>,
}
impl Packet {
pub fn new(source: &[u8]) -> Self {
Self { payload: source.to_vec() }
}
pub fn encrypt(&self, cypher: u32) -> EncryptedPacket {
let mut cypher_bytes = cypher.to_be_bytes();
let mut encrypted_payload: Vec<u8> = Vec::new();
for chunk in self.payload.chunks(4) {
for (i, byte) in chunk.iter().enumerate() {
let encrypted_byte = byte ^ cypher_bytes[i];
encrypted_payload.push(encrypted_byte);
cypher_bytes[i] = encrypted_byte;
}
}
return EncryptedPacket {
payload: encrypted_payload,
};
}
}
pub struct EncryptedPacket {
pub payload: Vec<u8>,
}
impl EncryptedPacket {
pub fn decrypt(&self, cypher: u32) -> Packet {
let mut cypher_bytes = cypher.to_be_bytes();
let mut decrypted_payload: Vec<u8> = Vec::new();
for chunk in self.payload.chunks(4) {
for (i, byte) in chunk.iter().enumerate() {
let decrypted_byte = byte ^ cypher_bytes[i];
decrypted_payload.push(decrypted_byte);
cypher_bytes[i] = *byte;
}
}
return Packet {
payload: decrypted_payload,
};
}
}
Compiling solution v0.1.0 (/tmp/d20191217-2173579-hqsdbu/solution)
    Finished dev [unoptimized + debuginfo] target(s) in 1.85s
     Running target/debug/deps/solution-28d77f5ef5bfec2e

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

     Running target/debug/deps/solution_test-b0ad3c2037f2314d

running 4 tests
test solution_test::test_exact_cyphers ... ok
test solution_test::test_full_roundtrip ... ok
test solution_test::test_roundtrip_with_specific_length ... ok
test solution_test::test_several_iterations ... ok

test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

   Doc-tests solution

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Иван Велков
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Иван Велков
pub struct Packet {
pub payload: Vec<u8>,
}
impl Packet {
pub fn new(source: &[u8]) -> Self {
Self { payload: source.to_vec() }
}
pub fn encrypt(&self, cypher: u32) -> EncryptedPacket {
let mut byte_cypher = cypher.to_be_bytes();
let chunked_payload = self.payload.chunks(4);
let mut result: Vec<u8> = Vec::new();
for chunk in chunked_payload {
for it in chunk.iter().zip(byte_cypher.iter_mut()) {
let (ai, bi) = it;
*bi = *ai ^ *bi;
result.push(*bi);
}
}
EncryptedPacket{payload: result}
}
}
pub struct EncryptedPacket {
pub payload: Vec<u8>,
}
// kogato nqmash vreme i copy/paste-vash kato retard....
impl EncryptedPacket {
pub fn decrypt(&self, cypher: u32) -> Packet {
let mut byte_cypher = cypher.to_be_bytes();
let chunked_payload = self.payload.chunks(4);
let mut result: Vec<u8> = Vec::new();
for chunk in chunked_payload {
for it in chunk.iter().zip(byte_cypher.iter_mut()) {
let (ai, bi) = it;
result.push(*ai ^ *bi);
*bi = *ai;
}
}
Packet{payload: result}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let packet = Packet::new(b"Secret message, plz don't hack");
assert_eq!(packet.encrypt(0xDEADBEEF).decrypt(0xDEADBEEF).payload, packet.payload);
}
}
Compiling solution v0.1.0 (/tmp/d20191217-2173579-1qzso9a/solution)
    Finished dev [unoptimized + debuginfo] target(s) in 2.01s
     Running target/debug/deps/solution-28d77f5ef5bfec2e

running 1 test
test tests::it_works ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

     Running target/debug/deps/solution_test-b0ad3c2037f2314d

running 4 tests
test solution_test::test_exact_cyphers ... ok
test solution_test::test_full_roundtrip ... ok
test solution_test::test_roundtrip_with_specific_length ... ok
test solution_test::test_several_iterations ... ok

test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

   Doc-tests solution

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Моника Киркова
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Моника Киркова
pub struct Packet {
pub payload: Vec<u8>,
}
impl Packet {
pub fn new(source: &[u8]) -> Self {
Self { payload: source.to_vec() }
}
pub fn encrypt(&self, cypher: u32) -> EncryptedPacket {
let mut encrypted = Vec::new();
let mut newCypher = cypher.to_be_bytes();
let mut first;
for i in (0..self.payload.len()).step_by(4){
if self.payload.len() < (i + 4){
first = self.payload.get(i..self.payload.len()).unwrap();
}else{
first = self.payload.get(i..i+4).unwrap();
}
newCypher.iter_mut()
.zip(first.iter())
.for_each(|(x1, x2)| *x1 ^= *x2);
for i in 0..first.len(){
encrypted.push(*newCypher.get(i).unwrap());
}
}
let encryptedPacket = EncryptedPacket {
payload: encrypted,
};
(encryptedPacket)
}
}
pub struct EncryptedPacket {
pub payload: Vec<u8>,
}
impl EncryptedPacket {
pub fn decrypt(&self, cypher: u32) -> Packet {
let mut decrypted = Vec::new();
let mut newCypher = cypher.to_be_bytes();
let mut first;
for i in (0..self.payload.len()).step_by(4){
if &self.payload.len() < &(i + 4){
first = self.payload.get(i..self.payload.len()).unwrap();
}else{
first = self.payload.get(i..i+4).unwrap();
}
newCypher.iter_mut()
.zip(first.iter())
.for_each(|(x1, x2)| *x1 ^= *x2);
for i in 0..first.len(){
decrypted.push(*newCypher.get(i).unwrap());
}
newCypher.iter_mut()
.zip(first.iter())
.for_each(|(x1, x2)| *x1 = *x2);
}
let packet = Packet {
payload: decrypted,
};
(packet)
}
}
Compiling solution v0.1.0 (/tmp/d20191217-2173579-12cmlq5/solution)
warning: variable `newCypher` should have a snake case name
  --> src/lib.rs:12:17
   |
12 |         let mut newCypher = cypher.to_be_bytes();
   |                 ^^^^^^^^^ help: convert the identifier to snake case: `new_cypher`
   |
   = note: `#[warn(non_snake_case)]` on by default

warning: variable `encryptedPacket` should have a snake case name
  --> src/lib.rs:28:13
   |
28 |         let encryptedPacket = EncryptedPacket {
   |             ^^^^^^^^^^^^^^^ help: convert the identifier to snake case: `encrypted_packet`

warning: variable `newCypher` should have a snake case name
  --> src/lib.rs:43:17
   |
43 |         let mut newCypher = cypher.to_be_bytes();
   |                 ^^^^^^^^^ help: convert the identifier to snake case: `new_cypher`

warning: variable `newCypher` should have a snake case name
  --> src/lib.rs:12:17
   |
12 |         let mut newCypher = cypher.to_be_bytes();
   |                 ^^^^^^^^^ help: convert the identifier to snake case: `new_cypher`
   |
   = note: `#[warn(non_snake_case)]` on by default

warning: variable `encryptedPacket` should have a snake case name
  --> src/lib.rs:28:13
   |
28 |         let encryptedPacket = EncryptedPacket {
   |             ^^^^^^^^^^^^^^^ help: convert the identifier to snake case: `encrypted_packet`

warning: variable `newCypher` should have a snake case name
  --> src/lib.rs:43:17
   |
43 |         let mut newCypher = cypher.to_be_bytes();
   |                 ^^^^^^^^^ help: convert the identifier to snake case: `new_cypher`

    Finished dev [unoptimized + debuginfo] target(s) in 2.21s
     Running target/debug/deps/solution-28d77f5ef5bfec2e

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

     Running target/debug/deps/solution_test-b0ad3c2037f2314d

running 4 tests
test solution_test::test_exact_cyphers ... ok
test solution_test::test_full_roundtrip ... ok
test solution_test::test_roundtrip_with_specific_length ... ok
test solution_test::test_several_iterations ... ok

test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

   Doc-tests solution

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Георги Петков
  • Коректно
  • 4 успешни тест(а)
  • 0 неуспешни тест(а)
Георги Петков
type FourBytes = [u8; 4];
pub struct Packet {
pub payload: Vec<u8>,
}
impl Packet {
pub fn new(source: &[u8]) -> Self {
Self { payload: source.to_vec() }
}
pub fn encrypt(&self, cypher: u32) -> EncryptedPacket {
let mut v: Vec<u8> = Vec::new();
let mut prev: FourBytes = cypher.to_be_bytes();
for (pos, e) in self.payload.iter().enumerate() {
let relative = pos%4;
let encrypted: u8 = prev[relative] ^ *e;
prev[relative] = encrypted;
v.push(encrypted);
}
EncryptedPacket{payload: v}
}
}
pub struct EncryptedPacket {
pub payload: Vec<u8>,
}
impl EncryptedPacket {
pub fn decrypt(&self, cypher: u32) -> Packet {
let mut v: Vec<u8> = Vec::new();
let mut prev: FourBytes = cypher.to_be_bytes();
for (pos, e) in self.payload.iter().enumerate() {
let relative = pos%4;
let decrypted: u8 = prev[relative] ^ *e;
prev[relative] = *e;
v.push(decrypted);
}
Packet{payload: v}
}
}
Compiling solution v0.1.0 (/tmp/d20191217-2173579-mhsno4/solution)
    Finished dev [unoptimized + debuginfo] target(s) in 1.77s
     Running target/debug/deps/solution-28d77f5ef5bfec2e

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

     Running target/debug/deps/solution_test-b0ad3c2037f2314d

running 4 tests
test solution_test::test_exact_cyphers ... ok
test solution_test::test_full_roundtrip ... ok
test solution_test::test_roundtrip_with_specific_length ... ok
test solution_test::test_several_iterations ... ok

test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

   Doc-tests solution

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out