Questo sito utilizza cookies solo per scopi di autenticazione sul sito e nient'altro. Nessuna informazione personale viene tracciata. Leggi l'informativa sui cookies.
Username: Password: oppure
RSACoder - RSA.java

RSA.java

Caricato da: Netarrow
Scarica il programma completo

  1. import java.security.*;
  2. import java.security.spec.*;
  3.  
  4. import javax.crypto.*;
  5. import javax.crypto.spec.*;
  6.  
  7. import java.io.*;
  8.  
  9. import javax.swing.*;
  10.  
  11. /**
  12.  * Classe per usare RSA<br>
  13.  *
  14.  * @author netarrow
  15.  * @version 1.1.00 beta
  16.  * @since 1.0.02
  17.  */
  18. public class RSA {
  19.         protected PublicKey puk;
  20.         protected PrivateKey prk;
  21.         protected Cipher c;
  22.         protected FileInputStream keyReader;
  23.         protected DataOutputStream out;
  24.         protected UsersPublicKeys upk;
  25.         protected ByteArrayOutputStream baos;
  26.         protected Blowfish blowfish;
  27.         protected IvParameterSpec spec;
  28.         protected KeyFactory kf;
  29.         protected SecureRandom random;
  30.         protected FileInputStream sourceReader;
  31.         protected FileInputStream storeReader;
  32.         protected DataInputStream dis;
  33.         protected Runnable cod;
  34.         protected Runnable decod;
  35.         protected String user;
  36.         protected File sorgente;
  37.  
  38.         /**
  39.          * Costruttore
  40.          */
  41.         public RSA() {
  42.                 upk = new UsersPublicKeys();
  43.                 blowfish = new Blowfish();
  44.                
  45.                 cod = new Runnable() {
  46.                         public void run() {
  47.                                 try {
  48.                                 keyReader = new FileInputStream(upk.getPublicFile(user));
  49.                                 sourceReader = new FileInputStream(sorgente);
  50.                                 blowfish.createKey();
  51.                                 out = new DataOutputStream(new FileOutputStream(sorgente.toString()+ ".cod"));
  52.                                 int i = 0;
  53.                                 baos = new ByteArrayOutputStream();
  54.                                         while((i = keyReader.read()) > -1) {
  55.                                                 baos.write(i);
  56.                                         }
  57.                                         baos.close();
  58.                                 X509EncodedKeySpec ks = new X509EncodedKeySpec(baos.toByteArray());
  59.                                 kf = KeyFactory.getInstance("RSA");
  60.                                 puk = kf.generatePublic(ks);
  61.                                 c = Cipher.getInstance("RSA/ECB/PKCS1Padding");
  62.                                 c.init(Cipher.ENCRYPT_MODE, puk);
  63.                                 byte[] encoded = c.doFinal(blowfish.getKey());
  64.                                 out.writeInt(encoded.length);
  65.                                 out.write(encoded);
  66.                                 random = new SecureRandom();
  67.                                 byte[] iv = new byte[8];
  68.                                 random.nextBytes(iv);
  69.                                 out.write(iv);
  70.                                 spec = new IvParameterSpec(iv);
  71.                                 blowfish.codifica(spec, out, sourceReader);
  72.                                 } catch(Exception e) {
  73.                                         e.printStackTrace();
  74.                                 }
  75.                         }
  76.                 };
  77.                
  78.                 decod = new Runnable() {
  79.                         public void run() {
  80.                                 try {
  81.                                         if(!new File("MyKeys").exists()) {
  82.                                                 JOptionPane.showMessageDialog(null, "Non trovo la tua chiave privata, genera una coppia di chiavi RSA prima", "Attenzione", JOptionPane.WARNING_MESSAGE);
  83.                                                 return;
  84.                                         }
  85.                                         keyReader = new FileInputStream("./MyKeys/MyPrivate");
  86.                                         sourceReader = new FileInputStream(sorgente);
  87.                                         storeReader = new FileInputStream("./MyKeys/MyKeyStore");
  88.                                         dis = new DataInputStream(sourceReader);
  89.                                         int i = 0;
  90.                                         baos = new ByteArrayOutputStream();
  91.                                         while((i = storeReader.read()) != -1) {
  92.                                                 baos.write(i);
  93.                                         }
  94.                                         baos.close();
  95.                                         checkPass(baos.toByteArray());
  96.                                         baos.reset();
  97.                                         i = 0;
  98.                                                 while((i = keyReader.read()) != -1) {
  99.                                                         baos.write(i);
  100.                                                 }
  101.                                                 baos.close();
  102.                                         PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(baos.toByteArray());
  103.                                         kf = KeyFactory.getInstance("RSA");
  104.                                         prk = kf.generatePrivate(ks);
  105.                                         c = Cipher.getInstance("RSA/ECB/PKCS1Padding");
  106.                                         c.init(Cipher.DECRYPT_MODE, prk);
  107.                                         byte[] keyEncrypt = new byte[dis.readInt()];
  108.                                         dis.readFully(keyEncrypt);
  109.                                         byte[] keyPlain = c.doFinal(keyEncrypt);
  110.                                         SecretKey blowfishKey = new SecretKeySpec(keyPlain, "Blowfish");
  111.                                         byte[] iv = new byte[8];
  112.                                         dis.read(iv);
  113.                                         spec = new IvParameterSpec(iv);
  114.                                         blowfish.decodifica(blowfishKey, spec, sorgente, dis);
  115.                                 } catch(Exception e) {
  116.                                         e.printStackTrace();
  117.                                 }
  118.                         }
  119.                 };
  120.         }
  121.        
  122.         /**
  123.          * Verifica la password<br>
  124.          *
  125.          * @param pass Password in byte su cui verificare
  126.          * @return Vero o falso se la password è corretta o meno
  127.          * @throws Exception
  128.          */
  129.         private boolean checkPass(byte[] pass) throws Exception {
  130.                 String password;
  131.                 MessageDigest md = MessageDigest.getInstance("MD5");
  132.                         password = JOptionPane.showInputDialog(null, "Inserire password per chiave privata");
  133.                         if(password == null) return false;
  134.                 return md.digest(password.getBytes()).equals(pass);
  135.         }
  136.        
  137.         /**
  138.          * Crea una coppia di chiavi RSA<br>
  139.          *
  140.          * @throws NoSuchAlgorithmException
  141.          */
  142.         public void createKeys() throws NoSuchAlgorithmException {
  143.                 KeyPairGenerator kg = KeyPairGenerator.getInstance("RSA");
  144.                 kg.initialize(1024);
  145.                 KeyPair kp = kg.generateKeyPair();
  146.                 puk = kp.getPublic();
  147.                 prk = kp.getPrivate();
  148.         }
  149.        
  150.         /**
  151.          * Metodo per ottenere la chiave pubblica<br>
  152.          *
  153.          * @return La chiave pubblica
  154.          */
  155.         public PublicKey getPublic() {
  156.                 return puk;
  157.         }
  158.        
  159.         /**
  160.          * Metodo per ottenere la chiave privata<br>
  161.          *
  162.          * @return La chiave privata
  163.          */
  164.         public PrivateKey getPrivate() {
  165.                 return prk;
  166.         }
  167.        
  168.         /**
  169.          * Codifica la chiave di sessione blowfish con la chiave pubblica rsa<br>
  170.          * dell'utente destinatario<br>
  171.          *
  172.          * @param user Utente destinatario
  173.          * @param sorgente File da codificare
  174.          * @throws Exception
  175.          * @throws Exception
  176.          */
  177.         public void codifica(String user, File sorgente) {
  178.                 this.user = user;
  179.                 this.sorgente = sorgente;
  180.                 SwingUtilities.invokeLater(cod);
  181.         }
  182.        
  183.         /**
  184.          * Decodifica file: estrai chiave blowfish, decodifica con la chiave privata<br>
  185.          * e col risultato decodifica il file<br>
  186.          *
  187.          * @param sorgente File da decodificare
  188.          * @throws Exception
  189.          */
  190.         public void decodifica(File sorgente) {
  191.                 this.sorgente = sorgente;
  192.                 SwingUtilities.invokeLater(decod);
  193.         }
  194.  
  195. }