andgau

CifradorDescifrador

Apr 23rd, 2018
2,835
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.07 KB | None | 0 0
  1. package es.sinjava.cifrando;
  2.  
  3. import java.io.File;
  4. import java.io.IOException;
  5. import java.nio.file.Files;
  6. import java.security.GeneralSecurityException;
  7. import java.security.KeyFactory;
  8. import java.security.PrivateKey;
  9. import java.security.PublicKey;
  10. import java.security.spec.KeySpec;
  11. import java.security.spec.PKCS8EncodedKeySpec;
  12. import java.security.spec.X509EncodedKeySpec;
  13.  
  14. import javax.crypto.Cipher;
  15.  
  16. public class CifradorDescifrador {
  17.  
  18.     private static Cipher cipherRsa;
  19.     private static KeyFactory keyFactory;
  20.  
  21.     public static CifradorDescifrador getInstanceRsa() {
  22.         try {
  23.             cipherRsa = Cipher.getInstance("RSA/ECB/PKCS1Padding");
  24.             keyFactory = KeyFactory.getInstance("RSA");
  25.         } catch (GeneralSecurityException e) {
  26.             System.out.println("Error: " + e);
  27.         }
  28.         return new CifradorDescifrador();
  29.     }
  30.  
  31.     public byte[] encript(String publicKeyFile, byte[] textAsByte) throws IOException, GeneralSecurityException {
  32.  
  33.         PublicKey publicKey = loadPublicKey(publicKeyFile);
  34.         cipherRsa.init(Cipher.ENCRYPT_MODE, publicKey);
  35.         byte[] encriptado = cipherRsa.doFinal(textAsByte);
  36.  
  37.         return encriptado;
  38.     }
  39.  
  40.     public byte[] deEncript(String privaKeyFile, byte[] textAsByte) throws IOException, GeneralSecurityException {
  41.         PrivateKey privateKey = loadPrivateKey(privaKeyFile);
  42.         cipherRsa.init(Cipher.DECRYPT_MODE, privateKey);
  43.         byte[] bytesDesencriptados = cipherRsa.doFinal(textAsByte);
  44.  
  45.         return bytesDesencriptados;
  46.     }
  47.  
  48.     private static PublicKey loadPublicKey(String fileName) throws IOException, GeneralSecurityException {
  49.         byte[] content = Files.readAllBytes(new File(fileName).toPath());
  50.         KeySpec keySpec = new X509EncodedKeySpec(content);
  51.         PublicKey keyFromBytes = keyFactory.generatePublic(keySpec);
  52.         return keyFromBytes;
  53.     }
  54.  
  55.     private static PrivateKey loadPrivateKey(String fileName) throws IOException, GeneralSecurityException {
  56.         byte[] content = Files.readAllBytes(new File(fileName).toPath());
  57.         KeySpec keySpec = new PKCS8EncodedKeySpec(content);
  58.         PrivateKey keyFromBytes = keyFactory.generatePrivate(keySpec);
  59.         return keyFromBytes;
  60.     }
  61.  
  62. }
Advertisement
Add Comment
Please, Sign In to add comment