Untitled
user_4708448
plain_text
3 years ago
14 kB
7
Indexable
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.SignatureException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateFactory;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.*;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
public class lab4
{
public static boolean checkCert(String certFile, String email)
{
try
{
CertificateFactory cf= CertificateFactory.getInstance("X509");
FileInputStream fis = new FileInputStream("C:\\Users\\pniki\\Downloads\\CMPSC 444\\Lab 4\\root.crt");
X509Certificate root = (X509Certificate) cf.generateCertificate(fis);
FileInputStream fs = new FileInputStream(certFile);
X509Certificate cert = (X509Certificate) cf.generateCertificate(fs);
PublicKey rootkey=root.getPublicKey();
cert.checkValidity();
System.out.println(cert.getSubjectX500Principal().toString());
if(!((cert.getSubjectX500Principal().toString()).contains(email)||(cert.getSubjectX500Principal().toString()).contains("nkp5373@psu.edu")))
{
System.out.println("Invalid Email Address in certificate");
return false;
}
Date dbefore=cert.getNotBefore();
Date dafter=cert.getNotAfter();
System.out.println("The certificate is valid from "+dbefore+" to "+dafter);
cert.verify(rootkey);
return true;
}catch(CertificateExpiredException e)
{
System.out.println("The certificate has expired");
return false;
}
catch(CertificateNotYetValidException e)
{
System.out.println("The Certificate has not been issued");
return false;
}
catch(SignatureException e)
{
System.out.println("The Certificate a bad signature");
return false;
}
catch(InvalidKeyException e)
{
System.out.println("The Certificate has invalid key");
return false;
}
catch(NoSuchAlgorithmException e)
{
System.out.println("The Certificate encryption algorithm is invalid");
return false;
}
catch(NoSuchProviderException e)
{
System.out.println("The Certificate was provided by a non trusted source");
return false;
}
catch(CertificateException e)
{
System.out.println("The Certificate is invalid");
return false;
}
catch(FileNotFoundException e)
{
System.out.println("File not found");
return false;
}
}
public static void encrypt(String certFile, String email, String privKeyFile, String message)
{
try
{
System.out.println("***********ENCRYPT METHOD***********");
if(checkCert(certFile, email))
System.out.println("Certificate Valid");
else
{
System.out.println("Invalid Certificate");
return;
}
SecureRandom random = SecureRandom.getInstanceStrong();
KeyGenerator generator = KeyGenerator.getInstance("AES");
generator.init(128, random);
SecretKey key = generator.generateKey();
//System.out.println("KEY : "+key);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encrypted = cipher.doFinal(message.getBytes());
String ciphertext=Base64.getEncoder().encodeToString(encrypted);
System.out.println("Ciphertext : "+ciphertext);
String iv=Base64.getEncoder().encodeToString(cipher.getIV());
System.out.println("IV : "+iv);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate certificate = (X509Certificate) cf.generateCertificate(new FileInputStream(certFile));
System.out.println(certificate.getPublicKey());
Cipher rsaCipher = Cipher.getInstance("RSA");
rsaCipher.init(Cipher.WRAP_MODE, certificate);
String wrappedKey = Base64.getEncoder().encodeToString(rsaCipher.wrap(key));
System.out.println("RSA Wrapped Key : "+wrappedKey);
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(message.trim().getBytes());
byte[] hash = md.digest();
System.out.println(hash);
System.out.println("HASH: "+hash.toString());
File KeyFile = new File(privKeyFile);
DataInputStream dis = new DataInputStream(new FileInputStream(KeyFile));
byte[] privKeyBytes = new byte[(int) KeyFile.length()];
dis.read(privKeyBytes);
dis.close();
PKCS8EncodedKeySpec pkcs8keySpec = new PKCS8EncodedKeySpec(privKeyBytes);
PrivateKey privKey = KeyFactory.getInstance("RSA").generatePrivate(pkcs8keySpec);
System.out.println("Private Key : "+ privKey);
Cipher rsa2Cipher = Cipher.getInstance("RSA");
rsa2Cipher.init(Cipher.ENCRYPT_MODE,privKey);
String signature = Base64.getEncoder().encodeToString(rsa2Cipher.doFinal(hash));
System.out.println("\nHASH : "+signature);
System.out.println("***********END OF ENCRYPT METHOD***********");
decrypt(certFile, email, privKeyFile, wrappedKey, iv, ciphertext, signature);
}
catch(NoSuchAlgorithmException | NoSuchPaddingException e)
{
System.out.println("Invalid Algorithm/Padding in file");
// return;
}
catch (InvalidKeyException e) {
System.out.println("Invalid Key");
// e.printStackTrace();
}
catch (IllegalBlockSizeException e)
{
System.out.println("Invalid Block Size");
// e.printStackTrace();
}
catch (BadPaddingException e)
{
System.out.println("Invalid Padding");
// e.printStackTrace();
}
catch (CertificateException e)
{
System.out.println("Invalid Certificate");
// e.printStackTrace();
}
catch (FileNotFoundException e)
{
System.out.println("Certificate file not found");
// e.printStackTrace();
}
catch (UnsupportedEncodingException e)
{
System.out.println("Invalid encoding in file");
// e.printStackTrace();
}
catch (IOException e)
{
System.out.println("Private key file not found");
// e.printStackTrace();
}
catch (InvalidKeySpecException e)
{
System.out.println("Private key file is not in PKCS8 format");
// e.printStackTrace();
}
}
public static void decrypt(String certFile, String email, String privKeyFile, String wrappedKey, String IV, String ciphertext, String signature)
{
System.out.println("***********DECRYPT METHOD***********");
CertificateFactory cf;
try {
File KeyFile = new File(privKeyFile);
DataInputStream dis = new DataInputStream(new FileInputStream(KeyFile));
byte[] privKeyBytes = new byte[(int) KeyFile.length()];
dis.read(privKeyBytes);
dis.close();
PKCS8EncodedKeySpec pkcs8keySpec = new PKCS8EncodedKeySpec(privKeyBytes);
PrivateKey privKey = KeyFactory.getInstance("RSA").generatePrivate(pkcs8keySpec);
if(checkCert(certFile, email))
System.out.println("Certificate Valid");
else
{
System.out.println("Invalid Certificate");
return;
}
cf = CertificateFactory.getInstance("X.509");
X509Certificate certificate = (X509Certificate) cf.generateCertificate(new FileInputStream(certFile));
Cipher rsaCipher = Cipher.getInstance("RSA");
rsaCipher.init(Cipher.UNWRAP_MODE, privKey);
System.out.println("Cipher Init");
SecretKey aesKey = (SecretKey) rsaCipher.unwrap(Base64.getDecoder().decode(wrappedKey), "AES", Cipher.SECRET_KEY);
System.out.println("RSA UnWrapped Key : "+aesKey);
IvParameterSpec iv = new IvParameterSpec(Base64.getDecoder().decode(IV));
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, aesKey, iv);
byte[] dtext=cipher.doFinal(Base64.getDecoder().decode(ciphertext));
String decryptedtext= new String(dtext);
System.out.println(decryptedtext);
System.out.println("Signature : "+signature);
Cipher rsa2Cipher = Cipher.getInstance("RSA");
//System.out.println("Public Key : "+certificate.getPublicKey());
rsa2Cipher.init(Cipher.DECRYPT_MODE,certificate.getPublicKey());
//String decryptedSignature = new String(rsa2Cipher.doFinal((signature.getBytes())));
String decryptedSignature = new String(rsa2Cipher.doFinal(Base64.getDecoder().decode(signature)));
System.out.println("Decrypted Signature : \n"+decryptedSignature+"\nEnd of dec Sign");
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(dtext);
byte[] hash = md.digest();
System.out.println(hash);
//String newHash=new String(Base64.getEncoder().encodeToString(hash));
System.out.println("New hash : "+hash.toString());
if (decryptedSignature.equals(hash.toString()))
System.out.println(decryptedtext);
else
System.out.println("Message has been tampered with");
}
catch (CertificateException e)
{
System.out.println("Key couldn't be unwrapped, Bad key provided EX1");
// e.printStackTrace();
}
catch (NoSuchAlgorithmException e)
{
System.out.println("Key couldn't be unwrapped, Bad key provided EX2");
// e.printStackTrace();
}
catch (NoSuchPaddingException e)
{
System.out.println("Key couldn't be unwrapped, Bad key provided EX3");
// e.printStackTrace();
}
catch (FileNotFoundException e)
{
System.out.println("Key couldn't be unwrapped, Private key file not found");
//e.printStackTrace();
}
catch (InvalidKeyException e)
{
System.out.println("Key couldn't be unwrapped, Bad key provided EX4");
//e.printStackTrace();
}
catch (IOException e)
{
System.out.println("Key couldn't be unwrapped, Bad key provided EX5");
//e.printStackTrace();
}
catch (InvalidKeySpecException e)
{
System.out.println("Key couldn't be unwrapped, Bad key provided EX6");
//e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
System.out.println("Invalid key is provided, the ciphertext cannot be decrypted");
//e.printStackTrace();
}
catch (IllegalBlockSizeException e)
{
System.out.println("Invalid IV is provided, the ciphertext cannot be decrypted");
//e.printStackTrace();
}
catch (BadPaddingException e)
{
System.out.println("Bad IV/Key is provided");
//e.printStackTrace();
}
}
public static void main(String args[])throws Exception
{
// CertificateFactory cf= CertificateFactory.getInstance("X509");
// String val=cert.getSubjectX500Principal().toString();
// System.out.println(val);
// String email="";
if(checkCert("C:\\Users\\pniki\\Downloads\\CMPSC 444\\Lab 4\\blum1.cert", "jjb24@cs.hbg.psu.edu"))
System.out.println("Valid Certificate");
else
System.out.println("Invalid Certificate");
encrypt("C:\\Users\\pniki\\Downloads\\CMPSC 444\\Lab 4\\nikil.cert", "nkp5373@psu.edu", "C:\\Users\\pniki\\Downloads\\CMPSC 444\\Lab 4\\nikil.priv", "123456");
}
} Editor is loading...