我正在尝试使用bouncyCastle创建KeyAgreement。它需要EC,因为我正在使用javacards。
不幸的是,当我使用Security.addProvider(new BouncyCastleProvider());
时,它会出错:
Multiple markers at this line
- Syntax error, insert ")" to complete MethodDeclaration
- Syntax error, insert "SimpleName" to complete
QualifiedName
- Syntax error, insert "Identifier (" to complete
MethodHeaderName
- Syntax error on token ".", @ expected after this token
如果我退出该行,则会出错:
Exception in thread "main" java.security.NoSuchProviderException: no such provider: BC
at sun.security.jca.GetInstance.getService(Unknown Source)
at javax.crypto.JceSecurity.getInstance(JceSecurity.java:97)
at javax.crypto.KeyAgreement.getInstance(KeyAgreement.java:230)
at pract_LCP.keyAgreement.<init>(keyAgreement.java:30)
at pract_LCP.main.main(main.java:12)
所以我必须强制使用bouncyCastle。 我的代码:
package pract_LCP;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import org.bouncycastle.*;
import javax.crypto.*;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class keyAgreement {
Security.addProvider(new BouncyCastleProvider());
//Security.addProvider(new BouncyCastleProvider());
private String StringPrivatekey="23dc5cf316583c2e60e36c405b10d03541f4a76f6da2852d";
private String StringPublicKey="47595243a6737a00fe5d911c1a3305be5c108bf4f68b01945c40358143f28077fad4a8a51f190b6d8bb8b580c88011335";
private PrivateKey convertPrivateKey(String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException{
byte[] privateKeyBytes=privateKey.getBytes();
KeyFactory kf = KeyFactory.getInstance("EC"); // or "EC" or whatever
PrivateKey converted = kf.generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes));
return converted;
}
private PublicKey convertPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException{
byte[] publicKeyBytes=publicKey.getBytes();
KeyFactory kf = KeyFactory.getInstance("EC"); // or "EC" or whatever
PublicKey converted = kf.generatePublic(new PKCS8EncodedKeySpec(publicKeyBytes));
return converted;
}
public keyAgreement() throws InvalidKeyException, IllegalStateException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException{
KeyAgreement aKeyAgree = KeyAgreement.getInstance("ECDH", "BC");
aKeyAgree.init(convertPrivateKey(StringPrivatekey));
aKeyAgree.doPhase(convertPublicKey(StringPublicKey), true);
byte[] aSecret = aKeyAgree.generateSecret();
String str = new String(aSecret, StandardCharsets.UTF_8);
System.out.println("keyagr"+str);
}
}