我正在使用 SpongyCastle 来支持转换AES/CBC/ISO7816-4Padding。我在 Android 项目的build.gradle文件中包含了以下依赖项:
compile "com.madgag.spongycastle:core:1.58.0.0"
compile "com.madgag.spongycastle:prov:1.58.0.0"
compile 'com.madgag.spongycastle:bcpkix-jdk15on:1.58.0.0'
我在 Android 手机上执行加密操作没有任何问题,但我需要通过以下单元测试(它只是一个简单的类,我提取了我必须加密和解密的实用程序类的主要功能数据所以请忽略硬编码的密钥和IV)
import static junit.framework.TestCase.assertEquals;
import java.security.GeneralSecurityException;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.junit.Test;
import org.spongycastle.jce.provider.BouncyCastleProvider;
public class SpongyTests {
static {
Security.insertProviderAt(new BouncyCastleProvider(), 1);
}
final static byte[] KEY = {
0x2b, 0x7e, 0x15, 0x16, 0x28, (byte) 0xae, (byte) 0xd2, (byte) 0xa6,
(byte) 0xab, (byte) 0xf7, 0x15, (byte) 0x88, 0x09, (byte) 0xcf, 0x4f, 0x3c
};
final static byte[] IV = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
@Test
public void testCryptoOperations() throws GeneralSecurityException {
String plainData = "This is the confidential information";
byte[] encryptedData = aesEncrypt(KEY, IV, plainData.getBytes());
byte[] decryptedData = aesDecrypt(KEY, IV, encryptedData);
assertEquals(plainData, new String(decryptedData));
}
public static byte[] aesEncrypt(byte[] key, byte[] iv, byte[] data) throws
GeneralSecurityException {
return symmetricCryptoOperation(Cipher.ENCRYPT_MODE, key, iv, data);
}
public static byte[] aesDecrypt(byte[] key, byte[] iv, byte[] data) throws GeneralSecurityException {
return symmetricCryptoOperation(Cipher.DECRYPT_MODE, key, iv, data);
}
private static byte[] symmetricCryptoOperation(int mode, byte[] key, byte[] iv, byte[] data) throws GeneralSecurityException {
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/ISO7816-4Padding");
cipher.init(mode, keySpec, new IvParameterSpec(iv));
return cipher.doFinal(data);
}
}
当我运行上述单元测试时,我收到以下异常:
java.security.NoSuchAlgorithmException: Cannot find any provider supporting AES/CBC/ISO7816-4Padding
at javax.crypto.Cipher.getInstance(Cipher.java:540)
at com.yoti.mobile.android.tags.common.SpongyTests.symmetricCryptoOperation(SpongyTests.java:49)
at com.yoti.mobile.android.tags.common.SpongyTests.aesEncrypt(SpongyTests.java:40)
at com.yoti.mobile.android.tags.common.SpongyTests.testCryptoOperations(SpongyTests.java:32)
如您所见,我将 BouncyCastleProvider 添加到第一个位置,但它不起作用。关于如何通过此测试的任何想法?:)