Skip to content

Instantly share code, notes, and snippets.

@marcaddeo
Created January 23, 2012 23:11
Show Gist options
  • Save marcaddeo/1666229 to your computer and use it in GitHub Desktop.
Save marcaddeo/1666229 to your computer and use it in GitHub Desktop.
Encryption methods
package crypto;
public class Crypto {
private char[] Key1 = {
// Omitted
};
private char[] Key2 = {
// Omitted
};
private char[] Key3;
private char[] Key4;
private boolean useNewKeys;
private Counter localCounter;
private Counter remoteCounter;
public Crypto() {
this.useNewKeys = false;
this.localCounter = new Counter();
this.remoteCounter = new Counter();
this.Key3 = new char[256];
this.Key4 = new char[256];
}
public void resetCounters() {
this.localCounter.reset();
this.remoteCounter.reset();
}
public void useNewKeys() {
this.useNewKeys = true;
}
public char[] incoming(char[] packet) {
for (int i = 0; i < packet.length; i++) {
int num = this.remoteCounter.first;
packet[i] = (char) ( ( packet[i] ^ this.Key1[num] ) ^ this.Key2[this.remoteCounter.second] );
this.remoteCounter.increment();
}
return packet;
}
public byte[] incoming(byte[] packet) {
for (int i = 0; i < packet.length; i++) {
int num = this.remoteCounter.first;
packet[i] = (byte) ( ( packet[i] ^ this.Key1[num] ) ^ this.Key2[this.remoteCounter.second] );
this.remoteCounter.increment();
}
return packet;
}
public char[] outgoing(char[] packet) {
for (int i = 0; i < packet.length; i++) {
int num = this.localCounter.first;
if (this.useNewKeys) {
packet[i] = (char) ( ( packet[i] ^ this.Key3[num] ) ^ this.Key4[this.localCounter.second]);
} else {
packet[i] = (char) ( ( packet[i] ^ this.Key1[num] ) ^ this.Key2[this.localCounter.second]);
}
this.localCounter.increment();
}
return packet;
}
public byte[] outgoing(byte[] packet) {
for (int i = 0; i < packet.length; i++) {
int num = this.localCounter.first;
if (this.useNewKeys) {
packet[i] = (byte) ( ( packet[i] ^ this.Key3[num] ) ^ this.Key4[this.localCounter.second]);
} else {
packet[i] = (byte) ( ( packet[i] ^ this.Key1[num] ) ^ this.Key2[this.localCounter.second]);
}
this.localCounter.increment();
}
return packet;
}
private static final byte[] intToByteArray(int value) {
return new byte[] {
(byte)(value >>> 24),
(byte)(value >>> 16),
(byte)(value >>> 8),
(byte)value};
}
public void generateKeys(int seed) {
int seed2 = seed * seed;
byte[] seedArr = Crypto.intToByteArray(seed);
byte[] seed2Arr = Crypto.intToByteArray(seed2);
for (int i = 0, n = 3; i < 256; i++, n = (n == 0) ? 3 : --n) {
this.Key3[i] = (char) (this.Key1[i] ^ seedArr[n]);
this.Key4[i] = (char) (this.Key2[i] ^ seed2Arr[n]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment