Skip to content

Commit 69bd973

Browse files
committed
[fix] copy key bytes in SimpleSecretKey#getEncoded
SunJCE wipes the bytes returned from getEncoded() after init
1 parent 179b40b commit 69bd973

2 files changed

Lines changed: 46 additions & 1 deletion

File tree

‎src/main/java/org/jruby/ext/openssl/SimpleSecretKey.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ public String getAlgorithm() {
6060
}
6161

6262
public byte[] getEncoded() {
63-
return value;
63+
return value.clone(); // NOTE: providers (SunJCE) wipe the returned bytes after init
6464
}
6565

6666
public String getFormat() {
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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

Comments
 (0)