Java AES encryption and decryption

后端 未结 6 1409
独厮守ぢ
独厮守ぢ 2020-12-07 15:48

I would like to encrypt and decrypt a password using 128 bit AES encryption with 16 byte key. I am getting javax.crypto.BadPaddingException error while decrypt

6条回答
  •  甜味超标
    2020-12-07 16:34

    import javax.crypto.*;    
    import java.security.*;  
    public class Java {
    
    private static SecretKey key = null;         
       private static Cipher cipher = null; 
    
       public static void main(String[] args) throws Exception
       {
    
          Security.addProvider(new com.sun.crypto.provider.SunJCE());
    
          KeyGenerator keyGenerator =
             KeyGenerator.getInstance("DESede");
          keyGenerator.init(168);
          SecretKey secretKey = keyGenerator.generateKey();
          cipher = Cipher.getInstance("DESede");
    
          String clearText = "I am an Employee";
          byte[] clearTextBytes = clearText.getBytes("UTF8");
    
          cipher.init(Cipher.ENCRYPT_MODE, secretKey);
          byte[] cipherBytes = cipher.doFinal(clearTextBytes);
          String cipherText = new String(cipherBytes, "UTF8");
    
          cipher.init(Cipher.DECRYPT_MODE, secretKey);
          byte[] decryptedBytes = cipher.doFinal(cipherBytes);
          String decryptedText = new String(decryptedBytes, "UTF8");
    
          System.out.println("Before encryption: " + clearText);
          System.out.println("After encryption: " + cipherText);
          System.out.println("After decryption: " + decryptedText);
       }
    }
    
    
    // Output
    
    /*
    Before encryption: I am an Employee  
    After encryption: }?ス?スj6?スm?スZyc?ス?ス*?ス?スl#l?スdV  
    After decryption: I am an Employee  
    */
    

提交回复
热议问题