【问题标题】:Encoding the passphrase [duplicate]对密码进行编码[重复]
【发布时间】:2016-12-17 04:34:21
【问题描述】:

我正在尝试将 passphase 编码到属性文件中,这样我就不必输入 passphase 来建立 SSH 连接。但我面临以下错误:

javax.crypto.BadPaddingException: Given final block not properly padded
    at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:966)
    at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:824)
    at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:436)
    at javax.crypto.Cipher.doFinal(Cipher.java:2165)
    at com.test.ssh.SSH_Public_Private.deCryptPwd(SSH_Public_Private.java:191)
    at com.test.ssh.SSH_Public_Private.checkHostName(SSH_Public_Private.java:227)
    at com.test.ssh.SSH_Public_Private.checkHostName(SSH_Public_Private.java:223)
    at com.test.ssh.SSH_Public_Private.connectToSSH(SSH_Public_Private.java:64)
    at com.test.ssh.SSH_Public_Private.main(SSH_Public_Private.java:124)

我的代码如下:

  private String checkHostName(String hostUserName) throws IOException, InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
            String deCrypted = null;
            FileInputStream is = new FileInputStream(new File("C:\\test\\SSH\\PrivateKey\\keystore.properties"));
            Properties properties = new Properties();
            properties.load(is);
            ssh_Public_Private = new SSH_Public_Private();
            boolean isHostNameExist = false;
            if (properties.getProperty(hostUserName) == null) {

                OutputStream outputStream = new FileOutputStream(
                        "C:\\test\\SSH\\PrivateKey\\keystore.properties");
                String passPhraseStored = new String(enCryptPwd());
                properties.setProperty(hostUserName,passPhraseStored );
                properties.store(outputStream, null);
                outputStream.close();
                is.close();
                return checkHostName(hostUserName);
            }else{
                System.out.println(properties.getProperty(hostUserName));
                String passPhrase = properties.getProperty(hostUserName);
                 deCrypted = deCryptPwd(passPhrase);            //isHostNameExist = true;
            }
            return deCrypted;

        }

My encryption and decryption piece of code is as follow :

    private static String enCryptPwd() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
        String decrypted = null;
        byte[] encrypted = null;
        try {
            String text = "";
            Scanner sc = new Scanner(System.in);
            System.out.println("Enter your passphrase : " );
            text = sc.next();
            String key = "Bar12345Bar12345"; // 128 bit key
            //String key = "AesSEcREtkeyABCD";
            // Create key and cipher
            Key aesKey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
            System.out.println(aesKey.getFormat());
            Cipher cipher = Cipher.getInstance("AES");
            // encrypt the text
            cipher.init(Cipher.ENCRYPT_MODE, aesKey);
            encrypted = cipher.doFinal(text.getBytes("UTF-8"));
            System.err.println(new String(encrypted));
            System.err.println(encrypted.length);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return new String(encrypted);
    }

    private static  String deCryptPwd(String encrypted) throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
        String originalString = "";
        try {
            String key = "Bar12345Bar12345"; // 128 bit key
            //String key = "AesSEcREtkeyABCD";
            // Create key and cipher
            Key aesKey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
            Cipher cipher = Cipher.getInstance("AES");
            // decrypt the text
            cipher.init(Cipher.DECRYPT_MODE, aesKey);
            byte[] encryptBytes = new byte[encrypted.length()];
            encryptBytes = encrypted.getBytes();
            byte[] decrypted = cipher.doFinal(encryptBytes);
            originalString = new String(decrypted, "UTF-8");
            System.out.println(originalString);
            System.err.println(decrypted);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return originalString;
      }

我一直在尝试阅读并尝试了许多其他方法,包括不包含填充算法。我的代码将输出写入属性文件:

abced=Y\u201Eh\uFFFD\u00EC-:\u00F9\u00F8mC\u0160\u0002\u00F3#\u00DE

我的控制台输出是:

输入您的密码: abc!@#

加密后>> Y„h?ì-:ùømCŠó#Þ

16

从属性文件中读取 >> Y„h?ì-:ùømCŠó#Þ

【问题讨论】:

  • 您的编码已关闭。如果您计算“加密后”显示的字符数,您会发现只有 15 个字符,而不是预期的 16 个。
  • 请注意,加密是基于字节而不是基于字符的。加密数据几乎总是不能作为文本打印,它显示为一个 8 位随机字节数组。为了显示问题,对加密数据进行十六进制编码。
  • 如果您对“passphase”进行加密,您将如何保护该加密密钥?
  • 一般建议:始终使用完全限定的密码字符串。 Cipher.getInstance("AES"); 可能会产生不同的密码,具体取决于默认的安全提供程序。它最有可能导致"AES/ECB/PKCS5Padding",但并非必须如此。如果它发生变化,您将失去不同 JVM 之间的兼容性。
  • 切勿使用ECB mode。它是确定性的,因此在语义上不安全。您至少应该使用像CBCCTR 这样的随机模式。最好对您的密文进行身份验证,以免像padding oracle attack 这样的攻击是不可能的。这可以通过 GCM 或 EAX 等经过身份验证的模式或encrypt-then-MAC 方案来完成。

标签: java encryption aes


【解决方案1】:

使用 KeyGenerator 生成密钥

KeyGenerator kg = KeyGenerator.getInstance("AES");
kg.init(128, new SecureRandom());
SecretKeySpec aesKey = new SecretKeySpec(kg.generateKey().getEncoded(), "AES");

使用 AES/CBC/PKCS5Padding 获取密码实例。

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")

这应该可行。

【讨论】:

  • 如前所述,它会更干净。我宁愿写 59201e683fec2d3af9f86d43160f323de 代替 Y„h?ì-:ùømCŠó#Þ.
  • @zaph 真的。编辑答案。
  • 现在我收到这样的错误:java.security.InvalidKeyException: Parameters missing at com.sun.crypto.provider.CipherCore.init(CipherCore.java:460) at com.sun.crypto.provider.AESCipher.engineInit(AESCipher.java:307) at javax.crypto.Cipher.implInit(Cipher.java:802) at javax.crypto.Cipher.chooseProvider(Cipher.java:864) at javax.crypto.Cipher.init(Cipher.java:1249) at javax.crypto.Cipher.init(Cipher.java:1186) at
  • @dodger 请使用 KeyGenerator 以避免 InvalidKeyException 错误。更新了答案。
  • 我已经能够使用link 找到我的解决方案。谢谢..
猜你喜欢
  • 2014-02-04
  • 2017-07-08
  • 1970-01-01
  • 2018-02-08
  • 1970-01-01
  • 2016-01-23
  • 2022-01-14
  • 2012-03-12
  • 1970-01-01
相关资源
最近更新 更多