1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.shiro.crypto;
20
21 import org.apache.shiro.codec.CodecSupport;
22 import org.apache.shiro.util.ByteSource;
23 import org.junit.Test;
24
25 import java.io.ByteArrayInputStream;
26 import java.io.ByteArrayOutputStream;
27 import java.io.InputStream;
28 import java.util.Arrays;
29
30 import static junit.framework.Assert.assertTrue;
31
32
33
34
35
36
37 public class BlowfishCipherServiceTest {
38
39 private static final String[] PLAINTEXTS = new String[]{
40 "Hello, this is a test.",
41 "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
42 };
43
44 @Test
45 public void testBlockOperations() {
46 BlowfishCipherService blowfish = new BlowfishCipherService();
47
48 byte[] key = blowfish.generateNewKey().getEncoded();
49
50 for (String plain : PLAINTEXTS) {
51 byte[] plaintext = CodecSupport.toBytes(plain);
52 ByteSource ciphertext = blowfish.encrypt(plaintext, key);
53 ByteSource decrypted = blowfish.decrypt(ciphertext.getBytes(), key);
54 assertTrue(Arrays.equals(plaintext, decrypted.getBytes()));
55 }
56 }
57
58 @Test
59 public void testStreamingOperations() {
60
61 BlowfishCipherService cipher = new BlowfishCipherService();
62 byte[] key = cipher.generateNewKey().getEncoded();
63
64 for (String plain : PLAINTEXTS) {
65 byte[] plaintext = CodecSupport.toBytes(plain);
66 InputStream plainIn = new ByteArrayInputStream(plaintext);
67 ByteArrayOutputStream cipherOut = new ByteArrayOutputStream();
68 cipher.encrypt(plainIn, cipherOut, key);
69
70 byte[] ciphertext = cipherOut.toByteArray();
71 InputStream cipherIn = new ByteArrayInputStream(ciphertext);
72 ByteArrayOutputStream plainOut = new ByteArrayOutputStream();
73 cipher.decrypt(cipherIn, plainOut, key);
74
75 byte[] decrypted = plainOut.toByteArray();
76 assertTrue(Arrays.equals(plaintext, decrypted));
77 }
78
79 }
80 }