|
| 1 | +package io.opentdf.platform.sdk; |
| 2 | + |
| 3 | +import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; |
| 4 | +import org.bouncycastle.crypto.SecretWithEncapsulation; |
| 5 | +import org.bouncycastle.crypto.util.PublicKeyFactory; |
| 6 | +import org.bouncycastle.openssl.PEMParser; |
| 7 | +import org.bouncycastle.pqc.crypto.mlkem.MLKEMGenerator; |
| 8 | +import org.bouncycastle.pqc.crypto.mlkem.MLKEMPublicKeyParameters; |
| 9 | + |
| 10 | +import java.io.IOException; |
| 11 | +import java.io.StringReader; |
| 12 | +import java.security.SecureRandom; |
| 13 | + |
| 14 | +/** |
| 15 | + * Handles ML-KEM-768 key encapsulation for wrapping a symmetric DEK. |
| 16 | + * |
| 17 | + * Wire format: base64(ml_kem_ciphertext [1088 bytes] || aes_gcm_wrapped_dek) |
| 18 | + * No ephemeralPublicKey field; KeyAccess type is "wrapped". |
| 19 | + */ |
| 20 | +class MLKEMEncryption { |
| 21 | + |
| 22 | + /** ML-KEM-768 ciphertext is always 1088 bytes. */ |
| 23 | + static final int CIPHERTEXT_SIZE = 1088; |
| 24 | + |
| 25 | + private final MLKEMPublicKeyParameters publicKeyParams; |
| 26 | + |
| 27 | + MLKEMEncryption(String pemPublicKey) { |
| 28 | + try { |
| 29 | + PEMParser parser = new PEMParser(new StringReader(pemPublicKey)); |
| 30 | + SubjectPublicKeyInfo spki = (SubjectPublicKeyInfo) parser.readObject(); |
| 31 | + parser.close(); |
| 32 | + publicKeyParams = (MLKEMPublicKeyParameters) PublicKeyFactory.createKey(spki); |
| 33 | + } catch (IOException e) { |
| 34 | + throw new SDKException("error parsing ML-KEM-768 public key", e); |
| 35 | + } catch (ClassCastException e) { |
| 36 | + throw new SDKException("public key is not an ML-KEM key", e); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + /** |
| 41 | + * Encapsulates against the KAS ML-KEM-768 public key and AES-GCM wraps the DEK. |
| 42 | + * |
| 43 | + * @return ciphertext (1088 bytes) concatenated with the AES-GCM wrapped DEK |
| 44 | + */ |
| 45 | + byte[] encapsulateAndWrap(byte[] dek) { |
| 46 | + MLKEMGenerator kemGen = new MLKEMGenerator(new SecureRandom()); |
| 47 | + SecretWithEncapsulation swe = kemGen.generateEncapsulated(publicKeyParams); |
| 48 | + |
| 49 | + byte[] ciphertext = swe.getEncapsulation(); |
| 50 | + byte[] sharedSecret = swe.getSecret(); |
| 51 | + |
| 52 | + byte[] sessionKey = ECKeyPair.calculateHKDF(TDF.GLOBAL_KEY_SALT, sharedSecret); |
| 53 | + byte[] aesWrappedDek = new AesGcm(sessionKey).encrypt(dek).asBytes(); |
| 54 | + |
| 55 | + byte[] combined = new byte[ciphertext.length + aesWrappedDek.length]; |
| 56 | + System.arraycopy(ciphertext, 0, combined, 0, ciphertext.length); |
| 57 | + System.arraycopy(aesWrappedDek, 0, combined, ciphertext.length, aesWrappedDek.length); |
| 58 | + return combined; |
| 59 | + } |
| 60 | +} |
0 commit comments