Monday, October 13, 2014

Encrypt AND Decrypt (DES)

Encrypt AND Decrypt



http://www.bouncycastle.org/.../bcprov-ext-jdk15on-151.jar



  • Encrypt button

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
        try {
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); //type of security
            input = type.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);
            encrypt.setText(new String(chiperText));
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
        }
    } 


  • Decrypt button


 private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                        
        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);
            decrypt.setText(new String(plainText));
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
        }
    }  


No comments:

Post a Comment