
com.github.bloodshura.x.cryptography.impl.twoway.Bytaway Maven / Gradle / Ivy
/*
* Copyright (c) 2013-2018, João Vitor Verona Biazibetti - All Rights Reserved
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see .
*
* https://www.github.com/BloodShura
*/
package com.github.bloodshura.x.cryptography.impl.twoway;
import com.github.bloodshura.x.cryptography.Twoway;
import com.github.bloodshura.x.cryptography.exception.CryptoException;
import javax.annotation.Nonnull;
public class Bytaway implements Twoway {
private int level;
private int modifier;
public Bytaway() {
this(15, 12);
}
public Bytaway(int level, int modifier) {
this.level = level;
this.modifier = modifier;
}
@Nonnull
@Override
public byte[] decrypt(@Nonnull byte[] data) {
int level = getLevel() + 1;
byte[] result = new byte[data.length / level];
for (int i = 0; i < result.length; i++) {
int offset = i * level;
byte bit = data[offset];
short s = bit;
if ((offset + 1) < data.length) {
byte bit2 = data[offset + 1];
s = (short) ((bit) + (bit2 << 8));
}
result[i] = (byte) (s + getModifier());
}
return result;
}
@Nonnull
@Override
public byte[] encrypt(@Nonnull byte[] data) {
int level = getLevel() + 1;
byte[] result = new byte[(data.length * level) + 1];
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < level; j++) {
int offset = (i * level) + j;
short bit = (short) (data[i] - getModifier() * (j + 1));
result[offset] = (byte) (bit & 0xFF);
result[offset + 1] = (byte) ((bit >>> 8) & 0xFF);
}
}
return result;
}
public int getLevel() {
return level;
}
public int getModifier() {
return modifier;
}
public boolean needsSalt() {
return false;
}
public void setLevel(int level) throws CryptoException {
if (level <= 0) {
throw new CryptoException("Level must be higher than zero");
}
this.level = level;
}
public void setModifier(int modifier) throws CryptoException {
if (modifier > Short.MAX_VALUE - Byte.MAX_VALUE || modifier < Short.MIN_VALUE + Byte.MIN_VALUE) {
throw new CryptoException("Modifier out of Short bounds.");
}
this.modifier = modifier;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy