1 package civitas.crypto.msg;
2
3 import org.springframework.beans.factory.annotation.Autowired;
4 import org.springframework.stereotype.Controller;
5
6 import civitas.crypto.CryptoException;
7 import civitas.crypto.ciphertext.ElGamalCiphertextish;
8 import civitas.crypto.parameters.ElGamalParameters;
9 import civitas.crypto.privatekey.ElGamalPrivateKey;
10 import civitas.crypto.signature.VerifyElGamalSignature;
11 import civitas.crypto.signedciphertext.ElGamalSignedCiphertext;
12 import civitas.util.CivitasBigInteger;
13
14 @Controller
15 public class DecryptElGamalMessage {
16
17 @Autowired
18 VerifyElGamalSignature verifyElGamalSignature;
19
20 public ElGamalMsg apply(
21 final ElGamalPrivateKey key, final ElGamalCiphertextish ciphertext, final byte[] additionalEnv)
22 throws CryptoException {
23 ElGamalPrivateKey k = key;
24 ElGamalParameters ps = key.params();
25
26 if (ciphertext instanceof ElGamalSignedCiphertext elGamalSignedCiphertext
27 && !verifyElGamalSignature.apply(ps, elGamalSignedCiphertext, additionalEnv)) {
28 throw new CryptoException("Ciphertext failed verification");
29 }
30
31 ElGamalCiphertextish c = ciphertext;
32 CivitasBigInteger a = c.getA();
33 CivitasBigInteger b = c.getB();
34 CivitasBigInteger m = b.modDivide(a.modPow(k.x(), ps.p), ps.p);
35 return new ElGamalMsg(m);
36 }
37
38 public ElGamalMsg apply(final ElGamalPrivateKey key, final ElGamalCiphertextish ciphertext) throws CryptoException {
39 return apply(key, ciphertext, null);
40 }
41 }