Advertisement
Guest User

Untitled

a guest
Apr 5th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.38 KB | None | 0 0
  1. package client;
  2.  
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.FileOutputStream;
  6. import java.io.IOException;
  7. import java.io.InputStream;
  8. import java.io.OutputStream;
  9. import java.math.BigInteger;
  10. import java.net.MalformedURLException;
  11. import java.rmi.*;
  12. import java.security.*;
  13. import java.security.spec.*;
  14. import java.security.cert.CertificateException;
  15. import java.security.cert.X509Certificate;
  16. import java.security.interfaces.RSAPrivateKey;
  17. import java.security.interfaces.RSAPublicKey;
  18. import java.security.spec.InvalidKeySpecException;
  19. import java.sql.SQLException;
  20. import java.util.ArrayList;
  21. import java.util.InputMismatchException;
  22. import java.util.*;
  23. import java.util.Scanner;
  24. import java.io.*;
  25. import server.Account;
  26. import server.HDSBankInterface;
  27.  
  28. import sun.security.tools.keytool.CertAndKeyGen;
  29. import sun.security.x509.*;
  30.  
  31. public class BankClient {
  32.  
  33. HDSBankInterface bank = null;
  34.  
  35. private PublicKey pubkey;
  36. private PrivateKey privkey;
  37. private String senderstrpubkey;
  38. private String senderstrprivkey;
  39. private String receiverstrpubkey;
  40. private String username;
  41. private String password;
  42. private String name;
  43. private String nonce;
  44. private double amount;
  45. private int destPubKey;
  46. private String signature;
  47.  
  48. private String keyStorePw;
  49.  
  50. private PublicKey temppub;
  51. private PrivateKey temppriv;
  52.  
  53. public boolean LoginBank(String username, String password) throws NotBoundException, SQLException, NoSuchAlgorithmException, InvalidKeySpecException, UnrecoverableKeyException, KeyStoreException, CertificateException, IOException{
  54. connectBank();
  55. this.username = username;
  56. this.password = password;
  57. this.keyStorePw = password;
  58. //System.out.println(this.username + ' ' + this.password);
  59. if(bank.login(this.username, this.password)){
  60. File f = new File("keystores/client/" + this.username + "KeyStore");
  61. if(f.exists() && !f.isDirectory()) {
  62. loadKeystore();
  63. System.out.println(testKeys());
  64. return true;
  65. }
  66. else {
  67. System.out.println("MAJOR ERROR: Login to server was successful but");
  68. System.out.println("Keystore couldn't be found! KeyStore was TAMPERED or DELETED!");
  69. return false;
  70. }
  71.  
  72. }else{
  73. System.out.println("Server denied Log in!");
  74. return false;
  75. }
  76. }
  77.  
  78. public String RegisterBank(String username, String password, String name) throws NotBoundException, SQLException, IOException, GeneralSecurityException {
  79. this.username = username;
  80. this.password = password;
  81. this.name = name;
  82. this.keyStorePw = password;
  83. connectBank();
  84. createKeystore();
  85. generateAndSave();
  86. return bank.register(this.pubkey, username, password, name);
  87. }
  88.  
  89. private void connectBank() {
  90. try {
  91. this.bank = (HDSBankInterface)Naming.lookup("//localhost/HDSBank");
  92. }catch(Exception e) {
  93. System.out.println("ERROR: Couldn't connect to bank!" + e);
  94. }
  95. }
  96.  
  97.  
  98. 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
  99. String sendSignature;
  100. System.out.println("daffffffffuuuuuuuuuuuuuuuuuuuqqqqqqqqqq");
  101. this.nonce = createNonce();
  102. System.out.println("lolololol");
  103. sendSignature = createSignature(this.username, receiverUsername, amount, this.nonce);
  104. System.out.println("damnnnn");
  105. // aqui em baixo trocar para chave publica de quem envia e depois de quem recebe
  106. System.out.println(sendSignature);
  107. //System.exit(0);
  108. // here we sign
  109. //this.signature = createSignature();
  110. //System.out.println(this.nonce);
  111. String rs = bank.send_amount(this.username, receiverUsername, amount, this.nonce, sendSignature);
  112. System.out.println(rs);
  113. return rs;
  114.  
  115. }
  116.  
  117. public ArrayList<String> check_account() throws MalformedURLException, RemoteException, NotBoundException, SQLException, NoSuchAlgorithmException, UnsupportedEncodingException, SignatureException, InvalidKeySpecException, InvalidKeyException {
  118. String checkAccSignature;
  119. this.nonce = createNonce();
  120.  
  121. checkAccSignature = checkAccSignature(this.username, this.nonce);
  122.  
  123.  
  124. return bank.check_account(this.username, this.nonce, checkAccSignature);
  125. }
  126.  
  127. public String receive_amount(String idTransaction) throws MalformedURLException, RemoteException, NotBoundException, SQLException, NoSuchAlgorithmException, UnsupportedEncodingException, SignatureException, InvalidKeySpecException, InvalidKeyException {
  128. String receiveSignature;
  129. this.nonce = createNonce();
  130.  
  131. receiveSignature = receiveSignature(this.username, idTransaction, this.nonce);
  132. String ret = bank.receive_amount(this.username, idTransaction, this.nonce, receiveSignature);
  133.  
  134. return ret;
  135. }
  136.  
  137. public String createNonce() throws RemoteException, NoSuchAlgorithmException, UnsupportedEncodingException {
  138. String result = null;
  139. SecureRandom sr = new SecureRandom();
  140. byte[] newNonce = new byte[64];
  141. sr.nextBytes(newNonce);
  142.  
  143. StringBuilder sb = new StringBuilder();
  144. for (byte b : newNonce) {
  145. sb.append(String.format("%02x", b));
  146. }
  147. //System.out.print("Key: ");
  148. result = sb.toString();
  149.  
  150. return result;
  151.  
  152. }
  153.  
  154. public String createSignature(String senderUsername, String receiversUsername, double amount, String nonce) throws RemoteException, NoSuchAlgorithmException, UnsupportedEncodingException, SignatureException, InvalidKeyException {
  155.  
  156. // GERAR CHAVES TESTE
  157. //KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
  158. //kpg.initialize(1024);
  159. //KeyPair keyPair = kpg.genKeyPair();
  160. // GERAR CHAVES TESTE
  161. //System.out.println(testKeys());
  162. //System.out.println("1 " + convertPubKeyToString(this.pubkey));
  163. String result = null;
  164. Signature signature = Signature.getInstance("SHA1WithRSA");
  165. Signature signature2 = Signature.getInstance("SHA1WithRSA");
  166.  
  167. byte[] data0 = senderUsername.getBytes("UTF8");
  168. byte[] data1 = receiversUsername.getBytes("UTF8");
  169. byte[] data2 = String.valueOf(amount).getBytes("UTF8");
  170. byte[] data3 = nonce.getBytes("UTF8");
  171.  
  172. //System.out.println(convertPubKeyToString(this.pubkey));
  173. //System.out.println(this.privkey);
  174. //System.out.println(this.pubkey);
  175. //System.exit(0);
  176.  
  177. try{
  178. signature.initSign(this.privkey);
  179. } catch (Exception e){
  180. System.out.println(e);
  181. }
  182. signature.update(data0);
  183. signature.update(data1);
  184. signature.update(data2);
  185. signature.update(data3);
  186.  
  187. byte[] signatureBytes = signature.sign();
  188. // DAQUI PA BAIXO E A VERIFICACAO - POR NOUTRA FUNCAO DEPOIS
  189. signature2.initVerify(this.pubkey);
  190.  
  191. signature2.update(data0);
  192. signature2.update(data1);
  193. signature2.update(data2);
  194. signature2.update(data3);
  195.  
  196. boolean verified = signature2.verify(signatureBytes);
  197.  
  198.  
  199. //System.exit(0);
  200. return Base64.getEncoder().encodeToString(signatureBytes);
  201. }
  202.  
  203. public String checkAccSignature(String senderUsername, String nonce) throws RemoteException, NoSuchAlgorithmException, UnsupportedEncodingException, SignatureException, InvalidKeyException {
  204.  
  205. String result = null;
  206. Signature signature = Signature.getInstance("SHA1WithRSA");
  207. Signature signature2 = Signature.getInstance("SHA1WithRSA");
  208.  
  209. byte[] data0 = senderUsername.getBytes("UTF8");
  210. byte[] data1 = nonce.getBytes("UTF8");
  211.  
  212. try{
  213. signature.initSign(this.privkey);
  214. } catch (Exception e){
  215. System.out.println(e);
  216. }
  217. signature.update(data0);
  218. signature.update(data1);
  219.  
  220. byte[] signatureBytes = signature.sign();
  221. // DAQUI PA BAIXO E A VERIFICACAO - POR NOUTRA FUNCAO DEPOIS
  222. signature2.initVerify(this.pubkey);
  223.  
  224. signature2.update(data0);
  225. signature2.update(data1);
  226.  
  227.  
  228. boolean verified = signature2.verify(signatureBytes);
  229.  
  230.  
  231. //System.exit(0);
  232. return Base64.getEncoder().encodeToString(signatureBytes);
  233. }
  234.  
  235.  
  236. public String receiveSignature(String receiverUsername, String idTransaction, String nonce) throws RemoteException, NoSuchAlgorithmException, UnsupportedEncodingException, SignatureException, InvalidKeyException {
  237.  
  238. String result = null;
  239. Signature signature = Signature.getInstance("SHA1WithRSA");
  240. Signature signature2 = Signature.getInstance("SHA1WithRSA");
  241.  
  242. byte[] data0 = receiverUsername.getBytes("UTF8");
  243. byte[] data1 = idTransaction.getBytes("UTF8");
  244. byte[] data2 = nonce.getBytes("UTF8");
  245.  
  246. try{
  247. signature.initSign(this.privkey);
  248. } catch (Exception e){
  249. System.out.println(e);
  250. }
  251. signature.update(data0);
  252. signature.update(data1);
  253. signature.update(data2);
  254.  
  255. byte[] signatureBytes = signature.sign();
  256. // DAQUI PA BAIXO E A VERIFICACAO - POR NOUTRA FUNCAO DEPOIS
  257. signature2.initVerify(this.pubkey);
  258.  
  259. signature2.update(data0);
  260. signature2.update(data1);
  261. signature2.update(data2);
  262.  
  263.  
  264. boolean verified = signature2.verify(signatureBytes);
  265.  
  266. //System.exit(0);
  267. return Base64.getEncoder().encodeToString(signatureBytes);
  268. }
  269.  
  270.  
  271. ////////////////////////////////////////////////////////// KEY FUNCTIONS ////////////////////////////////////////////////////////////
  272.  
  273.  
  274. private String convertPubKeyToString(PublicKey pub) {
  275. byte[] publicKeyBytes = pub.getEncoded();
  276. String pubkeyStr = Base64.getEncoder().encodeToString(publicKeyBytes);
  277. return pubkeyStr;
  278. }
  279.  
  280. private PublicKey convertStringToPubKey(String pubString) throws NoSuchAlgorithmException, InvalidKeySpecException {
  281. byte[] publicBytes = Base64.getDecoder().decode(pubString);
  282. X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes);
  283. KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  284. PublicKey pubKey = keyFactory.generatePublic(keySpec);
  285. return pubKey;
  286. }
  287.  
  288. private void createKeystore() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
  289. char[] password = this.keyStorePw.toCharArray();
  290. KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  291. ks.load(null, password);
  292. FileOutputStream fos = new FileOutputStream("keystores/client/" + this.username + "KeyStore");
  293. ks.store(fos, password);
  294. fos.close();
  295. }
  296.  
  297. private void loadKeystore() throws IOException, UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, CertificateException {
  298. char[] password = this.keyStorePw.toCharArray();
  299.  
  300. FileInputStream is = new FileInputStream("keystores/client/" + this.username + "KeyStore");
  301. KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
  302. keystore.load(is, password);
  303.  
  304. Key priv = keystore.getKey(this.username, password);
  305. this.privkey = (PrivateKey) priv;
  306. if (this.privkey instanceof PrivateKey) {
  307. X509Certificate cert = (X509Certificate) keystore.getCertificate(this.username);
  308. this.pubkey = cert.getPublicKey();
  309. }
  310. }
  311.  
  312. private void generateAndSave() throws GeneralSecurityException, IOException {
  313. char[] password = this.keyStorePw.toCharArray();
  314.  
  315. KeyStore ks = KeyStore.getInstance("JKS");
  316. InputStream readStream = new FileInputStream("keystores/client/" + this.username + "KeyStore");
  317. ks.load(readStream, password);
  318.  
  319. X509Certificate[] certChain = generateCertificate();
  320. ks.setKeyEntry(this.username, this.privkey, password, certChain);
  321. OutputStream writeStream = new FileOutputStream("keystores/client/" + this.username + "KeyStore");
  322. ks.store(writeStream, password);
  323. this.privkey = (PrivateKey) ks.getKey(this.username, password);
  324. this.pubkey = certChain[0].getPublicKey();
  325. writeStream.close();
  326. }
  327.  
  328. private X509Certificate[] generateCertificate() throws GeneralSecurityException, IOException {
  329. try{
  330. CertAndKeyGen keyGen = new CertAndKeyGen("RSA","SHA1WithRSA",null);
  331. keyGen.generate(1024);
  332. this.pubkey = keyGen.getPublicKey();
  333. this.privkey = keyGen.getPrivateKey();
  334. //Generate self signed certificate
  335. X509Certificate[] chain=new X509Certificate[1];
  336. chain[0]=keyGen.getSelfCertificate(new X500Name("CN=HDSBank"), (long)365*24*3600);
  337.  
  338. return chain;
  339. }catch(Exception ex){
  340. ex.printStackTrace();
  341. }
  342. return null;
  343.  
  344. }
  345.  
  346.  
  347. private boolean testKeys() {
  348. RSAPublicKey rsaPublicKey = (RSAPublicKey) this.pubkey;
  349. RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) this.privkey;
  350. return rsaPublicKey.getModulus().equals( rsaPrivateKey.getModulus() )
  351. && BigInteger.valueOf( 2 ).modPow( rsaPublicKey.getPublicExponent()
  352. .multiply( rsaPrivateKey.getPrivateExponent() ).subtract( BigInteger.ONE ),
  353. rsaPublicKey.getModulus() ).equals( BigInteger.ONE );
  354. }
  355.  
  356. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement