package meerkat.voting;

import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Message;
import meerkat.crypto.Encryption;
import meerkat.protobuf.Crypto.*;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Random;

/**
 * Created by hai on 07/06/16.
 */
public class ToyEncryption implements Encryption {

    @Override
    public RerandomizableEncryptedMessage encrypt(Message plaintext, EncryptionRandomness rnd) throws IOException {
        ByteString cipher = ByteString.copyFromUtf8("Encryption(")
                .concat(plaintext.toByteString())
                .concat(ByteString.copyFromUtf8(", Random("))
                .concat(rnd.getData())
                .concat(ByteString.copyFromUtf8("))"));
        return RerandomizableEncryptedMessage.newBuilder()
                .setData(cipher)
                .build();
    }

    @Override
    public RerandomizableEncryptedMessage rerandomize
            (RerandomizableEncryptedMessage msg, EncryptionRandomness rnd) throws InvalidProtocolBufferException {
        throw new UnsupportedOperationException();
    }

    @Override
    public EncryptionRandomness generateRandomness(Random rand) {
        ByteBuffer b = ByteBuffer.allocate(4);
        b.putInt(rand.nextInt());
        byte[] bArr = b.array();
        ByteString bs = ByteString.copyFrom(bArr);
        return EncryptionRandomness.newBuilder()
                .setData(bs)
                .build();
    }
}
