Tuesday, October 14, 2014

Encrypt / Decrypt



Encrypt / Decrypt

import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.*;
import javax.swing.JOptionPane;

public class Main extends javax.swing.JFrame {

    byte[] input;
    byte[] keyBytes = "12345678".getBytes(); // our own key
    byte[] ivBytes = "input123".getBytes();

    SecretKeySpec key = new SecretKeySpec(keyBytes, "DES");
    IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
    Cipher cipher;
    byte[] chiperText;
    int ctLenght;

    /**
     * Creates new form Main
     */
    public Main() {
        initComponents();
    }


private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{       
if (jRadioButton1.isSelected()) {
 try {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
//type of security

     input = txtTest.getText().getBytes();
     SecretKeySpec key = new SecretKeySpec(keyBytes, "DES");
     IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);

     cipher = Cipher.getInstance("DES/CTR/NoPadding", "BC");
//CTR of encryption      
     cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
     chiperText = new byte[cipher.getOutputSize(input.length)];
     ctLenght = cipher.update(input, 0, input.length, chiperText, 0);

     ctLenght += cipher.doFinal(chiperText, ctLenght);
     jLabel2.setText(new String(chiperText));
                               
     } catch (Exception e) {
                JOptionPane.showMessageDialog(null, e);
}
 }
 if (jRadioButton2.isSelected()) {
    try {
 
  cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
  byte[] plainText = new byte[cipher.getOutputSize(ctLenght)];
  int ptLength = cipher.update(chiperText, 0, ctLenght, plainText, 0);

  ptLength += cipher.doFinal(plainText, ptLength);
  jLabel2.setText(new String(plainText));
 
   } catch (Exception e) {
          JOptionPane.showMessageDialog(null, e);
   }
 }
 }





Lins






No comments:

Post a Comment