Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package client;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.math.BigInteger;
- import java.net.MalformedURLException;
- import java.rmi.*;
- import java.security.*;
- import java.security.spec.*;
- import java.security.cert.CertificateException;
- import java.security.cert.X509Certificate;
- import java.security.interfaces.RSAPrivateKey;
- import java.security.interfaces.RSAPublicKey;
- import java.security.spec.InvalidKeySpecException;
- import java.sql.SQLException;
- import java.util.ArrayList;
- import java.util.InputMismatchException;
- import java.util.*;
- import java.util.Scanner;
- import java.io.*;
- import server.Account;
- import server.HDSBankInterface;
- import sun.security.tools.keytool.CertAndKeyGen;
- import sun.security.x509.*;
- public class BankClient {
- HDSBankInterface bank = null;
- private PublicKey pubkey;
- private PrivateKey privkey;
- private String senderstrpubkey;
- private String senderstrprivkey;
- private String receiverstrpubkey;
- private String username;
- private String password;
- private String name;
- private String nonce;
- private double amount;
- private int destPubKey;
- private String signature;
- private String keyStorePw;
- private PublicKey temppub;
- private PrivateKey temppriv;
- public boolean LoginBank(String username, String password) throws NotBoundException, SQLException, NoSuchAlgorithmException, InvalidKeySpecException, UnrecoverableKeyException, KeyStoreException, CertificateException, IOException{
- connectBank();
- this.username = username;
- this.password = password;
- this.keyStorePw = password;
- //System.out.println(this.username + ' ' + this.password);
- if(bank.login(this.username, this.password)){
- File f = new File("keystores/client/" + this.username + "KeyStore");
- if(f.exists() && !f.isDirectory()) {
- loadKeystore();
- System.out.println(testKeys());
- return true;
- }
- else {
- System.out.println("MAJOR ERROR: Login to server was successful but");
- System.out.println("Keystore couldn't be found! KeyStore was TAMPERED or DELETED!");
- return false;
- }
- }else{
- System.out.println("Server denied Log in!");
- return false;
- }
- }
- public String RegisterBank(String username, String password, String name) throws NotBoundException, SQLException, IOException, GeneralSecurityException {
- this.username = username;
- this.password = password;
- this.name = name;
- this.keyStorePw = password;
- connectBank();
- createKeystore();
- generateAndSave();
- return bank.register(this.pubkey, username, password, name);
- }
- private void connectBank() {
- try {
- this.bank = (HDSBankInterface)Naming.lookup("//localhost/HDSBank");
- }catch(Exception e) {
- System.out.println("ERROR: Couldn't connect to bank!" + e);
- }
- }
- public String send_amount(String receiverUsername, double amount) throws MalformedURLException, RemoteException, NotBoundException, SQLException, NoSuchAlgorithmException, UnsupportedEncodingException, SignatureException, InvalidKeySpecException, InvalidKeyException { // this has to be done with key value not int
- String sendSignature;
- System.out.println("daffffffffuuuuuuuuuuuuuuuuuuuqqqqqqqqqq");
- this.nonce = createNonce();
- System.out.println("lolololol");
- sendSignature = createSignature(this.username, receiverUsername, amount, this.nonce);
- System.out.println("damnnnn");
- // aqui em baixo trocar para chave publica de quem envia e depois de quem recebe
- System.out.println(sendSignature);
- //System.exit(0);
- // here we sign
- //this.signature = createSignature();
- //System.out.println(this.nonce);
- String rs = bank.send_amount(this.username, receiverUsername, amount, this.nonce, sendSignature);
- System.out.println(rs);
- return rs;
- }
- public ArrayList<String> check_account() throws MalformedURLException, RemoteException, NotBoundException, SQLException, NoSuchAlgorithmException, UnsupportedEncodingException, SignatureException, InvalidKeySpecException, InvalidKeyException {
- String checkAccSignature;
- this.nonce = createNonce();
- checkAccSignature = checkAccSignature(this.username, this.nonce);
- return bank.check_account(this.username, this.nonce, checkAccSignature);
- }
- public String receive_amount(String idTransaction) throws MalformedURLException, RemoteException, NotBoundException, SQLException, NoSuchAlgorithmException, UnsupportedEncodingException, SignatureException, InvalidKeySpecException, InvalidKeyException {
- String receiveSignature;
- this.nonce = createNonce();
- receiveSignature = receiveSignature(this.username, idTransaction, this.nonce);
- String ret = bank.receive_amount(this.username, idTransaction, this.nonce, receiveSignature);
- return ret;
- }
- public String createNonce() throws RemoteException, NoSuchAlgorithmException, UnsupportedEncodingException {
- String result = null;
- SecureRandom sr = new SecureRandom();
- byte[] newNonce = new byte[64];
- sr.nextBytes(newNonce);
- StringBuilder sb = new StringBuilder();
- for (byte b : newNonce) {
- sb.append(String.format("%02x", b));
- }
- //System.out.print("Key: ");
- result = sb.toString();
- return result;
- }
- public String createSignature(String senderUsername, String receiversUsername, double amount, String nonce) throws RemoteException, NoSuchAlgorithmException, UnsupportedEncodingException, SignatureException, InvalidKeyException {
- // GERAR CHAVES TESTE
- //KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
- //kpg.initialize(1024);
- //KeyPair keyPair = kpg.genKeyPair();
- // GERAR CHAVES TESTE
- //System.out.println(testKeys());
- //System.out.println("1 " + convertPubKeyToString(this.pubkey));
- String result = null;
- Signature signature = Signature.getInstance("SHA1WithRSA");
- Signature signature2 = Signature.getInstance("SHA1WithRSA");
- byte[] data0 = senderUsername.getBytes("UTF8");
- byte[] data1 = receiversUsername.getBytes("UTF8");
- byte[] data2 = String.valueOf(amount).getBytes("UTF8");
- byte[] data3 = nonce.getBytes("UTF8");
- //System.out.println(convertPubKeyToString(this.pubkey));
- //System.out.println(this.privkey);
- //System.out.println(this.pubkey);
- //System.exit(0);
- try{
- signature.initSign(this.privkey);
- } catch (Exception e){
- System.out.println(e);
- }
- signature.update(data0);
- signature.update(data1);
- signature.update(data2);
- signature.update(data3);
- byte[] signatureBytes = signature.sign();
- // DAQUI PA BAIXO E A VERIFICACAO - POR NOUTRA FUNCAO DEPOIS
- signature2.initVerify(this.pubkey);
- signature2.update(data0);
- signature2.update(data1);
- signature2.update(data2);
- signature2.update(data3);
- boolean verified = signature2.verify(signatureBytes);
- //System.exit(0);
- return Base64.getEncoder().encodeToString(signatureBytes);
- }
- public String checkAccSignature(String senderUsername, String nonce) throws RemoteException, NoSuchAlgorithmException, UnsupportedEncodingException, SignatureException, InvalidKeyException {
- String result = null;
- Signature signature = Signature.getInstance("SHA1WithRSA");
- Signature signature2 = Signature.getInstance("SHA1WithRSA");
- byte[] data0 = senderUsername.getBytes("UTF8");
- byte[] data1 = nonce.getBytes("UTF8");
- try{
- signature.initSign(this.privkey);
- } catch (Exception e){
- System.out.println(e);
- }
- signature.update(data0);
- signature.update(data1);
- byte[] signatureBytes = signature.sign();
- // DAQUI PA BAIXO E A VERIFICACAO - POR NOUTRA FUNCAO DEPOIS
- signature2.initVerify(this.pubkey);
- signature2.update(data0);
- signature2.update(data1);
- boolean verified = signature2.verify(signatureBytes);
- //System.exit(0);
- return Base64.getEncoder().encodeToString(signatureBytes);
- }
- public String receiveSignature(String receiverUsername, String idTransaction, String nonce) throws RemoteException, NoSuchAlgorithmException, UnsupportedEncodingException, SignatureException, InvalidKeyException {
- String result = null;
- Signature signature = Signature.getInstance("SHA1WithRSA");
- Signature signature2 = Signature.getInstance("SHA1WithRSA");
- byte[] data0 = receiverUsername.getBytes("UTF8");
- byte[] data1 = idTransaction.getBytes("UTF8");
- byte[] data2 = nonce.getBytes("UTF8");
- try{
- signature.initSign(this.privkey);
- } catch (Exception e){
- System.out.println(e);
- }
- signature.update(data0);
- signature.update(data1);
- signature.update(data2);
- byte[] signatureBytes = signature.sign();
- // DAQUI PA BAIXO E A VERIFICACAO - POR NOUTRA FUNCAO DEPOIS
- signature2.initVerify(this.pubkey);
- signature2.update(data0);
- signature2.update(data1);
- signature2.update(data2);
- boolean verified = signature2.verify(signatureBytes);
- //System.exit(0);
- return Base64.getEncoder().encodeToString(signatureBytes);
- }
- ////////////////////////////////////////////////////////// KEY FUNCTIONS ////////////////////////////////////////////////////////////
- private String convertPubKeyToString(PublicKey pub) {
- byte[] publicKeyBytes = pub.getEncoded();
- String pubkeyStr = Base64.getEncoder().encodeToString(publicKeyBytes);
- return pubkeyStr;
- }
- private PublicKey convertStringToPubKey(String pubString) throws NoSuchAlgorithmException, InvalidKeySpecException {
- byte[] publicBytes = Base64.getDecoder().decode(pubString);
- X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes);
- KeyFactory keyFactory = KeyFactory.getInstance("RSA");
- PublicKey pubKey = keyFactory.generatePublic(keySpec);
- return pubKey;
- }
- private void createKeystore() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
- char[] password = this.keyStorePw.toCharArray();
- KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
- ks.load(null, password);
- FileOutputStream fos = new FileOutputStream("keystores/client/" + this.username + "KeyStore");
- ks.store(fos, password);
- fos.close();
- }
- private void loadKeystore() throws IOException, UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, CertificateException {
- char[] password = this.keyStorePw.toCharArray();
- FileInputStream is = new FileInputStream("keystores/client/" + this.username + "KeyStore");
- KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
- keystore.load(is, password);
- Key priv = keystore.getKey(this.username, password);
- this.privkey = (PrivateKey) priv;
- if (this.privkey instanceof PrivateKey) {
- X509Certificate cert = (X509Certificate) keystore.getCertificate(this.username);
- this.pubkey = cert.getPublicKey();
- }
- }
- private void generateAndSave() throws GeneralSecurityException, IOException {
- char[] password = this.keyStorePw.toCharArray();
- KeyStore ks = KeyStore.getInstance("JKS");
- InputStream readStream = new FileInputStream("keystores/client/" + this.username + "KeyStore");
- ks.load(readStream, password);
- X509Certificate[] certChain = generateCertificate();
- ks.setKeyEntry(this.username, this.privkey, password, certChain);
- OutputStream writeStream = new FileOutputStream("keystores/client/" + this.username + "KeyStore");
- ks.store(writeStream, password);
- this.privkey = (PrivateKey) ks.getKey(this.username, password);
- this.pubkey = certChain[0].getPublicKey();
- writeStream.close();
- }
- private X509Certificate[] generateCertificate() throws GeneralSecurityException, IOException {
- try{
- CertAndKeyGen keyGen = new CertAndKeyGen("RSA","SHA1WithRSA",null);
- keyGen.generate(1024);
- this.pubkey = keyGen.getPublicKey();
- this.privkey = keyGen.getPrivateKey();
- //Generate self signed certificate
- X509Certificate[] chain=new X509Certificate[1];
- chain[0]=keyGen.getSelfCertificate(new X500Name("CN=HDSBank"), (long)365*24*3600);
- return chain;
- }catch(Exception ex){
- ex.printStackTrace();
- }
- return null;
- }
- private boolean testKeys() {
- RSAPublicKey rsaPublicKey = (RSAPublicKey) this.pubkey;
- RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) this.privkey;
- return rsaPublicKey.getModulus().equals( rsaPrivateKey.getModulus() )
- && BigInteger.valueOf( 2 ).modPow( rsaPublicKey.getPublicExponent()
- .multiply( rsaPrivateKey.getPrivateExponent() ).subtract( BigInteger.ONE ),
- rsaPublicKey.getModulus() ).equals( BigInteger.ONE );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement