|
| 1 | +package org.jruby.ext.openssl; |
| 2 | + |
| 3 | +import java.security.Security; |
| 4 | +import java.util.Arrays; |
| 5 | + |
| 6 | +import javax.crypto.Cipher; |
| 7 | +import javax.crypto.Mac; |
| 8 | + |
| 9 | +import org.junit.jupiter.api.Test; |
| 10 | + |
| 11 | +import static org.junit.jupiter.api.Assertions.*; |
| 12 | +import static org.junit.jupiter.api.Assumptions.assumeTrue; |
| 13 | + |
| 14 | +public class SimpleSecretKeyTest { |
| 15 | + |
| 16 | + @Test |
| 17 | + public void getEncodedReturnsCopy() { |
| 18 | + final byte[] value = { 1, 2, 3, 4 }; |
| 19 | + final SimpleSecretKey key = new SimpleSecretKey("AES", value); |
| 20 | + key.getEncoded()[0] = 0; |
| 21 | + assertArrayEquals(new byte[] { 1, 2, 3, 4 }, key.getEncoded()); |
| 22 | + assertArrayEquals(new byte[] { 1, 2, 3, 4 }, value); |
| 23 | + } |
| 24 | + |
| 25 | + // SunJCE wipes the encoded key bytes after init |
| 26 | + @Test |
| 27 | + public void keyBytesSurviveSunJCEInit() throws Exception { |
| 28 | + assumeTrue(Security.getProvider("SunJCE") != null); |
| 29 | + |
| 30 | + final byte[] value = new byte[16]; Arrays.fill(value, (byte) 'k'); |
| 31 | + |
| 32 | + Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding", "SunJCE"); |
| 33 | + cipher.init(Cipher.ENCRYPT_MODE, new SimpleSecretKey("AES", value)); |
| 34 | + final byte[] out1 = cipher.doFinal(new byte[16]); |
| 35 | + cipher.init(Cipher.ENCRYPT_MODE, new SimpleSecretKey("AES", value)); |
| 36 | + assertArrayEquals(out1, cipher.doFinal(new byte[16])); |
| 37 | + |
| 38 | + Mac mac = Mac.getInstance("HmacSHA256", "SunJCE"); |
| 39 | + mac.init(new SimpleSecretKey("HmacSHA256", value)); |
| 40 | + |
| 41 | + final byte[] expected = new byte[16]; Arrays.fill(expected, (byte) 'k'); |
| 42 | + assertArrayEquals(expected, value); |
| 43 | + } |
| 44 | + |
| 45 | +} |
0 commit comments