下面列出了怎么用java.security.spec.ECParameterSpec的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void initialize(AlgorithmParameterSpec params, SecureRandom random)
throws InvalidAlgorithmParameterException {
if (params instanceof ECParameterSpec) {
this.params = ECUtil.getECParameterSpec(null,
(ECParameterSpec)params);
if (this.params == null) {
throw new InvalidAlgorithmParameterException(
"Unsupported curve: " + params);
}
} else if (params instanceof ECGenParameterSpec) {
String name = ((ECGenParameterSpec)params).getName();
this.params = ECUtil.getECParameterSpec(null, name);
if (this.params == null) {
throw new InvalidAlgorithmParameterException(
"Unknown curve name: " + name);
}
} else {
throw new InvalidAlgorithmParameterException(
"ECParameterSpec or ECGenParameterSpec required for EC");
}
this.keySize =
((ECParameterSpec)this.params).getCurve().getField().getFieldSize();
this.random = random;
}
static ECDHECredentials valueOf(NamedGroup namedGroup,
byte[] encodedPoint) throws IOException, GeneralSecurityException {
if (namedGroup.type != NamedGroupType.NAMED_GROUP_ECDHE) {
throw new RuntimeException(
"Credentials decoding: Not ECDHE named group");
}
if (encodedPoint == null || encodedPoint.length == 0) {
return null;
}
ECParameterSpec parameters =
JsseJce.getECParameterSpec(namedGroup.oid);
if (parameters == null) {
return null;
}
ECPoint point = JsseJce.decodePoint(
encodedPoint, parameters.getCurve());
KeyFactory factory = JsseJce.getKeyFactory("EC");
ECPublicKey publicKey = (ECPublicKey)factory.generatePublic(
new ECPublicKeySpec(point, parameters));
return new ECDHECredentials(publicKey, namedGroup);
}
public PublicKey getPublicKey()
throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException {
ECPrivateKey privateKey = (ECPrivateKey) getPrivateKey();
ECParameterSpec params = privateKey.getParams();
org.bouncycastle.jce.spec.ECParameterSpec bcSpec =
org.bouncycastle.jcajce.provider.asymmetric.util.EC5Util.convertSpec(params, false);
org.bouncycastle.math.ec.ECPoint q = bcSpec.getG().multiply(privateKey.getS());
org.bouncycastle.math.ec.ECPoint bcW = bcSpec.getCurve().decodePoint(q.getEncoded(false));
ECPoint w =
new ECPoint(
bcW.getAffineXCoord().toBigInteger(), bcW.getAffineYCoord().toBigInteger());
ECPublicKeySpec keySpec = new ECPublicKeySpec(w, tryFindNamedCurveSpec(params));
return (PublicKey)
KeyFactory.getInstance("EC", BouncyCastleProvider.PROVIDER_NAME)
.generatePublic(keySpec);
}
/**
*
*/
private void export() throws NoSuchAlgorithmException, IOException {
ProviderECLibrary lib = cfg.selected;
KeyPairGeneratorIdent ident = null;
String algo = cli.getOptionValue("export.type", "EC");
for (KeyPairGeneratorIdent kpIdent : lib.getKPGs()) {
if (kpIdent.contains(algo)) {
ident = kpIdent;
break;
}
}
if (ident == null) {
throw new NoSuchAlgorithmException(algo);
}
KeyPairGenerator kpg = ident.getInstance(lib.getProvider());
if (cli.hasOption("export.bits")) {
int bits = Integer.parseInt(cli.getOptionValue("export.bits"));
kpg.initialize(bits);
}
KeyPair kp = kpg.genKeyPair();
ECPrivateKey privateKey = (ECPrivateKey) kp.getPrivate();
ECParameterSpec params = privateKey.getParams();
System.out.println(params);
EC_Curve curve = EC_Curve.fromSpec(params);
curve.writeCSV(System.out);
}
private KeyPair generateKeyPairNative(SecureRandom random)
throws Exception {
ECParameterSpec ecParams = (ECParameterSpec) params;
byte[] encodedParams = ECUtil.encodeECParameterSpec(null, ecParams);
// seed is twice the key size (in bytes) plus 1
byte[] seed = new byte[(((keySize + 7) >> 3) + 1) * 2];
random.nextBytes(seed);
Object[] keyBytes = generateECKeyPair(keySize, encodedParams, seed);
// The 'params' object supplied above is equivalent to the native
// one so there is no need to fetch it.
// keyBytes[0] is the encoding of the native private key
BigInteger s = new BigInteger(1, (byte[]) keyBytes[0]);
PrivateKey privateKey = new ECPrivateKeyImpl(s, ecParams);
// keyBytes[1] is the encoding of the native public key
byte[] pubKey = (byte[]) keyBytes[1];
ECPoint w = ECUtil.decodePoint(pubKey, ecParams.getCurve());
PublicKey publicKey = new ECPublicKeyImpl(w, ecParams);
return new KeyPair(publicKey, privateKey);
}
public BCDSTU4145PublicKey(
org.ripple.bouncycastle.jce.spec.ECPublicKeySpec spec)
{
this.q = spec.getQ();
if (spec.getParams() != null) // can be null if implictlyCa
{
ECCurve curve = spec.getParams().getCurve();
EllipticCurve ellipticCurve = EC5Util.convertCurve(curve, spec.getParams().getSeed());
this.ecSpec = EC5Util.convertSpec(ellipticCurve, spec.getParams());
}
else
{
if (q.getCurve() == null)
{
org.ripple.bouncycastle.jce.spec.ECParameterSpec s = BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa();
q = s.getCurve().createPoint(q.getAffineXCoord().toBigInteger(), q.getAffineYCoord().toBigInteger());
}
this.ecSpec = null;
}
}
public PublicKey getPublicKey()
throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException,
InvalidKeySpecException, NoSuchProviderException {
ECPrivateKey privateKey = (ECPrivateKey) getPrivateKey();
ECParameterSpec params = privateKey.getParams();
org.bouncycastle.jce.spec.ECParameterSpec bcSpec =
org.bouncycastle.jcajce.provider.asymmetric.util.EC5Util.convertSpec(params, false);
org.bouncycastle.math.ec.ECPoint q = bcSpec.getG().multiply(privateKey.getS());
org.bouncycastle.math.ec.ECPoint bcW = bcSpec.getCurve().decodePoint(q.getEncoded(false));
ECPoint w =
new ECPoint(
bcW.getAffineXCoord().toBigInteger(), bcW.getAffineYCoord().toBigInteger());
ECPublicKeySpec keySpec = new ECPublicKeySpec(w, tryFindNamedCurveSpec(params));
return (PublicKey)
KeyFactory.getInstance("EC", BouncyCastleProvider.PROVIDER_NAME)
.generatePublic(keySpec);
}
private static String getCurveOid(ECParameterSpec params) {
// Check that the params represent one of the supported
// curves. If there is a match, return the object identifier
// of the curve.
Curve match;
if (matchCurve(params, SECP256R1)) {
match = SECP256R1;
} else if (matchCurve(params, SECP384R1)) {
match = SECP384R1;
} else if (matchCurve(params, SECP521R1)) {
match = SECP521R1;
} else {
return null;
}
return match.getObjectId();
}
@Override
public void initialize(AlgorithmParameterSpec params, SecureRandom random)
throws InvalidAlgorithmParameterException {
if (params instanceof ECParameterSpec) {
this.params = ECUtil.getECParameterSpec(null,
(ECParameterSpec)params);
if (this.params == null) {
throw new InvalidAlgorithmParameterException(
"Unsupported curve: " + params);
}
} else if (params instanceof ECGenParameterSpec) {
String name = ((ECGenParameterSpec)params).getName();
this.params = ECUtil.getECParameterSpec(null, name);
if (this.params == null) {
throw new InvalidAlgorithmParameterException(
"Unknown curve name: " + name);
}
} else {
throw new InvalidAlgorithmParameterException(
"ECParameterSpec or ECGenParameterSpec required for EC");
}
this.keySize =
((ECParameterSpec)this.params).getCurve().getField().getFieldSize();
this.random = random;
}
public static ECParameterSpec convertSpec(
EllipticCurve ellipticCurve,
org.ripple.bouncycastle.jce.spec.ECParameterSpec spec)
{
if (spec instanceof ECNamedCurveParameterSpec)
{
return new ECNamedCurveSpec(
((ECNamedCurveParameterSpec)spec).getName(),
ellipticCurve,
new ECPoint(
spec.getG().getAffineXCoord().toBigInteger(),
spec.getG().getAffineYCoord().toBigInteger()),
spec.getN(),
spec.getH());
}
else
{
return new ECParameterSpec(
ellipticCurve,
new ECPoint(
spec.getG().getAffineXCoord().toBigInteger(),
spec.getG().getAffineYCoord().toBigInteger()),
spec.getN(),
spec.getH().intValue());
}
}
private void testSerialization(CryptoAlgorithm algorithm, String curveName, int[] x, int[] y, int[] expected) throws Exception {
byte[] xBytes = TestUtils.unsignedBytesToSignedBytes(x);
byte[] yBytes = TestUtils.unsignedBytesToSignedBytes(y);
final AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC");
parameters.init(new ECGenParameterSpec(curveName));
ECParameterSpec ecParameterSpec = parameters.getParameterSpec(ECParameterSpec.class);
PublicKey publicKey = KeyFactory.getInstance("EC").generatePublic(
new ECPublicKeySpec(new ECPoint(new BigInteger(1, xBytes), new BigInteger(1, yBytes)), ecParameterSpec));
int[] result = TestUtils.signedBytesToUnsignedBytes(Utils.decodeBase64String(TrailingSignatureAlgorithm
.forCryptoAlgorithm(algorithm)
.serializePublicKey(publicKey)));
assertArrayEquals(expected, result);
}
public JCEECPublicKey(
String algorithm,
ECPublicKeyParameters params,
ECParameterSpec spec)
{
ECDomainParameters dp = params.getParameters();
this.algorithm = algorithm;
this.q = params.getQ();
if (spec == null)
{
EllipticCurve ellipticCurve = EC5Util.convertCurve(dp.getCurve(), dp.getSeed());
this.ecSpec = createSpec(ellipticCurve, dp);
}
else
{
this.ecSpec = spec;
}
}
@Override
public ECParameterSpec getParams() {
try {
AlgorithmParameters ap = AlgorithmParameters.getInstance("EC");
ap.init(new ECKeySizeParameterSpec(keyLength));
return ap.getParameterSpec(ECParameterSpec.class);
} catch (Exception e) {
throw new ProviderException(e);
}
}
boolean checkSupport(Vector<ECParameterSpec> supportedEC,
ECParameterSpec curve) {
boolean found = false;
for (ECParameterSpec ec: supportedEC) {
if (ec.equals(curve)) {
return true;
}
}
return false;
}
@Override
public void initialize(AlgorithmParameterSpec params, SecureRandom random)
throws InvalidAlgorithmParameterException {
ECParameterSpec ecSpec = null;
if (params instanceof ECParameterSpec) {
ECParameterSpec ecParams = (ECParameterSpec) params;
ecSpec = ECUtil.getECParameterSpec(null, ecParams);
if (ecSpec == null) {
throw new InvalidAlgorithmParameterException(
"Unsupported curve: " + params);
}
} else if (params instanceof ECGenParameterSpec) {
String name = ((ECGenParameterSpec) params).getName();
ecSpec = ECUtil.getECParameterSpec(null, name);
if (ecSpec == null) {
throw new InvalidAlgorithmParameterException(
"Unknown curve name: " + name);
}
} else {
throw new InvalidAlgorithmParameterException(
"ECParameterSpec or ECGenParameterSpec required for EC");
}
// Not all known curves are supported by the native implementation
ensureCurveIsSupported(ecSpec);
this.params = ecSpec;
this.keySize = ecSpec.getCurve().getField().getFieldSize();
this.random = random;
}
public static EllipticCurveJsonWebKey generateJwk(ECParameterSpec spec, String provider, SecureRandom secureRandom) throws JoseException
{
EcKeyUtil keyUtil = new EcKeyUtil(provider, secureRandom);
KeyPair keyPair = keyUtil.generateKeyPair(spec);
PublicKey publicKey = keyPair.getPublic();
EllipticCurveJsonWebKey ecJwk = (EllipticCurveJsonWebKey) PublicJsonWebKey.Factory.newPublicJwk(publicKey);
ecJwk.setPrivateKey(keyPair.getPrivate());
return ecJwk;
}
@Test
public void generatePoints() {
// curve definition
String a = "1";
String b = "0";
String q = "23"; // modulus in the elliptic curve
// base point initialization
String basePointX = "1";
String basePointY = "5";
String order = "23";
// private key
String privateKey = "6";
// public key points
String publicKeyX = "11";
String publicKeyY = "1";
// y^2 = x^3 + ax + b mod q
EllipticCurve curve = new EllipticCurve(new ECFieldFp(new BigInteger(q)), // q
// (modulus)
new BigInteger(a), // a
new BigInteger(b)); // b
ECParameterSpec spec = new ECParameterSpec(curve, new ECPoint(new BigInteger(basePointX), new BigInteger(
basePointY)), // G
new BigInteger(order), // n
1); // h
}
private static ECParameterSpec getECParameterSpec(String oid) {
if (oid.equals(SECP256R1.getObjectId())) {
return SECP256R1;
} else if (oid.equals(SECP384R1.getObjectId())) {
return SECP384R1;
} else if (oid.equals(SECP521R1.getObjectId())) {
return SECP521R1;
} else {
return null;
}
}
public JCEECPrivateKey(
String algorithm,
ECPrivateKeyParameters params,
JCEECPublicKey pubKey,
ECParameterSpec spec)
{
ECDomainParameters dp = params.getParameters();
this.algorithm = algorithm;
this.d = params.getD();
if (spec == null)
{
EllipticCurve ellipticCurve = EC5Util.convertCurve(dp.getCurve(), dp.getSeed());
this.ecSpec = new ECParameterSpec(
ellipticCurve,
new ECPoint(
dp.getG().getAffineXCoord().toBigInteger(),
dp.getG().getAffineYCoord().toBigInteger()),
dp.getN(),
dp.getH().intValue());
}
else
{
this.ecSpec = spec;
}
publicKey = getPublicKeyDetails(pubKey);
}
private ECParameterSpec createSpec(EllipticCurve ellipticCurve, ECDomainParameters dp)
{
return new ECParameterSpec(
ellipticCurve,
new ECPoint(
dp.getG().getAffineXCoord().toBigInteger(),
dp.getG().getAffineYCoord().toBigInteger()),
dp.getN(),
dp.getH().intValue());
}
private static PrivateKey getECPrivateKey(byte[] d, ECParameterSpec curveSpec, Provider provider) {
try {
ECPrivateKeySpec priSpec = new ECPrivateKeySpec(new BigInteger(1, d), curveSpec);
KeyFactory kf = provider != null ? KeyFactory.getInstance("EC", provider)
: KeyFactory.getInstance("EC", "SunEC");
return (ECPrivateKey) kf.generatePrivate(priSpec);
} catch (GeneralSecurityException e) {
throw new IllegalStateException(e);
}
}
org.ripple.bouncycastle.jce.spec.ECParameterSpec engineGetSpec()
{
if (ecSpec != null)
{
return EC5Util.convertSpec(ecSpec, withCompression);
}
return BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa();
}
SecretKey getAgreedSecret(
byte[] encodedPoint) throws SSLHandshakeException {
try {
ECParameterSpec params = publicKey.getParams();
ECPoint point =
JsseJce.decodePoint(encodedPoint, params.getCurve());
KeyFactory kf = JsseJce.getKeyFactory("EC");
ECPublicKeySpec spec = new ECPublicKeySpec(point, params);
PublicKey peerPublicKey = kf.generatePublic(spec);
return getAgreedSecret(peerPublicKey);
} catch (GeneralSecurityException | java.io.IOException e) {
throw (SSLHandshakeException) new SSLHandshakeException(
"Could not generate secret").initCause(e);
}
}
ECDHClientKeyExchangeMessage(HandshakeContext handshakeContext,
ECPublicKey publicKey) {
super(handshakeContext);
ECPoint point = publicKey.getW();
ECParameterSpec params = publicKey.getParams();
encodedPoint = JsseJce.encodePoint(point, params.getCurve());
}
@Override
public KeyPair generateKeyPair() {
byte[] encodedParams =
ECUtil.encodeECParameterSpec(null, (ECParameterSpec)params);
// seed is twice the key size (in bytes) plus 1
byte[] seed = new byte[(((keySize + 7) >> 3) + 1) * 2];
if (random == null) {
random = JCAUtil.getSecureRandom();
}
random.nextBytes(seed);
try {
long[] handles = generateECKeyPair(keySize, encodedParams, seed);
// The 'params' object supplied above is equivalent to the native
// one so there is no need to fetch it.
// handles[0] points to the native private key
BigInteger s = new BigInteger(1, getEncodedBytes(handles[0]));
PrivateKey privateKey =
new ECPrivateKeyImpl(s, (ECParameterSpec)params);
// handles[1] points to the native public key
ECPoint w = ECUtil.decodePoint(getEncodedBytes(handles[1]),
((ECParameterSpec)params).getCurve());
PublicKey publicKey =
new ECPublicKeyImpl(w, (ECParameterSpec)params);
return new KeyPair(publicKey, privateKey);
} catch (Exception e) {
throw new ProviderException(e);
}
}
boolean checkSupport(Vector<ECParameterSpec> supportedEC,
ECParameterSpec curve) {
boolean found = false;
for (ECParameterSpec ec: supportedEC) {
if (ec.equals(curve)) {
return true;
}
}
return false;
}
private ECParameterSpec createSpec(EllipticCurve ellipticCurve, ECDomainParameters dp)
{
return new ECParameterSpec(
ellipticCurve,
new ECPoint(
dp.getG().getAffineXCoord().toBigInteger(),
dp.getG().getAffineYCoord().toBigInteger()),
dp.getN(),
dp.getH().intValue());
}
public BCDSTU4145PrivateKey(
String algorithm,
ECPrivateKeyParameters params,
BCDSTU4145PublicKey pubKey,
ECParameterSpec spec)
{
ECDomainParameters dp = params.getParameters();
this.algorithm = algorithm;
this.d = params.getD();
if (spec == null)
{
EllipticCurve ellipticCurve = EC5Util.convertCurve(dp.getCurve(), dp.getSeed());
this.ecSpec = new ECParameterSpec(
ellipticCurve,
new ECPoint(
dp.getG().getAffineXCoord().toBigInteger(),
dp.getG().getAffineYCoord().toBigInteger()),
dp.getN(),
dp.getH().intValue());
}
else
{
this.ecSpec = spec;
}
publicKey = getPublicKeyDetails(pubKey);
}
@Override
KeyPair generate(AlgorithmParameterSpec params, SecureRandom random) {
if (params instanceof ECGenParameterSpec) {
String curveName = ((ECGenParameterSpec) params).getName();
if (curveName.contains("secp")) {
curveName = "secg/" + curveName;
}
EC_Curve curve = EC_Store.getInstance().getObject(EC_Curve.class, curveName);
ECParameterSpec spec = curve.toSpec();
return generate(params, random, spec);
}
return null;
}
public static void assertECParameterSpecEquals(String message, ECParameterSpec expected, ECParameterSpec actual) {
if (expected == actual) {
return;
}
assertEquals(message + "[order]", expected.getOrder(), actual.getOrder());
assertEquals(message + "[cofactor]", expected.getCofactor(), actual.getCofactor());
assertECPointEquals(message + "[generator]", expected.getGenerator(), actual.getGenerator());
assertCurveEquals(message + "[curve]", expected.getCurve(), actual.getCurve());
}