【问题标题】:When encoding the password, always return null value对密码进行编码时,始终返回空值
【发布时间】:2022-01-14 00:33:42
【问题描述】:

我想使用加密密钥对我的密码进行编码。但是在打印编码密码时,我得到了一个空值。我在下面附上了我的代码:

 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);
        }
    }

【问题讨论】:

  • 您的 encrypt 方法在发生异常时返回 null,因此很可能发生的情况是:异常。如果发生异常,您会写出“错误”,这很有帮助,因此如果您在输出中看到它,这将表明您确实有异常。然后下一步是找出异常是什么。为此,您可以在 catch 块中写 exception.printStackTrace();
  • java.security.InvalidKeyException: Invalid AES key length: 14 bytes

标签: java password-encryption


【解决方案1】:

AES 仅支持 16、24 或 32 字节的密钥大小。您的密钥长度为 14,在您的密钥中再添加 2 位数字即可。

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

【讨论】:

    猜你喜欢
    • 2016-07-15
    • 1970-01-01
    • 2016-12-17
    • 2015-12-04
    • 1970-01-01
    • 2017-07-08
    • 1970-01-01
    • 2015-03-21
    • 2018-02-08
    相关资源
    最近更新 更多