use of java.security.interfaces.ECPrivateKey in project robovm by robovm.
the class TestKeyStore method createCertificate.
private static X509Certificate createCertificate(PublicKey publicKey, PrivateKey privateKey, X500Principal subject, X500Principal issuer, int keyUsage, boolean ca, List<KeyPurposeId> extendedKeyUsages, List<Boolean> criticalExtendedKeyUsages, List<GeneralName> subjectAltNames, List<GeneralSubtree> permittedNameConstraints, List<GeneralSubtree> excludedNameConstraints) throws Exception {
// Note that there is no way to programmatically make a
// Certificate using java.* or javax.* APIs. The
// CertificateFactory interface assumes you want to read
// in a stream of bytes, typically the X.509 factory would
// allow ASN.1 DER encoded bytes and optionally some PEM
// formats. Here we use Bouncy Castle's
// X509V3CertificateGenerator and related classes.
long millisPerDay = 24 * 60 * 60 * 1000;
long now = System.currentTimeMillis();
Date start = new Date(now - millisPerDay);
Date end = new Date(now + millisPerDay);
BigInteger serial = BigInteger.valueOf(1);
String keyAlgorithm = privateKey.getAlgorithm();
String signatureAlgorithm;
if (keyAlgorithm.equals("RSA")) {
signatureAlgorithm = "sha1WithRSA";
} else if (keyAlgorithm.equals("DSA")) {
signatureAlgorithm = "sha1WithDSA";
} else if (keyAlgorithm.equals("EC")) {
signatureAlgorithm = "sha1WithECDSA";
} else if (keyAlgorithm.equals("EC_RSA")) {
signatureAlgorithm = "sha1WithRSA";
} else {
throw new IllegalArgumentException("Unknown key algorithm " + keyAlgorithm);
}
X509V3CertificateGenerator x509cg = new X509V3CertificateGenerator();
x509cg.setSubjectDN(subject);
x509cg.setIssuerDN(issuer);
x509cg.setNotBefore(start);
x509cg.setNotAfter(end);
x509cg.setPublicKey(publicKey);
x509cg.setSignatureAlgorithm(signatureAlgorithm);
x509cg.setSerialNumber(serial);
if (keyUsage != 0) {
x509cg.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(keyUsage));
}
if (ca) {
x509cg.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
}
for (int i = 0; i < extendedKeyUsages.size(); i++) {
KeyPurposeId keyPurposeId = extendedKeyUsages.get(i);
boolean critical = criticalExtendedKeyUsages.get(i);
x509cg.addExtension(X509Extensions.ExtendedKeyUsage, critical, new ExtendedKeyUsage(keyPurposeId));
}
for (GeneralName subjectAltName : subjectAltNames) {
x509cg.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(subjectAltName).getEncoded());
}
if (!permittedNameConstraints.isEmpty() || !excludedNameConstraints.isEmpty()) {
x509cg.addExtension(X509Extensions.NameConstraints, true, new NameConstraints(permittedNameConstraints.toArray(new GeneralSubtree[permittedNameConstraints.size()]), excludedNameConstraints.toArray(new GeneralSubtree[excludedNameConstraints.size()])));
}
if (privateKey instanceof ECPrivateKey) {
/*
* bouncycastle needs its own ECPrivateKey implementation
*/
KeyFactory kf = KeyFactory.getInstance(keyAlgorithm, "BC");
PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(privateKey.getEncoded());
privateKey = kf.generatePrivate(ks);
}
X509Certificate x509c = x509cg.generateX509Certificate(privateKey);
if (StandardNames.IS_RI) {
/*
* The RI can't handle the BC EC signature algorithm
* string of "ECDSA", since it expects "...WITHEC...",
* so convert from BC to RI X509Certificate
* implementation via bytes.
*/
CertificateFactory cf = CertificateFactory.getInstance("X.509");
ByteArrayInputStream bais = new ByteArrayInputStream(x509c.getEncoded());
Certificate c = cf.generateCertificate(bais);
x509c = (X509Certificate) c;
}
return x509c;
}
use of java.security.interfaces.ECPrivateKey in project robovm by robovm.
the class OpenSSLSignature method engineInitSign.
@Override
protected void engineInitSign(PrivateKey privateKey) throws InvalidKeyException {
destroyContextIfExists();
if (privateKey instanceof OpenSSLKeyHolder) {
OpenSSLKey pkey = ((OpenSSLKeyHolder) privateKey).getOpenSSLKey();
checkEngineType(pkey);
key = pkey;
} else if (privateKey instanceof RSAPrivateCrtKey) {
if (engineType != EngineType.RSA) {
throw new InvalidKeyException("Signature not initialized as RSA");
}
RSAPrivateCrtKey rsaPrivateKey = (RSAPrivateCrtKey) privateKey;
key = OpenSSLRSAPrivateCrtKey.getInstance(rsaPrivateKey);
} else if (privateKey instanceof RSAPrivateKey) {
if (engineType != EngineType.RSA) {
throw new InvalidKeyException("Signature not initialized as RSA");
}
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;
key = OpenSSLRSAPrivateKey.getInstance(rsaPrivateKey);
} else if (privateKey instanceof DSAPrivateKey) {
if (engineType != EngineType.DSA) {
throw new InvalidKeyException("Signature not initialized as DSA");
}
DSAPrivateKey dsaPrivateKey = (DSAPrivateKey) privateKey;
key = OpenSSLDSAPrivateKey.getInstance(dsaPrivateKey);
} else if (privateKey instanceof ECPrivateKey) {
if (engineType != EngineType.EC) {
throw new InvalidKeyException("Signature not initialized as EC");
}
ECPrivateKey ecPrivateKey = (ECPrivateKey) privateKey;
key = OpenSSLECPrivateKey.getInstance(ecPrivateKey);
} else {
throw new InvalidKeyException("Need DSA or RSA or EC private key");
}
}
use of java.security.interfaces.ECPrivateKey in project robovm by robovm.
the class OpenSSLECKeyFactory method engineTranslateKey.
@Override
protected Key engineTranslateKey(Key key) throws InvalidKeyException {
if (key == null) {
throw new InvalidKeyException("key == null");
}
if ((key instanceof OpenSSLECPublicKey) || (key instanceof OpenSSLECPrivateKey)) {
return key;
} else if (key instanceof ECPublicKey) {
ECPublicKey ecKey = (ECPublicKey) key;
ECPoint w = ecKey.getW();
ECParameterSpec params = ecKey.getParams();
try {
return engineGeneratePublic(new ECPublicKeySpec(w, params));
} catch (InvalidKeySpecException e) {
throw new InvalidKeyException(e);
}
} else if (key instanceof ECPrivateKey) {
ECPrivateKey ecKey = (ECPrivateKey) key;
BigInteger s = ecKey.getS();
ECParameterSpec params = ecKey.getParams();
try {
return engineGeneratePrivate(new ECPrivateKeySpec(s, params));
} catch (InvalidKeySpecException e) {
throw new InvalidKeyException(e);
}
} else if ((key instanceof PrivateKey) && ("PKCS#8".equals(key.getFormat()))) {
byte[] encoded = key.getEncoded();
if (encoded == null) {
throw new InvalidKeyException("Key does not support encoding");
}
try {
return engineGeneratePrivate(new PKCS8EncodedKeySpec(encoded));
} catch (InvalidKeySpecException e) {
throw new InvalidKeyException(e);
}
} else if ((key instanceof PublicKey) && ("X.509".equals(key.getFormat()))) {
byte[] encoded = key.getEncoded();
if (encoded == null) {
throw new InvalidKeyException("Key does not support encoding");
}
try {
return engineGeneratePublic(new X509EncodedKeySpec(encoded));
} catch (InvalidKeySpecException e) {
throw new InvalidKeyException(e);
}
} else {
throw new InvalidKeyException("Key must be EC public or private key; was " + key.getClass().getName());
}
}
use of java.security.interfaces.ECPrivateKey in project wycheproof by google.
the class EcKeyTest method testEncodedPrivateKey.
public void testEncodedPrivateKey() throws Exception {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
keyGen.initialize(EcUtil.getNistP256Params());
KeyPair keyPair = keyGen.generateKeyPair();
ECPrivateKey priv = (ECPrivateKey) keyPair.getPrivate();
byte[] encoded = priv.getEncoded();
System.out.println("Encoded ECPrivateKey:" + TestUtil.bytesToHex(encoded));
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(encoded);
KeyFactory kf = KeyFactory.getInstance("EC");
ECPrivateKey decoded = (ECPrivateKey) kf.generatePrivate(spec);
assertEquals(priv.getS(), decoded.getS());
assertEquals(priv.getParams().getCofactor(), decoded.getParams().getCofactor());
assertEquals(priv.getParams().getCurve(), decoded.getParams().getCurve());
assertEquals(priv.getParams().getGenerator(), decoded.getParams().getGenerator());
assertEquals(priv.getParams().getOrder(), decoded.getParams().getOrder());
}
use of java.security.interfaces.ECPrivateKey in project wycheproof by google.
the class EcdhTest method testWrongOrder.
/**
* This test modifies the order of group in the public key. A severe bug would be an
* implementation that leaks information whether the private key is larger than the order given in
* the public key. Also a severe bug would be to reduce the private key modulo the order given in
* the public key parameters.
*/
// TODO(bleichen): This can be merged with testModifiedPublic once this is fixed.
@SuppressWarnings("InsecureCryptoUsage")
public void testWrongOrder(String algorithm, ECParameterSpec spec) throws Exception {
KeyAgreement ka;
try {
ka = KeyAgreement.getInstance(algorithm);
} catch (NoSuchAlgorithmException ex) {
System.out.println("testWrongOrder: " + algorithm + " not supported");
return;
}
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
ECPrivateKey priv;
ECPublicKey pub;
try {
keyGen.initialize(spec);
priv = (ECPrivateKey) keyGen.generateKeyPair().getPrivate();
pub = (ECPublicKey) keyGen.generateKeyPair().getPublic();
} catch (GeneralSecurityException ex) {
// This is OK, since not all provider support Brainpool curves
System.out.println("testWrongOrder: could not generate keys for curve");
return;
}
// Get the shared secret for the unmodified keys.
ka.init(priv);
ka.doPhase(pub, true);
byte[] shared = ka.generateSecret();
// Generate a modified public key.
ECParameterSpec modifiedParams = new ECParameterSpec(spec.getCurve(), spec.getGenerator(), spec.getOrder().shiftRight(16), 1);
ECPublicKeySpec modifiedPubSpec = new ECPublicKeySpec(pub.getW(), modifiedParams);
KeyFactory kf = KeyFactory.getInstance("EC");
ECPublicKey modifiedPub;
try {
modifiedPub = (ECPublicKey) kf.generatePublic(modifiedPubSpec);
} catch (GeneralSecurityException ex) {
// The provider does not support non-standard curves or did a validity check.
// Both would be correct.
System.out.println("testWrongOrder: can't modify order.");
return;
}
byte[] shared2;
try {
ka.init(priv);
ka.doPhase(modifiedPub, true);
shared2 = ka.generateSecret();
} catch (GeneralSecurityException ex) {
// This is the expected behavior
System.out.println("testWrongOrder:" + ex.toString());
return;
}
// TODO(bleichen): Getting here is already a bug and we might flag this later.
// At the moment we are only interested in really bad behavior of a library, that potentially
// leaks the secret key. This is the case when the shared secrets are different, since this
// suggests that the implementation reduces the multiplier modulo the given order of the curve
// or some other behaviour that is dependent on the private key.
// An attacker who can check whether a DH computation was done correctly or incorrectly because
// of modular reduction, can determine the private key, either by a binary search or by trying
// to guess the private key modulo some small "order".
// BouncyCastle v.1.53 fails this test, and leaks the private key.
System.out.println("Generated shared secret with a modified order:" + algorithm + "\n" + "expected:" + TestUtil.bytesToHex(shared) + " computed:" + TestUtil.bytesToHex(shared2));
assertEquals("Algorithm:" + algorithm, TestUtil.bytesToHex(shared), TestUtil.bytesToHex(shared2));
}
Aggregations