package org.bouncycastle.pqc.crypto.ntru;
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.AsymmetricCipherKeyPairGenerator;
import org.bouncycastle.crypto.KeyGenerationParameters;
import org.bouncycastle.pqc.math.ntru.polynomial.DenseTernaryPolynomial;
import org.bouncycastle.pqc.math.ntru.polynomial.IntegerPolynomial;
import org.bouncycastle.pqc.math.ntru.polynomial.Polynomial;
import org.bouncycastle.pqc.math.ntru.polynomial.ProductFormPolynomial;
import org.bouncycastle.pqc.math.ntru.util.Util;
public class NTRUEncryptionKeyPairGenerator
implements AsymmetricCipherKeyPairGenerator
{
private NTRUEncryptionKeyGenerationParameters params;
public void init(KeyGenerationParameters param)
{
this.params = (NTRUEncryptionKeyGenerationParameters)param;
}
public AsymmetricCipherKeyPair generateKeyPair()
{
int N = params.N;
int q = params.q;
int df = params.df;
int df1 = params.df1;
int df2 = params.df2;
int df3 = params.df3;
int dg = params.dg;
boolean fastFp = params.fastFp;
boolean sparse = params.sparse;
Polynomial t;
IntegerPolynomial fq;
IntegerPolynomial fp = null;
while (true)
{
IntegerPolynomial f;
if (fastFp)
{
t = params.polyType == NTRUParameters.TERNARY_POLYNOMIAL_TYPE_SIMPLE ? Util.generateRandomTernary(N, df, df, sparse, params.getRandom()) : ProductFormPolynomial.generateRandom(N, df1, df2, df3, df3, params.getRandom());
f = t.toIntegerPolynomial();
f.mult(3);
f.coeffs[0] += 1;
}
else
{
t = params.polyType == NTRUParameters.TERNARY_POLYNOMIAL_TYPE_SIMPLE ? Util.generateRandomTernary(N, df, df - 1, sparse, params.getRandom()) : ProductFormPolynomial.generateRandom(N, df1, df2, df3, df3 - 1, params.getRandom());
f = t.toIntegerPolynomial();
fp = f.invertF3();
if (fp == null)
{
continue;
}
}
fq = f.invertFq(q);
if (fq == null)
{
continue;
}
break;
}
if (fastFp)
{
fp = new IntegerPolynomial(N);
fp.coeffs[0] = 1;
}
DenseTernaryPolynomial g;
while (true)
{
g = DenseTernaryPolynomial.generateRandom(N, dg, dg - 1, params.getRandom());
if (g.invertFq(q) != null)
{
break;
}
}
IntegerPolynomial h = g.mult(fq, q);
h.mult3(q);
h.ensurePositive(q);
g.clear();
fq.clear();
NTRUEncryptionPrivateKeyParameters priv = new NTRUEncryptionPrivateKeyParameters(h, t, fp, params.getEncryptionParameters());
NTRUEncryptionPublicKeyParameters pub = new NTRUEncryptionPublicKeyParameters(h, params.getEncryptionParameters());
return new AsymmetricCipherKeyPair(pub, priv);
}
}