Advertisement
Guest User

Untitled

a guest
Dec 17th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.03 KB | None | 0 0
  1. import org.mindrot.jbcrypt.BCrypt;
  2. import sun.misc.BASE64Encoder;
  3.  
  4. import javax.crypto.Cipher;
  5. import javax.crypto.KeyAgreement;
  6. import javax.crypto.interfaces.DHPublicKey;
  7. import javax.crypto.spec.DHParameterSpec;
  8. import javax.crypto.spec.SecretKeySpec;
  9. import java.io.FileInputStream;
  10. import java.io.FileOutputStream;
  11. import java.io.InputStream;
  12. import java.nio.charset.StandardCharsets;
  13. import java.nio.file.Files;
  14. import java.nio.file.Path;
  15. import java.nio.file.Paths;
  16. import java.security.*;
  17. import java.security.spec.PKCS8EncodedKeySpec;
  18. import java.security.spec.X509EncodedKeySpec;
  19.  
  20. public class DHKeyAgreement2 {
  21. private DHKeyAgreement2() {}
  22. private static final int logRounds=12;
  23.  
  24. public static String hashpw(String password) {
  25. return BCrypt.hashpw(password, BCrypt.gensalt(logRounds));
  26. }
  27.  
  28. public static boolean verifyHash(String password, String hash) {
  29. return BCrypt.checkpw(password, hash);
  30. }
  31. public static void main(String argv[]) throws Exception {
  32.  
  33. /*
  34. * Alice creates her own DH key pair with 2048-bit key size
  35. */
  36. System.out.println("ALICE: Generate DH keypair ...");
  37. KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance("DH");
  38. aliceKpairGen.initialize(2048);
  39. KeyPair aliceKpair = aliceKpairGen.generateKeyPair();
  40.  
  41. // Alice creates and initializes her DH KeyAgreement object
  42. System.out.println("ALICE: Initialization ...");
  43. KeyAgreement aliceKeyAgree = KeyAgreement.getInstance("DH");
  44. aliceKeyAgree.init(aliceKpair.getPrivate());
  45.  
  46. // Alice encodes her public key, and sends it over to Bob.
  47. byte[] alicePubKeyEnc = aliceKpair.getPublic().getEncoded();
  48.  
  49. /*
  50. * Let's turn over to Bob. Bob has received Alice's public key
  51. * in encoded format.
  52. * He instantiates a DH public key from the encoded key material.
  53. */
  54. KeyFactory bobKeyFac = KeyFactory.getInstance("DH");
  55. X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(alicePubKeyEnc);
  56.  
  57. PublicKey alicePubKey = bobKeyFac.generatePublic(x509KeySpec);
  58. System.out.println("aquiiiiiiiiiiiiii:");
  59. /*
  60. * Bob gets the DH parameters associated with Alice's public key.
  61. * He must use the same parameters when he generates his own key
  62. * pair.
  63. */
  64. DHParameterSpec dhParamFromAlicePubKey = ((DHPublicKey)alicePubKey).getParams();
  65.  
  66. // Bob creates his own DH key pair
  67. System.out.println("BOB: Generate DH keypair ...");
  68. KeyPairGenerator bobKpairGen = KeyPairGenerator.getInstance("DH");
  69. bobKpairGen.initialize(dhParamFromAlicePubKey);
  70. KeyPair bobKpair = bobKpairGen.generateKeyPair();
  71.  
  72. // Bob creates and initializes his DH KeyAgreement object
  73. System.out.println("BOB: Initialization ...");
  74. KeyAgreement bobKeyAgree = KeyAgreement.getInstance("DH");
  75. bobKeyAgree.init(bobKpair.getPrivate());
  76.  
  77. // Bob encodes his public key, and sends it over to Alice.
  78. byte[] bobPubKeyEnc = bobKpair.getPublic().getEncoded();
  79.  
  80. /*
  81. * Alice uses Bob's public key for the first (and only) phase
  82. * of her version of the DH
  83. * protocol.
  84. * Before she can do so, she has to instantiate a DH public key
  85. * from Bob's encoded key material.
  86. */
  87. KeyFactory aliceKeyFac = KeyFactory.getInstance("DH");
  88. x509KeySpec = new X509EncodedKeySpec(bobPubKeyEnc);
  89. PublicKey bobPubKey = aliceKeyFac.generatePublic(x509KeySpec);
  90. System.out.println("ALICE: Execute PHASE1 ...");
  91. aliceKeyAgree.doPhase(bobPubKey, true);
  92.  
  93. /*
  94. * Bob uses Alice's public key for the first (and only) phase
  95. * of his version of the DH
  96. * protocol.
  97. */
  98. System.out.println("BOB: Execute PHASE1 ...");
  99. bobKeyAgree.doPhase(alicePubKey, true);
  100.  
  101. /*
  102. * At this stage, both Alice and Bob have completed the DH key
  103. * agreement protocol.
  104. * Both generate the (same) shared secret.
  105. */
  106.  
  107.  
  108. byte[] aliceSharedSecret = aliceKeyAgree.generateSecret();
  109. int aliceLen = aliceSharedSecret.length;
  110. byte[] bobSharedSecret = new byte[aliceLen];
  111. int bobLen;
  112.  
  113. bobLen = bobKeyAgree.generateSecret(bobSharedSecret, 0);
  114. System.out.println("Alice secret: " +
  115. toHexString(aliceSharedSecret));
  116. System.out.println("Bob secret: " +
  117. toHexString(bobSharedSecret));
  118. if (!java.util.Arrays.equals(aliceSharedSecret, bobSharedSecret))
  119. throw new Exception("Shared secrets differ");
  120. System.out.println("Shared secrets are the same");
  121. System.out.println(aliceLen);
  122.  
  123. System.out.println("Use shared secret as SecretKey object ...");
  124. SecretKeySpec bobAesKey = new SecretKeySpec(bobSharedSecret, 0, 16, "AES");
  125. SecretKeySpec aliceAesKey = new SecretKeySpec(aliceSharedSecret, 0, 16, "AES");
  126.  
  127. /*
  128. * Bob encrypts, using AES in CBC mode
  129. */
  130. Cipher bobCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
  131. bobCipher.init(Cipher.ENCRYPT_MODE, bobAesKey);
  132. byte[] cleartext = "This is just an example".getBytes();
  133. byte[] ciphertext = bobCipher.doFinal(cleartext);
  134.  
  135. // Retrieve the parameter that was used, and transfer it to Alice in
  136. // encoded format
  137. byte[] encodedParams = bobCipher.getParameters().getEncoded();
  138.  
  139. /*
  140. * Alice decrypts, using AES in CBC mode
  141. */
  142.  
  143. // Instantiate AlgorithmParameters object from parameter encoding
  144. // obtained from Bob
  145. AlgorithmParameters aesParams = AlgorithmParameters.getInstance("AES");
  146. aesParams.init(encodedParams);
  147. Cipher aliceCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
  148. aliceCipher.init(Cipher.DECRYPT_MODE, aliceAesKey, aesParams);
  149. byte[] recovered = aliceCipher.doFinal(ciphertext);
  150. if (!java.util.Arrays.equals(cleartext, recovered))
  151. throw new Exception("AES in CBC mode recovered text is " +
  152. "different from cleartext");
  153. System.out.println("AES in CBC mode recovered text is same as cleartext");
  154. System.out.println(new String(recovered, StandardCharsets.UTF_8));
  155.  
  156. System.out.println("-------------------------------------------------------------");
  157. KeyPairGenerator kpg=KeyPairGenerator.getInstance("RSA");
  158. kpg.initialize(2048);
  159. KeyPair AliceTrueKeyPare=kpg.generateKeyPair();
  160.  
  161.  
  162.  
  163. String hash=hashpw("password");
  164. conectBD con=new conectBD();
  165. con.inserirUser("Alice",hash,AliceTrueKeyPare.getPublic());
  166. if(con.confirmLogin("Alice","password"))
  167. System.out.println("fuck yeah boiiiiiii");
  168. if(toHexString(con.userPublic("Alice").getEncoded()).equals(toHexString(AliceTrueKeyPare.getPublic().getEncoded())))
  169. System.out.println("sou mesmo bom");
  170. System.out.println(toHexString(AliceTrueKeyPare.getPublic().getEncoded()));
  171. System.out.println(toHexString(con.userPublic("Alice").getEncoded()));
  172. System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++");
  173. Signature signature=Signature.getInstance("SHA256WithRSA");
  174. signature.initSign(AliceTrueKeyPare.getPrivate());
  175. String original="this is the string test";
  176. System.out.println("original message:"+original);
  177. try{
  178. byte[] data=original.getBytes("UTF8");
  179. signature.update(data);
  180. byte[] signatureBytes=signature.sign();
  181. System.out.println("Singature:" + new BASE64Encoder().encode(signatureBytes));
  182. signature.initVerify(AliceTrueKeyPare.getPublic());
  183. signature.update(data);
  184. System.out.println(signature.verify(signatureBytes));
  185. System.out.println("all good");
  186. }catch (Exception e){
  187. System.out.println("rip :( "+e);
  188. }
  189.  
  190. String outFile = "testfile";
  191. FileOutputStream out = new FileOutputStream(outFile + ".key");
  192. out.write(AliceTrueKeyPare.getPrivate().getEncoded());
  193. out.close();
  194.  
  195. out = new FileOutputStream(outFile + ".pub");
  196. out.write(AliceTrueKeyPare.getPublic().getEncoded());
  197. out.close();
  198.  
  199.  
  200. Path path = Paths.get("testfile.pub");
  201. byte[] bytes = Files.readAllBytes(path);
  202.  
  203. /* Generate public key. */
  204. X509EncodedKeySpec ks = new X509EncodedKeySpec(bytes);
  205. KeyFactory kf = KeyFactory.getInstance("RSA");
  206. PublicKey pub = kf.generatePublic(ks);
  207.  
  208. path=Paths.get("testfile.key");
  209. bytes = Files.readAllBytes(path);
  210. PKCS8EncodedKeySpec ksp = new PKCS8EncodedKeySpec(bytes);
  211. KeyFactory kfp = KeyFactory.getInstance("RSA");
  212. PrivateKey pvt = kfp.generatePrivate(ksp);
  213.  
  214.  
  215. System.out.println(toHexString(pub.getEncoded()).equals(toHexString(AliceTrueKeyPare.getPublic().getEncoded())));
  216. System.out.println(toHexString(pvt.getEncoded()).equals(toHexString(AliceTrueKeyPare.getPrivate().getEncoded())));
  217. }
  218.  
  219. /*
  220. * Converts a byte to hex digit and writes to the supplied buffer
  221. */
  222. private static void byte2hex(byte b, StringBuffer buf) {
  223. char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
  224. '9', 'A', 'B', 'C', 'D', 'E', 'F' };
  225. int high = ((b & 0xf0) >> 4);
  226. int low = (b & 0x0f);
  227. buf.append(hexChars[high]);
  228. buf.append(hexChars[low]);
  229. }
  230.  
  231. /*
  232. * Converts a byte array to hex string
  233. */
  234. private static String toHexString(byte[] block) {
  235. StringBuffer buf = new StringBuffer();
  236. int len = block.length;
  237. for (int i = 0; i < len; i++) {
  238. byte2hex(block[i], buf);
  239. if (i < len-1) {
  240. buf.append(":");
  241. }
  242. }
  243. return buf.toString();
  244. }
  245. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement