| 1 |
/* |
| 2 |
* Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0, |
| 3 |
* and the EPL 1.0 (https://h2database.com/html/license.html). |
| 4 |
* Initial Developer: H2 Group |
| 5 |
*/ |
| 6 |
package org.h2.security; |
| 7 |
|
| 8 |
import org.h2.util.Bits; |
| 9 |
|
| 10 |
/** |
| 11 |
* A pseudo-encryption algorithm that makes the data appear to be |
| 12 |
* encrypted. This algorithm is cryptographically extremely weak, and should |
| 13 |
* only be used to hide data from reading the plain text using a text editor. |
| 14 |
*/ |
| 15 |
public class Fog implements BlockCipher { |
| 16 |
|
| 17 |
private int key; |
| 18 |
|
| 19 |
@Override |
| 20 |
public void encrypt(byte[] bytes, int off, int len) { |
| 21 |
for (int i = off; i < off + len; i += 16) { |
| 22 |
encryptBlock(bytes, bytes, i); |
| 23 |
} |
| 24 |
} |
| 25 |
|
| 26 |
@Override |
| 27 |
public void decrypt(byte[] bytes, int off, int len) { |
| 28 |
for (int i = off; i < off + len; i += 16) { |
| 29 |
decryptBlock(bytes, bytes, i); |
| 30 |
} |
| 31 |
} |
| 32 |
|
| 33 |
private void encryptBlock(byte[] in, byte[] out, int off) { |
| 34 |
int x0 = Bits.readInt(in, off); |
| 35 |
int x1 = Bits.readInt(in, off + 4); |
| 36 |
int x2 = Bits.readInt(in, off + 8); |
| 37 |
int x3 = Bits.readInt(in, off + 12); |
| 38 |
int k = key; |
| 39 |
x0 = Integer.rotateLeft(x0 ^ k, x1); |
| 40 |
x2 = Integer.rotateLeft(x2 ^ k, x1); |
| 41 |
x1 = Integer.rotateLeft(x1 ^ k, x0); |
| 42 |
x3 = Integer.rotateLeft(x3 ^ k, x0); |
| 43 |
Bits.writeInt(out, off, x0); |
| 44 |
Bits.writeInt(out, off + 4, x1); |
| 45 |
Bits.writeInt(out, off + 8, x2); |
| 46 |
Bits.writeInt(out, off + 12, x3); |
| 47 |
} |
| 48 |
|
| 49 |
private void decryptBlock(byte[] in, byte[] out, int off) { |
| 50 |
int x0 = Bits.readInt(in, off); |
| 51 |
int x1 = Bits.readInt(in, off + 4); |
| 52 |
int x2 = Bits.readInt(in, off + 8); |
| 53 |
int x3 = Bits.readInt(in, off + 12); |
| 54 |
int k = key; |
| 55 |
x1 = Integer.rotateRight(x1, x0) ^ k; |
| 56 |
x3 = Integer.rotateRight(x3, x0) ^ k; |
| 57 |
x0 = Integer.rotateRight(x0, x1) ^ k; |
| 58 |
x2 = Integer.rotateRight(x2, x1) ^ k; |
| 59 |
Bits.writeInt(out, off, x0); |
| 60 |
Bits.writeInt(out, off + 4, x1); |
| 61 |
Bits.writeInt(out, off + 8, x2); |
| 62 |
Bits.writeInt(out, off + 12, x3); |
| 63 |
} |
| 64 |
|
| 65 |
@Override |
| 66 |
public int getKeyLength() { |
| 67 |
return 16; |
| 68 |
} |
| 69 |
|
| 70 |
@Override |
| 71 |
public void setKey(byte[] key) { |
| 72 |
this.key = (int) Bits.readLong(key, 0); |
| 73 |
} |
| 74 |
|
| 75 |
} |