com.github.bloodshura.x.cryptography.impl.twoway.ByteSwitch 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 javax.annotation.Nonnull;
public class ByteSwitch implements Twoway {
private int modifier;
public ByteSwitch() {
this(16);
}
public ByteSwitch(int modifier) {
this.modifier = modifier;
}
@Nonnull
@Override
public byte[] decrypt(@Nonnull byte[] data) {
byte[] result = new byte[data.length / 2];
for (int i = data.length - 1; i >= 0; i -= 2) {
int offset = i / 2;
short s = (short) ((data[i - 1] << 8) + data[i]);
byte bit;
if (i == data.length - 1) {
bit = (byte) (short) (s - getModifier());
}
else {
bit = (byte) (short) (s - result[offset + 1] + getModifier());
}
result[offset] = bit;
}
return result;
}
@Nonnull
@Override
public byte[] encrypt(@Nonnull byte[] data) {
byte[] result = new byte[data.length * 2];
for (int i = 0; i < data.length; i++) {
int offset = i * 2;
short bit;
if (i == data.length - 1) {
bit = (short) (data[i] + getModifier());
}
else {
bit = (short) (data[i] + data[i + 1] - getModifier());
}
result[offset] = (byte) ((bit >>> 8) & 0xFF);
result[offset + 1] = (byte) (bit & 0xFF);
}
return result;
}
public int getModifier() {
return modifier;
}
public boolean needsSalt() {
return false;
}
public void setModifier(int modifier) {
if ((Byte.MAX_VALUE * modifier) > Short.MAX_VALUE) {
throw new IllegalArgumentException("Modifier out of Short bounds.");
}
this.modifier = modifier;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy