gpt4 book ai didi

java - 使用 Android 实现 Bouncy CaSTLe 密码算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:00:49 36 4
gpt4 key购买 nike

如何使用 Bouncy CaSTLe 提供程序来实现 Serpent 和 Twofish 等算法,因为 Sun 的提供程序根本不实现这些。我知道当多个供应商可以实现相同的算法时,您会从排名最高的供应商那里获得实现,这将是 Sun 供应商。如果出于某种原因你想使用来自特定提供者的实现(可能是因为你知道它更快),你可以在 getInstance() 的双参数版本中指定提供者。就我而言,Sun 供应商根本没有实现我感兴趣的算法。

我试图实现 Serpent:

    public static final String FILE_EXTENSION = ".serpent";
public static final String PROVIDER = "BC"; // Bouncy Castle
public static final String BLOCK_CIPHER = "Serpent";
public static final String TRANSFORMATION = "Serpent/CBC/PKCS7Padding";
public static final String KEY_ALGORITHM = "PBKDF2WithHmacSHA1";
public static final String PRNG_ALGORITHM = "SHA1PRNG";

public static final int BLOCK_SIZE = 128; // bits
public static final int KEY_SIZE = 256; // bits
public static final int ITERATION_COUNT = 1024; // for PBE

/** Performs the encryption of a file. */
public void encrypt(String pathname, char[] password, byte[] salt) {
// Use bouncy castle as our provider
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

// Convert the file into a byte array
byte[] plaintext = fileToBytes(new File(pathname));

// Generate a 256-bit key
SecretKey key = generateSecretKey(password,salt);

// Generate a 128-bit secure random IV
byte[] iv = generateIV();

// Setup the cipher and perform the encryption
Cipher cipher = null;
byte[] ciphertext = null;
try {
cipher = Cipher.getInstance(TRANSFORMATION, PROVIDER);
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
ciphertext = cipher.doFinal(plaintext);
} catch (Exception e) {
e.printStackTrace();
}

// Append the IV to the ciphertext
byte[] temp = new byte[iv.length+ciphertext.length];
System.arraycopy(iv, 0, temp, 0, iv.length);
System.arraycopy(ciphertext, 0, temp, iv.length, ciphertext.length);
ciphertext = temp;

// Store the encrypted file in the same directory we found it
if (Environment.getExternalStorageDirectory().canWrite()) {
bytesToFile(ciphertext, pathname+FILE_EXTENSION);
File file = new File(pathname);
file.delete();
}
}

然而这会抛出一个

java.security.NoSuchAlgorithmException: Serpent/CBC/PKCS7Padding

在我打电话的那条线上

cipher = Cipher.getInstance(TRANSFORMATION, PROVIDER);

运行

$ adb shell
# logcat

我得到了很多

not resolving ambiguous class
not verifying
multiple definitions

正在输出错误。知道是什么原因导致这种情况发生以及我该如何解决这个问题?

最佳答案

你可能想要 Spongy Castle - 我专门针对 Android 对 Bouncy CaSTLe 进行了重新打包。

Spongy CaSTLe 完全替代了 Android 附带的 Bouncy CaSTLe 加密库的残缺版本。有几个小的变化可以让它在 Android 上运行:

  • 所有包名称都已从 org.bouncycaSTLe.* 移至 org.spongycaSTLe.* - 因此没有类加载器冲突
  • Java 安全 API 提供程序名称现在是 SC 而不是 BC

“海绵城堡救了我的命。” - 来自一位快乐用户的反馈:)

关于java - 使用 Android 实现 Bouncy CaSTLe 密码算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6037897/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com