下面列出了怎么用java.security.spec.ECPrivateKeySpec的API类实例代码及写法,或者点击链接到github查看源代码。
private static PrivateKey getECPrivateKey(String curve) throws Exception {
String s;
ECParameterSpec params;
switch (curve) {
case "P256":
s = EC_P256_S;
params = EC_P256_PARAMS;
break;
case "P384":
s = EC_P384_S;
params = EC_P384_PARAMS;
break;
case "P521":
s = EC_P521_S;
params = EC_P521_PARAMS;
break;
default:
throw new Exception("Unsupported curve: " + curve);
}
KeyFactory kf = KeyFactory.getInstance("EC");
KeySpec kspec = new ECPrivateKeySpec(new BigInteger(s), params);
return kf.generatePrivate(kspec);
}
/**
* Returns the ECPrivateKey instance from its raw bytes. Note that you must provide the "s" value of the
* private key, not e.g. the byte array from reading a PKCS#8 key file.
*
* @param privateKeyBytes The byte array (the "s" value) of the private key
* @return The ECPrivateKey instance
*/
public static ECPrivateKey getPrivateKey(byte[] privateKeyBytes) {
try {
AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC");
parameters.init(new ECGenParameterSpec("secp256r1"));
ECParameterSpec ecParameterSpec = parameters.getParameterSpec(ECParameterSpec.class);
ECPrivateKeySpec ecPrivateKeySpec = new ECPrivateKeySpec(new BigInteger(privateKeyBytes), ecParameterSpec);
ECPrivateKey privateKey = (ECPrivateKey) KeyFactory.getInstance("EC").generatePrivate(ecPrivateKeySpec);
return privateKey;
} catch (NoSuchAlgorithmException | InvalidKeySpecException | InvalidParameterSpecException e) {
getLogger().error(e.getClass().getSimpleName() + " occurred when trying to get private key from raw bytes", e);
return null;
}
}
private static PrivateKey getECPrivateKey(String curve) throws Exception {
String s;
ECParameterSpec params;
switch (curve) {
case "P256":
s = EC_P256_S;
params = EC_P256_PARAMS;
break;
case "P384":
s = EC_P384_S;
params = EC_P384_PARAMS;
break;
case "P521":
s = EC_P521_S;
params = EC_P521_PARAMS;
break;
default:
throw new Exception("Unsupported curve: " + curve);
}
KeyFactory kf = KeyFactory.getInstance("EC");
KeySpec kspec = new ECPrivateKeySpec(new BigInteger(s), params);
return kf.generatePrivate(kspec);
}
private static PrivateKey getECPrivateKey(String curve) throws Exception {
String s;
ECParameterSpec params;
switch (curve) {
case "P256":
s = EC_P256_S;
params = EC_P256_PARAMS;
break;
case "P384":
s = EC_P384_S;
params = EC_P384_PARAMS;
break;
case "P521":
s = EC_P521_S;
params = EC_P521_PARAMS;
break;
default:
throw new Exception("Unsupported curve: " + curve);
}
KeyFactory kf = KeyFactory.getInstance("EC");
KeySpec kspec = new ECPrivateKeySpec(new BigInteger(s), params);
return kf.generatePrivate(kspec);
}
private static ECPrivateKey toJcaPrivateKey(org.bouncycastle.asn1.sec.ECPrivateKey ecPrivateKey)
throws GeneralSecurityException {
String curveName = null;
ASN1ObjectIdentifier curveId = (ASN1ObjectIdentifier) ecPrivateKey.getParameters();
if (curveId.equals(secp224r1_OID)) {
curveName = "secp224r1";
} else if (curveId.equals(prime256v1_OID)) {
curveName = "prime256v1";
} else if (curveId.equals(secp384r1_OID)) {
curveName = "secp384r1";
} else if (curveId.equals(secp521r1_OID)) {
curveName = "secp521r1";
} else {
throw new IllegalStateException("Unknown curve OID: " + curveId);
}
ECNamedCurveParameterSpec sp = ECNamedCurveTable.getParameterSpec(curveName);
ECParameterSpec params = new ECNamedCurveSpec(sp.getName(), sp.getCurve(), sp.getG(),
sp.getN(), sp.getH());
ECPrivateKeySpec pkSpec = new ECPrivateKeySpec(ecPrivateKey.getKey(), params);
KeyFactory kf = KeyFactory.getInstance("EC");
ECPrivateKey privateKey = (ECPrivateKey) kf.generatePrivate(pkSpec);
return privateKey;
}
public JCEECPrivateKey(
String algorithm,
org.ripple.bouncycastle.jce.spec.ECPrivateKeySpec spec)
{
this.algorithm = algorithm;
this.d = spec.getD();
if (spec.getParams() != null) // can be null if implicitlyCA
{
ECCurve curve = spec.getParams().getCurve();
EllipticCurve ellipticCurve;
ellipticCurve = EC5Util.convertCurve(curve, spec.getParams().getSeed());
this.ecSpec = EC5Util.convertSpec(ellipticCurve, spec.getParams());
}
else
{
this.ecSpec = null;
}
}
public BCDSTU4145PrivateKey(
org.ripple.bouncycastle.jce.spec.ECPrivateKeySpec spec)
{
this.d = spec.getD();
if (spec.getParams() != null) // can be null if implicitlyCA
{
ECCurve curve = spec.getParams().getCurve();
EllipticCurve ellipticCurve;
ellipticCurve = EC5Util.convertCurve(curve, spec.getParams().getSeed());
this.ecSpec = EC5Util.convertSpec(ellipticCurve, spec.getParams());
}
else
{
this.ecSpec = null;
}
}
public BCECPrivateKey(
String algorithm,
org.ripple.bouncycastle.jce.spec.ECPrivateKeySpec spec,
ProviderConfiguration configuration)
{
this.algorithm = algorithm;
this.d = spec.getD();
if (spec.getParams() != null) // can be null if implicitlyCA
{
ECCurve curve = spec.getParams().getCurve();
EllipticCurve ellipticCurve;
ellipticCurve = EC5Util.convertCurve(curve, spec.getParams().getSeed());
this.ecSpec = EC5Util.convertSpec(ellipticCurve, spec.getParams());
}
else
{
this.ecSpec = null;
}
this.configuration = configuration;
}
public BCECGOST3410PrivateKey(
org.ripple.bouncycastle.jce.spec.ECPrivateKeySpec spec)
{
this.d = spec.getD();
if (spec.getParams() != null) // can be null if implicitlyCA
{
ECCurve curve = spec.getParams().getCurve();
EllipticCurve ellipticCurve;
ellipticCurve = EC5Util.convertCurve(curve, spec.getParams().getSeed());
this.ecSpec = EC5Util.convertSpec(ellipticCurve, spec.getParams());
}
else
{
this.ecSpec = null;
}
}
public JCEECPrivateKey(
String algorithm,
org.ripple.bouncycastle.jce.spec.ECPrivateKeySpec spec)
{
this.algorithm = algorithm;
this.d = spec.getD();
if (spec.getParams() != null) // can be null if implicitlyCA
{
ECCurve curve = spec.getParams().getCurve();
EllipticCurve ellipticCurve;
ellipticCurve = EC5Util.convertCurve(curve, spec.getParams().getSeed());
this.ecSpec = EC5Util.convertSpec(ellipticCurve, spec.getParams());
}
else
{
this.ecSpec = null;
}
}
public BCDSTU4145PrivateKey(
org.ripple.bouncycastle.jce.spec.ECPrivateKeySpec spec)
{
this.d = spec.getD();
if (spec.getParams() != null) // can be null if implicitlyCA
{
ECCurve curve = spec.getParams().getCurve();
EllipticCurve ellipticCurve;
ellipticCurve = EC5Util.convertCurve(curve, spec.getParams().getSeed());
this.ecSpec = EC5Util.convertSpec(ellipticCurve, spec.getParams());
}
else
{
this.ecSpec = null;
}
}
public BCECPrivateKey(
String algorithm,
org.ripple.bouncycastle.jce.spec.ECPrivateKeySpec spec,
ProviderConfiguration configuration)
{
this.algorithm = algorithm;
this.d = spec.getD();
if (spec.getParams() != null) // can be null if implicitlyCA
{
ECCurve curve = spec.getParams().getCurve();
EllipticCurve ellipticCurve;
ellipticCurve = EC5Util.convertCurve(curve, spec.getParams().getSeed());
this.ecSpec = EC5Util.convertSpec(ellipticCurve, spec.getParams());
}
else
{
this.ecSpec = null;
}
this.configuration = configuration;
}
public BCECGOST3410PrivateKey(
org.ripple.bouncycastle.jce.spec.ECPrivateKeySpec spec)
{
this.d = spec.getD();
if (spec.getParams() != null) // can be null if implicitlyCA
{
ECCurve curve = spec.getParams().getCurve();
EllipticCurve ellipticCurve;
ellipticCurve = EC5Util.convertCurve(curve, spec.getParams().getSeed());
this.ecSpec = EC5Util.convertSpec(ellipticCurve, spec.getParams());
}
else
{
this.ecSpec = null;
}
}
public static String signObject(String input, String privateKeyS) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException, InvalidKeySpecException {
////put decrypted private key in a BCPrivate key object
byte[] prk = Base64.decodeBase64(privateKeyS);
//get private key into BC understandable form
ECPrivateKeySpec ecpks = new ECPrivateKeySpec(new BigInteger(privateKeyS), null);
KeyFactory kf = KeyFactory.getInstance("ECDSA", "BCFIPS");
PrivateKey pvk = kf.generatePrivate(ecpks);
//Base64 decode input
byte[] inputbytes = Base64.decodeBase64(input);
//sign
Signature sig = Signature.getInstance("SHA256withECDSA", "BCFIPS");
sig.initSign(pvk, new SecureRandom());
sig.update(inputbytes);
byte[] signedBytes = sig.sign();
// //verify locally FIXME -- local verification is required // not sure how to get the public key
// PublicKey pkey = userKeyPair.getPublic();
// sig.initVerify(pkey);
// sig.update(inputbytes);
// if (sig.verify(signedBytes)) {
// return Base64.encodeBase64String(signedBytes);
// } else {
// return null;
// }
return Base64.encodeBase64String(signedBytes);
}
public static String decryptKeyHandle(String keyHandleWithIV) throws DecoderException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, ShortBufferException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, InvalidKeySpecException, SignatureException {
//get secure element key to decrypt
byte[] Seckeybytes = Hex.decodeHex(CSConstants.SECURE_ELEMENT_SECRET_KEY.toCharArray());
SecretKeySpec sks = new SecretKeySpec(Seckeybytes, "AES");
byte[] receivedkeyHandle = DatatypeConverter.parseBase64Binary(keyHandleWithIV);
//get IV
byte[] receivedIV = new byte[16];
System.arraycopy(receivedkeyHandle, 0, receivedIV, 0, 16);
//unwrap the key handle
//get the wrapped key handle bytes
byte[] wrappedKeyHandleBytes = new byte[receivedkeyHandle.length - receivedIV.length];
System.arraycopy(receivedkeyHandle, receivedIV.length, wrappedKeyHandleBytes, 0, wrappedKeyHandleBytes.length);
//unwrapping received key handle
//decrypt
Cipher cipher1 = Cipher.getInstance("AES/CBC/PKCS7Padding", "BCFIPS");
IvParameterSpec ivspec = new IvParameterSpec(receivedIV);
cipher1.init(Cipher.DECRYPT_MODE, sks, ivspec);
byte[] receivedunwrappedKeyHandle = new byte[cipher1.getOutputSize(wrappedKeyHandleBytes.length)];
int p = cipher1.update(wrappedKeyHandleBytes, 0, wrappedKeyHandleBytes.length, receivedunwrappedKeyHandle, 0);
cipher1.doFinal(receivedunwrappedKeyHandle, p);
//put decrypted key in a BCPrivate key object //to test
String privateKey = keyHandleDecode(new String(receivedunwrappedKeyHandle, "UTF-8"), 0); //0 for key
byte[] prk = Base64.decodeBase64(privateKey);
//get private key into BC understandable form -- test working
ECPrivateKeySpec ecpks = new ECPrivateKeySpec(new BigInteger(prk), null);
KeyFactory kf = KeyFactory.getInstance("ECDSA", "BCFIPS");
PrivateKey privatetest = kf.generatePrivate(ecpks);
return new String(receivedunwrappedKeyHandle, "UTF-8");
}
/**
* Function to generate a PrivateKey object from a byte-array containing the
* ECDSA private-key
*
* @param pvk String with Base64-encoded private key
* @return PrivateKey
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws InvalidKeySpecException
* @throws java.security.spec.InvalidParameterSpecException
*/
public static PrivateKey getUserPrivateKey(String pvk)
throws NoSuchAlgorithmException, NoSuchProviderException,
InvalidKeySpecException, InvalidParameterSpecException
{
AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC");
parameters.init(new ECGenParameterSpec("secp256r1"));
ECParameterSpec ecParameterSpec = parameters.getParameterSpec(ECParameterSpec.class);
ECPrivateKeySpec ecPrivateKeySpec = new ECPrivateKeySpec(new BigInteger(1, Base64.getUrlDecoder().decode(pvk)), ecParameterSpec);
return KeyFactory.getInstance("EC").generatePrivate(ecPrivateKeySpec);
}
public ECPrivateKey ecPrivateKey() {
final ECParameterSpec params = ecParameterSpec(this.value.get("crv").stringValue());
final BigInteger d = parseBase64UrlUInt(this.value.get("d").stringValue());
try {
final ECPrivateKeySpec keySpec = new ECPrivateKeySpec(d, params);
final KeyFactory keyFactory = KeyFactory.getInstance("EC");
return (ECPrivateKey) keyFactory.generatePrivate(keySpec);
} catch (GeneralSecurityException cause) {
throw new RuntimeException(cause);
}
}
/**
* create BCECPrivateKey from privateKey
*
* @param privateKey
* @return
*/
private BCECPrivateKey createBCECPrivateKey(BigInteger privateKey) {
// Handle secret key
ECPrivateKeySpec secretKeySpec =
new ECPrivateKeySpec(privateKey, ECCParams.ecNamedCurveSpec);
BCECPrivateKey bcecPrivateKey =
new BCECPrivateKey("ECDSA", secretKeySpec, BouncyCastleProvider.CONFIGURATION);
return bcecPrivateKey;
}
private KeyPair genECKeyPair(String curvName, String privD, String pubX,
String pubY, Provider p) throws Exception {
AlgorithmParameters params = AlgorithmParameters.getInstance("EC", p);
params.init(new ECGenParameterSpec(curvName));
ECParameterSpec ecParams = params.getParameterSpec(ECParameterSpec.class);
ECPrivateKeySpec privKeySpec =
new ECPrivateKeySpec(new BigInteger(privD, 16), ecParams);
ECPublicKeySpec pubKeySpec =
new ECPublicKeySpec(new ECPoint(new BigInteger(pubX, 16),
new BigInteger(pubY, 16)),
ecParams);
PrivateKey privKey = kf.generatePrivate(privKeySpec);
PublicKey pubKey = kf.generatePublic(pubKeySpec);
return new KeyPair(pubKey, privKey);
}
private static void testPrivate(KeyFactory kf, PrivateKey key) throws Exception {
System.out.println("Testing private key...");
PrivateKey key2 = (PrivateKey)kf.translateKey(key);
KeySpec keySpec = kf.getKeySpec(key, ECPrivateKeySpec.class);
PrivateKey key3 = kf.generatePrivate(keySpec);
KeySpec pkcs8Spec = kf.getKeySpec(key, PKCS8EncodedKeySpec.class);
PrivateKey key4 = kf.generatePrivate(pkcs8Spec);
KeySpec pkcs8Spec2 = new PKCS8EncodedKeySpec(key.getEncoded());
PrivateKey key5 = kf.generatePrivate(pkcs8Spec2);
testKey(key, key);
testKey(key, key2);
testKey(key, key3);
testKey(key, key4);
testKey(key, key5);
}
private KeyPair genECKeyPair(String curvName, String privD, String pubX,
String pubY, Provider p) throws Exception {
AlgorithmParameters params = AlgorithmParameters.getInstance("EC", p);
params.init(new ECGenParameterSpec(curvName));
ECParameterSpec ecParams = params.getParameterSpec(ECParameterSpec.class);
ECPrivateKeySpec privKeySpec =
new ECPrivateKeySpec(new BigInteger(privD, 16), ecParams);
ECPublicKeySpec pubKeySpec =
new ECPublicKeySpec(new ECPoint(new BigInteger(pubX, 16), new BigInteger(pubY, 16)),
ecParams);
PrivateKey privKey = kf.generatePrivate(privKeySpec);
PublicKey pubKey = kf.generatePublic(pubKeySpec);
return new KeyPair(pubKey, privKey);
}
public void bad10() throws Exception {
BigInteger bigInteger = new BigInteger("12345", 5);
new DSAPrivateKeySpec(bigInteger, null, null, null);
new DSAPublicKeySpec(bigInteger, null, bigInteger, null); // report once
new DHPrivateKeySpec(bigInteger, null, null);
new DHPublicKeySpec(bigInteger, null, null);
new ECPrivateKeySpec(bigInteger, null);
new RSAPrivateKeySpec(bigInteger, null);
new RSAMultiPrimePrivateCrtKeySpec(bigInteger, null, null, null, null, null, null, null, null);
new RSAPrivateCrtKeySpec(bigInteger, null, null, null, null, null, null, null);
new RSAPublicKeySpec(bigInteger, null);
new DSAPublicKeyImpl(bigInteger, null, null, null);
}
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);
}
}
/**
* Decode based on d - 32 byte integer
*
* @param privKey
* @param curveName
* - Example secp256r1
* @return
* @throws InvalidKeySpecException
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
*/
public static PrivateKey getPrivKeyFromCurve(byte[] privKey,
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());
ECPrivateKeySpec priKey = new ECPrivateKeySpec(new BigInteger(privKey), // d
params);
return kf.generatePrivate(priKey);
}
/**
* Decode based on d - 32 byte integer
*
* @param privKey
* @param curveName - Example secp256r1
* @return
* @throws InvalidKeySpecException
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
*/
public static PrivateKey getPrivKeyFromCurve(byte[] privKey, 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());
ECPrivateKeySpec priKey = new ECPrivateKeySpec(
new BigInteger(privKey), // d
params);
return kf.generatePrivate(priKey);
}
protected void setUp() throws Exception {
super.setUp();
ECPoint ecpoint = new ECPoint(BigInteger.valueOf(1), BigInteger
.valueOf(1));
EllipticCurve curve = new EllipticCurve(new ECFieldF2m(2), BigInteger
.valueOf(1), BigInteger.valueOf(1));
s = BigInteger.valueOf(1);
ecparams = new ECParameterSpec(curve, ecpoint, BigInteger.valueOf(1), 1);
ecpks = new ECPrivateKeySpec(s, ecparams);
}
public JCEECPrivateKey(
String algorithm,
ECPrivateKeySpec spec)
{
this.algorithm = algorithm;
this.d = spec.getS();
this.ecSpec = spec.getParams();
}
public BCECPrivateKey(
String algorithm,
ECPrivateKeySpec spec,
ProviderConfiguration configuration)
{
this.algorithm = algorithm;
this.d = spec.getS();
this.ecSpec = spec.getParams();
this.configuration = configuration;
}
public static ECPrivateKey getECPrivateKey(String curve, byte[] privateKey) {
try {
ECParameterSpec params = getECParameterSpec(curve, true);
ECPrivateKeySpec keySpec = new ECPrivateKeySpec(
toBigInteger(privateKey), params);
KeyFactory kf = KeyFactory.getInstance("EC");
return (ECPrivateKey) kf.generatePrivate(keySpec);
} catch (Exception ex) {
throw new SecurityException(ex);
}
}
public JCEECPrivateKey(
String algorithm,
ECPrivateKeySpec spec)
{
this.algorithm = algorithm;
this.d = spec.getS();
this.ecSpec = spec.getParams();
}