I want to encrypt a secret key using another key pair and decrypt it back to the DCRTPoly. I tried using the decryption function’s code without the CRTInterpolation step. But it results in a different output.
Also, the Elements in the key are not in the same plaintext modulus as the one we pass in parameters. It is larger. Could this difference come from it?
From my understanding, when you generate a secret key with the KeyGen method it will be a DCRTPoly mod q (where q is the modulus of the ciphertext space). So, assuming ternary distribution, the secret key will have values in {0, 1, q-1} (after being interpolated). So, I guess you could encrypt it by interpolating it and turning it into a std::vector like this:
KeyPair<DCRTPoly> kp = cc->KeyGen();
DCRTPoly s = kp.secretKey->GetPrivateElement();
s.SetFormat(Format::COEFFICIENT);
DCRTPoly::PolyLargeType sInt = s.CRTInterpolate();
const size_t n = sInt.GetLength();
std::vector<int64_t> keyVector(n);
for (size_t i = 0; i < n; i++) {
if (sInt.GetValues()[i] == 1)
keyVector[i] = 1;
else if (sInt.GetValues()[i] == 0)
keyVector[i] = 0;
else
keyVector[i] = -1;
}
Plaintext ptxt = cc->MakePackedPlaintext(keyVector);
KeyPair<DCRTPoly> kp2 = cc->KeyGen();
Ciphertext<DCRTPoly> encryptedKey = cc->Encrypt(kp2.publicKey, ptxt);
Then, you can just invoke the standard Decrypt method and get the original private key as std::vector with GetPackedValue (for BFV at least). Then, if you want a DCRTPoly from that, I guess you could do something like this:
Poly decryptedKeyPoly(cc->GetElementParams(), Format::COEFFICIENT);
decryptedKeyPoly.SetValuesToZero();
for (size_t i = 0; i < decryptedKeyVector.size() && i < decryptedKeyPoly.GetLength(); i++) {
if (decryptedKeyVector[i] == 1)
decryptedKeyPoly[i] = 1;
else if (decryptedKeyVector[i] == 0)
decryptedKeyPoly[i] = 0;
else
decryptedKeyPoly[i] = decryptedKeyPoly.GetModulus() - 1;
}
DCRTPoly decryptedKeyDCRTPoly(cc->GetElementParams(), Format::COEFFICIENT);
decryptedKeyDCRTPoly = decryptedKeyPoly;
Not sure if this answers your question. Maybe it could be useful if you state what do you need the output DCRTPoly for.