package org.bouncycastle.pqc.legacy.crypto.test;

import java.security.SecureRandom;
import java.util.Random;

import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.crypto.params.ParametersWithRandom;
import org.bouncycastle.pqc.crypto.util.PrivateKeyFactory;
import org.bouncycastle.pqc.legacy.crypto.mceliece.McElieceCipher;
import org.bouncycastle.pqc.legacy.crypto.mceliece.McElieceKeyGenerationParameters;
import org.bouncycastle.pqc.legacy.crypto.mceliece.McElieceKeyPairGenerator;
import org.bouncycastle.pqc.legacy.crypto.mceliece.McElieceKobaraImaiCipher;
import org.bouncycastle.pqc.legacy.crypto.mceliece.McElieceParameters;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.encoders.Base64;
import org.bouncycastle.util.test.SimpleTest;

public class McElieceCipherTest
    extends SimpleTest
{

    SecureRandom keyRandom = new SecureRandom();

    public String getName()
    {
        return "McEliecePKCS";
    }

    public void performTest()
        throws Exception
    {
        leadingZeroTest();

        int numPassesKPG = 1;
        int numPassesEncDec = 10;
        Random rand = new Random();
        byte[] mBytes;
        for (int j = 0; j < numPassesKPG; j++)
        {

            McElieceParameters params = new McElieceParameters();
            McElieceKeyPairGenerator mcElieceKeyGen = new McElieceKeyPairGenerator();
            McElieceKeyGenerationParameters genParam = new McElieceKeyGenerationParameters(keyRandom, params);

            mcElieceKeyGen.init(genParam);
            AsymmetricCipherKeyPair pair = mcElieceKeyGen.generateKeyPair();

            ParametersWithRandom param = new ParametersWithRandom(pair.getPublic(), keyRandom);
            Digest msgDigest = new SHA256Digest();
            McElieceCipher mcEliecePKCSDigestCipher = new McElieceCipher();


            for (int k = 1; k <= numPassesEncDec; k++)
            {
                // System.out.println("############### test: " + k);
                // initialize for encryption
                mcEliecePKCSDigestCipher.init(true, param);

                // generate random message
                int mLength = (rand.nextInt() & 0x1f) + 1;
                mBytes = new byte[mLength];
                rand.nextBytes(mBytes);

                // encrypt
                msgDigest.update(mBytes, 0, mBytes.length);
                byte[] hash = new byte[msgDigest.getDigestSize()];

                msgDigest.doFinal(hash, 0);

                byte[] enc = mcEliecePKCSDigestCipher.messageEncrypt(hash);

                // initialize for decryption
                mcEliecePKCSDigestCipher.init(false, pair.getPrivate());
                byte[] constructedmessage = mcEliecePKCSDigestCipher.messageDecrypt(enc);

                boolean verified = true;
                for (int i = 0; i < hash.length; i++)
                {
                    verified = verified && hash[i] == constructedmessage[i];
                }

                if (!verified)
                {
                    fail("en/decryption fails");
                }
                else
                {
                    // System.out.println("test okay");
                    // System.out.println();
                }

            }
        }

    }

    public void leadingZeroTest()
        throws Exception
    {
        /*
[encoded data, 6507 characters]

         */
        PrivateKeyInfo cca2PrivKey = PrivateKeyInfo.getInstance(
            Base64.decode(
                "[encoded data, 5688 characters]"));
        byte[] plainText = Base64.decode(
            "JPRvWBk1htKrDwB/tcjmdg02SxHNKyHwZqJ5EWxoFBpcCuthOyezRfBOKTAd7Py0pEYeq1POQqyWuhoIH7bLtdWK3WtUootS31fY2RGJ6h14Lyw80GmmawHFWbXwxirn3SkuWlF9DEs8fLa6SToRvR6JLJXYrM9I1U120z63xhRt0NyvYG/n/0H7IGpTD2gHjoK+AxpcyIV0pgRV69du6XX754P3JhH3WtUhDLo0pyeGI07di3aXxmLWoz8iAU1N3enwxDksZxT51hPkZERlcZ4l8p2B3rjE+JnQkaa0gWkE7WP+aoxcax6OXN00MgbX9yteJy/cRKdw+A==");
        byte[] cipherText = Base64.decode(
            "5Btx1aKTMktU9pwKG9U1KZp9OTag90msKyZhaqzWnXrDwJpPfbWZHt7VGOvbkKxQ8O6VdqDqyRMcAJPARZzjbYCTwug5jsUsEL2FQfaEpSw3bV8NYHcVPe9nz5a92cOjkSku9+GhTtAv1X/4UkIjgTdYeLEHoNmAmhfh3wrB9yWbOm7NujYa2T84w+9CxOBTfuPnKlay4O6vMRSpZGNG+BNMAkeDVGcQKqEofk80yDqW1GAbRY/kD7tqh0IXo6ARlGlumy/Zgmbb+1J4zo4obtB5s4JdrWo2d3JMK9vviQz9R2jOQme65prfp8pAM9OG3zNwqkFO8YdKjNMHUOZ+vEpwbzdzDhqOJprSWfAWL+PHk8xHevMKrCaqHLRp5Xk+rSkGAEaa9GuoNmQkO9Cx5qfvfpfzB+Md2YjmpeofOzL7QQRvE6yPRPANJys0pi7gGd2DHiw=");

        McElieceKobaraImaiCipher cipher = new McElieceKobaraImaiCipher();

        cipher.init(false, PrivateKeyFactory.createKey(cca2PrivKey));

        isTrue(Arrays.areEqual(plainText, cipher.messageDecrypt(cipherText)));
    }

    public static void main(
        String[] args)
    {
        runTest(new McElieceCipherTest());
    }

}
