Home > Software design >  When encoding the password, always return null value
When encoding the password, always return null value

Time:12-09

I want to encode my password using an encryption key. but I got a null value, when printing the encoded password. I have attached my code below:

 public class FirstJava {
    
        private static final Long ENCRYPTION_KEY = 29190210908917L;     
                
        public static String encrypt(String strToEncrypt, byte[] key) {
            if (strToEncrypt == null)
                return strToEncrypt;
            try {
                Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
                final SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
                cipher.init(Cipher.ENCRYPT_MODE, secretKey);
                return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes()));
            } catch (Exception exception) {
                System.out.println("ERROR");
            }
            return null;
        }

    
        public static void main(String[] args) {
            String password = "12345678";
            byte[] arr = String.valueOf(ENCRYPTION_KEY).getBytes();
            String passwordEnc = encrypt(password,arr);
            System.out.println("passwordEnc============= " passwordEnc);
        }
    }

CodePudding user response:

AES only supports key sizes of 16, 24 or 32 bytes. Your key length is 14, add 2 more digits to your key and it will work.

private static final Long ENCRYPTION_KEY = 2919021090891712L; //16 bytes
  • Related