| 7 | import org.jetbrains.annotations.NotNull; |
| 8 | |
| 9 | public class Encrypt implements Codec { |
| 10 | private final @NotNull Codec sink; |
| 11 | private final @NotNull Cipher cipher; |
| 12 | private final @NotNull ByteBuffer ivr; |
| 13 | private final @NotNull ByteBuffer ivw; |
| 14 | private final byte @NotNull [] iv; |
| 15 | private final byte @NotNull [] in; |
| 16 | private int count = 0; |
| 17 | |
| 18 | public Encrypt(@NotNull Codec sink, byte @NotNull [] key) throws CodecException { |
| 19 | this.sink = sink; |
| 20 | iv = new byte[16]; |
| 21 | in = new byte[16]; |
| 22 | System.arraycopy(Digest.md5(key), 0, iv, 0, 16); |
| 23 | ivr = ByteBuffer.wrap(iv); |
| 24 | ivw = ByteBuffer.wrap(iv); |
| 25 | try { |
| 26 | cipher = Cipher.getInstance("AES/ECB/NoPadding"); |
| 27 | cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(iv, "AES")); |
| 28 | } catch (Exception e) { |
| 29 | throw new CodecException(e); |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | private void succeed() { |
| 34 | try { |
| 35 | cipher.update(ivr, ivw); |
| 36 | ivr.clear(); |
| 37 | ivw.clear(); |
| 38 | } catch (ShortBufferException e) { |
| 39 | // skip |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | @Override |
| 44 | public void update(byte c) throws CodecException { |
| 45 | if (count < 0) { |
| 46 | sink.update(iv[count++ + 16] ^= c); |
| 47 | return; |
| 48 | } |
| 49 | in[count++] = c; |
| 50 | if (count < 16) |
| 51 | return; |
| 52 | succeed(); |
| 53 | for (int i = 0; i < 16; i++) |
| 54 | iv[i] ^= in[i]; |
| 55 | sink.update(iv, 0, 16); |
| 56 | count = 0; |
| 57 | } |
| 58 | |
| 59 | @Override |
| 60 | public void update(byte @NotNull [] data, int off, int len) throws CodecException { |
| 61 | int i = off; |
| 62 | len += off; |
| 63 | if (count < 0) { |
| 64 | for (; i < len && count < 0; i++, count++) |
| 65 | sink.update(iv[count + 16] ^= data[i]); |
| 66 | } else if (count > 0) { |
nothing calls this directly
no outgoing calls
no test coverage detected