java - 获取不同的加密 key 会导致 Android 使用相同的密码

标签 java android

每次我使用相同的密码运行设置方法时,每次都会得到不同的 key 结果。我正在使用 key 结果来检查解密密码是否正确,以防止不必要的解密。

我在 java 中运行了以下代码,我没有遇到任何问题,但在 Android 中,它生成不同的 key 时出现问题。有人可以告诉我问题是什么以及如何解决这个问题。我想要 Android 和 Java 之间的通用软件。

当我在 android 中运行程序时,我得到 key org.bouncycaSTLe.jce.provider.JCEPBEKEY@12345678

当我在 java 中运行程序时,我得到了 key com.sun.crypto.Provider.PBEKey@12345678

private static byte[] bytes;
  Cipher ecipher;
  Cipher dcipher;

  // 8-byte Salt
  byte[] salt = {
      (byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32,
      (byte)0x56, (byte)0x35, (byte)0xE3, (byte)0x03
  };

  // Iteration count
  int iterationCount = 19;

  public String setup(String passPhrase) 
  {
      String output = null;
      try {
          // Create the key
          KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
          SecretKey key = SecretKeyFactory.getInstance(
              "PBEWithMD5AndDES").generateSecret(keySpec);

          ecipher = Cipher.getInstance(key.getAlgorithm());
          dcipher = Cipher.getInstance(key.getAlgorithm());

          // Prepare the parameter to the ciphers
          AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);

          // Create the ciphers
          ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
          dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);

          // print key
          System.out.println("key  = " + key);
          System.out.println("paramSpec  = " + paramSpec);


          output = key.toString();
      //    showToast("setting up key " + output);
      //    showToast("key size " + output.length());
          System.out.println("key Size " + output.length());

      } catch (java.security.InvalidAlgorithmParameterException e) {
      } catch (java.security.spec.InvalidKeySpecException e) {
      } catch (javax.crypto.NoSuchPaddingException e) {
      } catch (java.security.NoSuchAlgorithmException e) {
      } catch (java.security.InvalidKeyException e) {
      }

      return output;
  }

最佳答案

改变行:

SecretKey key = SecretKeyFactory.getInstance(
              "PBEWithMD5AndDES").generateSecret(keySpec);

SecretKey key = SecretKeyFactory.getInstance(
              "PBEWithMD5AndDES","BC").generateSecret(keySpec);

像这样你特别要求加密提供商(充气城堡) 注意:您还必须将 bouncycaSTLe 提供程序添加到您的 VM。

关于java - 获取不同的加密 key 会导致 Android 使用相同的密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12852170/

相关文章:

java - 如何提高 Java ArrayList 的性能

android如何通过路径在 Canvas 上绘制三角形

java - 在ANTLR4中处理自定义异常

java - 执行 mvn archetype :generate with URL for 时未定义原型(prototype)

android - 检查所有 EditText 是否为空

java - Google App Engine 整数数组参数

Android tesseract OCR 改进结果

java - SQlite 数据库不将 double 值存储为字符串

java - 子实体 hibernate

java - 从 Android 上的 Web 服务缓存 JSON - 模式?