我有一个创建私钥和公钥的项目。我想用ecdsa对它们进行加密,因此我将ecgenparameterspec与'secp256k1'参数一起使用,但这会产生错误。如果我用“secp256r1”更改它,就没有问题。下面是生成密钥的代码:
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
ECGenParameterSpec ecSpec = newECGenParameterSpec("secp256k1");
keyGen.initialize(ecSpec);
KeyPair kp = keyGen.generateKeyPair();
PublicKey pub = kp.getPublic();
PrivateKey pvt = kp.getPrivate();
ECPrivateKey epvt = (ECPrivateKey)pvt;
String sepvt = adjustTo64(epvt.getS().toString(16));
System.out.println("s[" + sepvt.length() + "]: " + sepvt);
ECPublicKey epub = (ECPublicKey)pub;
ECPoint pt = epub.getW();
String sx = adjustTo64(pt.getAffineX().toString(16));
String sy = adjustTo64(pt.getAffineY().toString(16));
String bcPub = sx + sy;
System.out.println("bcPub: " + bcPub);
return bcPub;
调整64位
static private String adjustTo64(String s) {
switch(s.length()) {
case 62: return "00" + s;
case 63: return "0" + s;
case 64: return s;
default:
throw new IllegalArgumentException("not a valid key: " +s);
}
}
当我使用secp256k1时,会出现以下错误:
05-01 12:20:46.066 17297-17297/com.sikke.app W/System.err: java.security.InvalidAlgorithmParameterException: unknown curve name: secp256k1
at com.android.org.conscrypt.OpenSSLECKeyPairGenerator.initialize(OpenSSLECKeyPairGenerator.java:113)
at java.security.KeyPairGenerator.initialize(KeyPairGenerator.java:439)
at com.sikke.app.AppHelper.getEcdsa(AppHelper.java:125)
at com.sikke.app.activities.AccountActivity.onCreate(AccountActivity.java:59)
at android.app.Activity.performCreate(Activity.java:6975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)05-01 12:20:46.067 17297-17297/com.sikke.app W/System.err: at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
最佳答案
经过长时间的搜索,我找到了我的项目的解决方案。您应该在项目中添加此代码以更改安全提供程序。
Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider(), 1);
要添加此代码,您应该使用此库:
prov-1.58.0.0