下面列出了怎么用java.security.spec.ECPublicKeySpec的API类实例代码及写法,或者点击链接到github查看源代码。
/**
*
* @param publickeybytes
* @return
* @throws java.security.spec.InvalidKeySpecException
* @throws java.security.NoSuchAlgorithmException
* @throws java.security.NoSuchProviderException
* @throws java.security.spec.InvalidParameterSpecException
*/
public static ECPublicKey getUserECPublicKey(byte[] publickeybytes) throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException, InvalidParameterSpecException {
//append the sign byte to the arrays
byte[] processedXData = new byte[EC_POINTSIZE];
byte[] processedYData = new byte[EC_POINTSIZE];
System.arraycopy(publickeybytes, 1, processedXData, 0, EC_POINTSIZE);
System.arraycopy(publickeybytes, EC_POINTSIZE + 1, processedYData, 0, EC_POINTSIZE);
ECPoint pubPoint = new ECPoint(new BigInteger(1, processedXData), new BigInteger(1, processedYData));
AlgorithmParameters params = AlgorithmParameters.getInstance("EC", BC_FIPS_PROVIDER);
params.init(new ECGenParameterSpec("prime256v1"));
ECParameterSpec ecParameters = params.getParameterSpec(ECParameterSpec.class);
ECPublicKeySpec pubECSpec = new ECPublicKeySpec(pubPoint, ecParameters);
return (ECPublicKey) KeyFactory.getInstance("EC", BC_FIPS_PROVIDER).generatePublic(pubECSpec);
}
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);
}
void checkConstraints(AlgorithmConstraints constraints,
byte[] encodedPoint) throws SSLHandshakeException {
try {
ECParameterSpec params = publicKey.getParams();
ECPoint point =
JsseJce.decodePoint(encodedPoint, params.getCurve());
ECPublicKeySpec spec = new ECPublicKeySpec(point, params);
KeyFactory kf = JsseJce.getKeyFactory("EC");
ECPublicKey pubKey = (ECPublicKey)kf.generatePublic(spec);
// check constraints of ECPublicKey
if (!constraints.permits(
EnumSet.of(CryptoPrimitive.KEY_AGREEMENT), pubKey)) {
throw new SSLHandshakeException(
"ECPublicKey does not comply to algorithm constraints");
}
} catch (GeneralSecurityException | java.io.IOException e) {
throw (SSLHandshakeException) new SSLHandshakeException(
"Could not generate ECPublicKey").initCause(e);
}
}
static void checkConstraints(AlgorithmConstraints constraints,
ECPublicKey publicKey,
byte[] encodedPoint) throws SSLHandshakeException {
try {
ECParameterSpec params = publicKey.getParams();
ECPoint point =
JsseJce.decodePoint(encodedPoint, params.getCurve());
ECPublicKeySpec spec = new ECPublicKeySpec(point, params);
KeyFactory kf = JsseJce.getKeyFactory("EC");
ECPublicKey peerPublicKey =
(ECPublicKey)kf.generatePublic(spec);
// check constraints of ECPublicKey
if (!constraints.permits(
EnumSet.of(CryptoPrimitive.KEY_AGREEMENT),
peerPublicKey)) {
throw new SSLHandshakeException(
"ECPublicKey does not comply to algorithm constraints");
}
} catch (GeneralSecurityException | java.io.IOException e) {
throw (SSLHandshakeException) new SSLHandshakeException(
"Could not generate ECPublicKey").initCause(e);
}
}
@VisibleForTesting
static PublicKey decodePublicKey(byte[] keyBytes)
throws NoSuchAlgorithmException, InvalidKeyException {
BigInteger x =
new BigInteger(
/*signum=*/ 1,
Arrays.copyOfRange(keyBytes, 1, 1 + EC_COORDINATE_LEN_BYTES));
BigInteger y =
new BigInteger(
/*signum=*/ 1,
Arrays.copyOfRange(
keyBytes, 1 + EC_COORDINATE_LEN_BYTES, EC_PUBLIC_KEY_LEN_BYTES));
// Checks if the point is indeed on the P-256 curve for security considerations
validateEcPoint(x, y);
KeyFactory keyFactory = KeyFactory.getInstance(EC_ALG);
try {
return keyFactory.generatePublic(new ECPublicKeySpec(new ECPoint(x, y), EC_PARAM_SPEC));
} catch (InvalidKeySpecException ex) {
// This should never happen
throw new RuntimeException(ex);
}
}
private static ECPublicKey generateECPublicKey(final JWK jwk) {
final BigInteger x = decodeBase64(jwk.getX());
final BigInteger y = decodeBase64(jwk.getY());
try {
final KeyFactory factory = KeyFactory.getInstance("EC");
final ECPoint point = new ECPoint(x, y);
final ECNamedCurveParameterSpec paramSpec = ECNamedCurveTable.getParameterSpec(jwk.getCurve());
final ECNamedCurveSpec params = new ECNamedCurveSpec(jwk.getCurve(),
paramSpec.getCurve(),
paramSpec.getG(),
paramSpec.getN());
final ECPublicKeySpec spec = new ECPublicKeySpec(point, params);
return (ECPublicKey) factory.generatePublic(spec);
} catch (final NoSuchAlgorithmException | InvalidKeySpecException e) {
Log.e(TAG, "failed to generate EC Public Key from JWK: " + jwk, e);
return 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);
}
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);
}
/**
* Returns the ECPublicKey instance from its encoded raw bytes.
* The first byte has the fixed value 0x04 indicating the uncompressed form.
* Therefore, the byte array must be of form: [0x04, x coord of point (32 bytes), y coord of point (32 bytes)]
*
* @param publicKeyBytes The byte array representing the encoded raw bytes of the public key
* @return The ECPublicKey instance
*/
public static ECPublicKey getPublicKey(byte[] publicKeyBytes) {
// First we separate x and y of coordinates into separate variables
byte[] x = new byte[32];
byte[] y = new byte[32];
System.arraycopy(publicKeyBytes, 1, x, 0, 32);
System.arraycopy(publicKeyBytes, 33, y, 0, 32);
try {
KeyFactory kf = KeyFactory.getInstance("EC");
AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC");
parameters.init(new ECGenParameterSpec("secp256r1"));
ECParameterSpec ecParameterSpec = parameters.getParameterSpec(ECParameterSpec.class);
ECPublicKeySpec ecPublicKeySpec = new ECPublicKeySpec(new ECPoint(new BigInteger(x), new BigInteger(y)), ecParameterSpec);
ECPublicKey ecPublicKey = (ECPublicKey) kf.generatePublic(ecPublicKeySpec);
return ecPublicKey;
} catch (NoSuchAlgorithmException | InvalidParameterSpecException | InvalidKeySpecException e) {
getLogger().error(e.getClass().getSimpleName() + " occurred when trying to get public key from raw bytes", e);
return null;
}
}
static ECDHECredentials valueOf(NamedGroup namedGroup,
byte[] encodedPoint) throws IOException, GeneralSecurityException {
if (namedGroup.spec != NamedGroupSpec.NAMED_GROUP_ECDHE) {
throw new RuntimeException(
"Credentials decoding: Not ECDHE named group");
}
if (encodedPoint == null || encodedPoint.length == 0) {
return null;
}
ECParameterSpec parameters =
(ECParameterSpec)namedGroup.keAlgParamSpec;
ECPoint point = ECUtil.decodePoint(
encodedPoint, parameters.getCurve());
KeyFactory factory = KeyFactory.getInstance("EC");
ECPublicKey publicKey = (ECPublicKey)factory.generatePublic(
new ECPublicKeySpec(point, parameters));
return new ECDHECredentials(publicKey, namedGroup);
}
void checkConstraints(AlgorithmConstraints constraints,
byte[] encodedPoint) throws SSLHandshakeException {
try {
ECParameterSpec params = publicKey.getParams();
ECPoint point =
ECUtil.decodePoint(encodedPoint, params.getCurve());
ECPublicKeySpec spec = new ECPublicKeySpec(point, params);
KeyFactory kf = KeyFactory.getInstance("EC");
ECPublicKey pubKey = (ECPublicKey)kf.generatePublic(spec);
// check constraints of ECPublicKey
if (!constraints.permits(
EnumSet.of(CryptoPrimitive.KEY_AGREEMENT), pubKey)) {
throw new SSLHandshakeException(
"ECPublicKey does not comply to algorithm constraints");
}
} catch (GeneralSecurityException | java.io.IOException e) {
throw (SSLHandshakeException) new SSLHandshakeException(
"Could not generate ECPublicKey").initCause(e);
}
}
private JWSVerifier from(ECKey ecKey) {
try {
Curve curve = Curve.parse(ecKey.getCrv());
if(curve.getStdName()==null) {
throw new IllegalArgumentException("Unknown EC Curve: "+ecKey.getCrv());
}
AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC");
parameters.init(new ECGenParameterSpec(curve.getStdName()));
ECParameterSpec ecParameters = parameters.getParameterSpec(ECParameterSpec.class);
byte[] x = Base64.getUrlDecoder().decode(ecKey.getX());
byte[] y = Base64.getUrlDecoder().decode(ecKey.getY());
ECPoint ecPoint = new ECPoint(new BigInteger(1,x), new BigInteger(1,y));
ECPublicKeySpec ecPublicKeySpec = new ECPublicKeySpec(ecPoint, ecParameters);
ECPublicKey ecPublicKey = (ECPublicKey) KeyFactory.getInstance("EC").generatePublic(ecPublicKeySpec);
return new ECDSAVerifier(ecPublicKey);
}
catch (NoSuchAlgorithmException | InvalidParameterSpecException | InvalidKeySpecException | JOSEException ex) {
LOGGER.error("Unable to build Verifier from Elliptic Curve (EC) key",ex);
throw new IllegalArgumentException("Signature is using and unknown/not managed key");
}
}
/**
* Returns this key as ECPublicKeySpec or null if the key cannot be represented as
* ECPublicKeySpec. The later happens for example if the order of cofactor are not positive.
*/
public ECPublicKeySpec getSpec() {
try {
ECFieldFp fp = new ECFieldFp(p);
EllipticCurve curve = new EllipticCurve(fp, a, b);
ECPoint g = new ECPoint(gx, gy);
// ECParameterSpec requires that the cofactor h is specified.
if (h == null) {
return null;
}
ECParameterSpec params = new ECParameterSpec(curve, g, n, h);
ECPoint pubPoint = new ECPoint(pubx, puby);
ECPublicKeySpec pub = new ECPublicKeySpec(pubPoint, params);
return pub;
} catch (Exception ex) {
System.out.println(comment + " throws " + ex.toString());
return null;
}
}
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);
}
@Test
public void security_info_rpk_ser_des_then_equal() throws Exception {
byte[] publicX = Hex
.decodeHex("89c048261979208666f2bfb188be1968fc9021c416ce12828c06f4e314c167b5".toCharArray());
byte[] publicY = Hex
.decodeHex("cbf1eb7587f08e01688d9ada4be859137ca49f79394bad9179326b3090967b68".toCharArray());
// Get Elliptic Curve Parameter spec for secp256r1
AlgorithmParameters algoParameters = AlgorithmParameters.getInstance("EC");
algoParameters.init(new ECGenParameterSpec("secp256r1"));
ECParameterSpec parameterSpec = algoParameters.getParameterSpec(ECParameterSpec.class);
// Create key specs
KeySpec publicKeySpec = new ECPublicKeySpec(new ECPoint(new BigInteger(publicX), new BigInteger(publicY)),
parameterSpec);
SecurityInfo si = SecurityInfo.newRawPublicKeyInfo("myendpoint",
KeyFactory.getInstance("EC").generatePublic(publicKeySpec));
byte[] data = SecurityInfoSerDes.serialize(si);
assertEquals(
"{\"ep\":\"myendpoint\",\"rpk\":{\"x\":\"89c048261979208666f2bfb188be1968fc9021c416ce12828c06f4e314c167b5\",\"y\":\"cbf1eb7587f08e01688d9ada4be859137ca49f79394bad9179326b3090967b68\",\"params\":\"secp256r1\"}}",
new String(data));
System.err.println(new String(SecurityInfoSerDes.serialize(SecurityInfoSerDes.deserialize(data))));
assertEquals(si, SecurityInfoSerDes.deserialize(data));
}
/**
* Decode based on X, Y 32 byte integers
*
* @param pubKey
* @param curveName
* - Example secp256r1
* @return
* @throws InvalidKeySpecException
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
*/
public static PublicKey getPubKeyFromCurve(byte[] pubKey, String curveName)
throws InvalidKeySpecException, NoSuchAlgorithmException,
NoSuchProviderException {
ECNamedCurveParameterSpec spec = ECNamedCurveTable
.getParameterSpec(curveName);
KeyFactory kf = KeyFactory.getInstance("ECDSA",
new BouncyCastleProvider());
ECNamedCurveSpec params = new ECNamedCurveSpec(curveName,
spec.getCurve(), spec.getG(), spec.getN());
ECPoint point = ECPointUtil.decodePoint(params.getCurve(), pubKey);
ECPublicKeySpec pubKeySpec = new ECPublicKeySpec(point, params);
ECPublicKey pk = (ECPublicKey) kf.generatePublic(pubKeySpec);
return pk;
}
@Test
public void security_info_rpk_ser_des_then_equal() throws Exception {
byte[] publicX = Hex
.decodeHex("89c048261979208666f2bfb188be1968fc9021c416ce12828c06f4e314c167b5".toCharArray());
byte[] publicY = Hex
.decodeHex("cbf1eb7587f08e01688d9ada4be859137ca49f79394bad9179326b3090967b68".toCharArray());
// Get Elliptic Curve Parameter spec for secp256r1
AlgorithmParameters algoParameters = AlgorithmParameters.getInstance("EC");
algoParameters.init(new ECGenParameterSpec("secp256r1"));
ECParameterSpec parameterSpec = algoParameters.getParameterSpec(ECParameterSpec.class);
// Create key specs
KeySpec publicKeySpec = new ECPublicKeySpec(new ECPoint(new BigInteger(publicX), new BigInteger(publicY)),
parameterSpec);
SecurityInfo si = SecurityInfo.newRawPublicKeyInfo("myendpoint",
KeyFactory.getInstance("EC").generatePublic(publicKeySpec));
byte[] data = SecurityInfoSerDes.serialize(si);
assertEquals(
"{\"ep\":\"myendpoint\",\"rpk\":{\"x\":\"89c048261979208666f2bfb188be1968fc9021c416ce12828c06f4e314c167b5\",\"y\":\"cbf1eb7587f08e01688d9ada4be859137ca49f79394bad9179326b3090967b68\",\"params\":\"secp256r1\"}}",
new String(data));
System.err.println(new String(SecurityInfoSerDes.serialize(SecurityInfoSerDes.deserialize(data))));
assertEquals(si, SecurityInfoSerDes.deserialize(data));
}
public static void main(String[] args) throws Exception {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC");
ECGenParameterSpec gps = new ECGenParameterSpec ("secp256r1"); // NIST P-256
kpg.initialize(gps);
KeyPair apair = kpg.generateKeyPair();
ECPublicKey apub = (ECPublicKey)apair.getPublic();
ECParameterSpec aspec = apub.getParams();
// could serialize aspec for later use (in compatible JRE)
//
// for test only reuse bogus pubkey, for real substitute values
ECPoint apoint = apub.getW();
BigInteger x = apoint.getAffineX(), y = apoint.getAffineY();
// construct point plus params to pubkey
ECPoint bpoint = new ECPoint (x,y);
ECPublicKeySpec bpubs = new ECPublicKeySpec (bpoint, aspec);
KeyFactory kfa = KeyFactory.getInstance ("EC");
ECPublicKey bpub = (ECPublicKey) kfa.generatePublic(bpubs);
new Ssh2EcdsaSha2NistPublicKey(bpub);
}
public JCEECPublicKey(
String algorithm,
org.ripple.bouncycastle.jce.spec.ECPublicKeySpec spec)
{
this.algorithm = algorithm;
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(), false);
}
this.ecSpec = null;
}
}
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 BCECGOST3410PublicKey(
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 JCEECPublicKey(
String algorithm,
org.ripple.bouncycastle.jce.spec.ECPublicKeySpec spec)
{
this.algorithm = algorithm;
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(), false);
}
this.ecSpec = null;
}
}
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 BCECGOST3410PublicKey(
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 static ECPublicKey getUserECPublicKey(byte[] x, byte[] y, String curveString) throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException, InvalidParameterSpecException {
//append the sign byte to the arrays
ECPoint pubPoint = new ECPoint(new BigInteger(1, x), new BigInteger(1, y));
AlgorithmParameters params = AlgorithmParameters.getInstance("EC", BC_FIPS_PROVIDER);
params.init(new ECGenParameterSpec(curveString));
ECParameterSpec ecParameters = params.getParameterSpec(ECParameterSpec.class);
ECPublicKeySpec pubECSpec = new ECPublicKeySpec(pubPoint, ecParameters);
return (ECPublicKey) KeyFactory.getInstance("EC", BC_FIPS_PROVIDER).generatePublic(pubECSpec);
}
public ECPublicKey ecPublicKey() {
final ECParameterSpec params = ecParameterSpec(this.value.get("crv").stringValue());
final BigInteger x = parseBase64UrlUInt(this.value.get("x").stringValue());
final BigInteger y = parseBase64UrlUInt(this.value.get("y").stringValue());
try {
final ECPublicKeySpec keySpec = new ECPublicKeySpec(new ECPoint(x, y), params);
final KeyFactory keyFactory = KeyFactory.getInstance("EC");
return (ECPublicKey) keyFactory.generatePublic(keySpec);
} catch (GeneralSecurityException cause) {
throw new RuntimeException(cause);
}
}
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);
}
}
@Override
public byte[] getEncoded() {
if (encoding == null) {
try {
encoding = KeyFactory.getInstance("EC").generatePublic(
new ECPublicKeySpec(getW(), getParams()))
.getEncoded();
} catch (Exception e) {
// ignore
}
}
return encoding;
}
private static PublicKey getECPublicKey(String curve) throws Exception {
KeyFactory kf = KeyFactory.getInstance("EC");
String x, y;
ECParameterSpec params;
switch (curve) {
case "P256":
x = EC_P256_X;
y = EC_P256_Y;
params = EC_P256_PARAMS;
break;
case "P384":
x = EC_P384_X;
y = EC_P384_Y;
params = EC_P384_PARAMS;
break;
case "P521":
x = EC_P521_X;
y = EC_P521_Y;
params = EC_P521_PARAMS;
break;
default:
throw new Exception("Unsupported curve: " + curve);
}
KeySpec kspec = new ECPublicKeySpec(new ECPoint(new BigInteger(x),
new BigInteger(y)),
params);
return kf.generatePublic(kspec);
}
SecretKey getAgreedSecret(
byte[] encodedPoint) throws SSLHandshakeException {
try {
ECParameterSpec params = publicKey.getParams();
ECPoint point =
ECUtil.decodePoint(encodedPoint, params.getCurve());
KeyFactory kf = KeyFactory.getInstance("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);
}
}