package gr.duth.eece.cryptographyLesson.asymmetric.rsa;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Arrays;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

public class PaddedRSA_PKCS {


public PublicKey publicKey;
public PrivateKey privateKey;

public PaddedRSA_PKCS()
{

}

public void generateKeys(int bits) throws NoSuchAlgorithmException{
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(bits);
    KeyPair kp = kpg.genKeyPair();

    publicKey = kp.getPublic();
    privateKey = kp.getPrivate();
}


public BigInteger Encrypt(BigInteger plain) throws NoSuchAlgorithmException,
        NoSuchPaddingException, InvalidKeyException,
        IllegalBlockSizeException, BadPaddingException {

	BigInteger encrypted;
    byte[] encryptedBytes;      

    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    encryptedBytes = cipher.doFinal(plain.toByteArray());

    encrypted = new BigInteger(encryptedBytes);
    return encrypted;

}

public BigInteger Decrypt(BigInteger ciphertext) throws NoSuchAlgorithmException,
        NoSuchPaddingException, InvalidKeyException,
        IllegalBlockSizeException, BadPaddingException {

    byte[] decryptedBytes;
    BigInteger decrypted;

    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.DECRYPT_MODE, privateKey);
    decryptedBytes = cipher.doFinal(ciphertext.toByteArray());
    decrypted = new BigInteger(decryptedBytes);
    return decrypted;

}

}