Skip to content

Commit 9855fd9

Browse files
committed
#BAEL-6958: add KemUtils main source
1 parent cdcc7a2 commit 9855fd9

File tree

1 file changed

+27
-0
lines changed
  • core-java-modules/core-java-security-5/src/main/java/com/baeldung/kem

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package com.baeldung.kem;
2+
3+
import java.security.PrivateKey;
4+
import java.security.PublicKey;
5+
6+
import javax.crypto.KEM;
7+
import javax.crypto.SecretKey;
8+
9+
public class KemUtils {
10+
11+
public record KemResult(SecretKey sharedSecret, byte[] encapsulation) {}
12+
13+
public static KemResult encapsulate(String algorithm, PublicKey publicKey) throws Exception {
14+
KEM kem = KEM.getInstance(algorithm);
15+
KEM.Encapsulator encapsulator = kem.newEncapsulator(publicKey);
16+
KEM.Encapsulated result = encapsulator.encapsulate();
17+
return new KemResult(result.key(), result.encapsulation());
18+
}
19+
20+
public static KemResult decapsulate(String algorithm, PrivateKey privateKey, byte[] encapsulation) throws Exception {
21+
KEM kem = KEM.getInstance(algorithm);
22+
KEM.Decapsulator decapsulator = kem.newDecapsulator(privateKey);
23+
SecretKey recoveredSecret = decapsulator.decapsulate(encapsulation);
24+
return new KemResult(recoveredSecret, encapsulation);
25+
}
26+
27+
}

0 commit comments

Comments
 (0)