use of java.security.PublicKey in project robovm by robovm.
the class KeyFactoryTest method testGeneratePublic.
@SuppressWarnings("unchecked")
public void testGeneratePublic() {
KeyFactory factory = null;
try {
factory = KeyFactory.getInstance(TEST_KEYFACTORY_NAME);
} catch (NoSuchAlgorithmException e) {
fail("unexpected exception: " + e);
}
assertNotNull(factory);
try {
TestPublicKey key = new TestPublicKey();
TestPublicKeySpec keySpec = new TestPublicKeySpec(key);
PublicKey publicKey = factory.generatePublic(keySpec);
assertNotNull(publicKey);
assertTrue(Arrays.equals(key.encoded, publicKey.getEncoded()));
} catch (InvalidKeySpecException e) {
fail("unexpected exception: " + e);
}
KeySpec[] keySpecs = { new TestPrivateKeySpec(new TestPrivateKey()), null, new DSAPublicKeySpec(null, null, null, null) };
Class[] exceptions = { InvalidKeySpecException.class, NullPointerException.class, InvalidKeySpecException.class };
for (int i = 0; i < keySpecs.length; i++) {
KeySpec keySpec = keySpecs[i];
String message = "generatePublic(" + (keySpec == null ? "null" : keySpec.toString()) + ")";
try {
PublicKey generatePublic = factory.generatePublic(keySpec);
assertNotNull(generatePublic);
} catch (Exception e) {
checkException(message, e, exceptions[i]);
} finally {
checkException(message, null, exceptions[i]);
}
}
}
use of java.security.PublicKey in project robovm by robovm.
the class Identity2Test method test_getPublicKey.
/**
* java.security.Identity#getPublicKey()
*/
public void test_getPublicKey() throws Exception {
IdentitySubclass sub = new IdentitySubclass("test", new IdentityScopeSubclass());
sub.setPublicKey(getPubKey());
PublicKey returnedPubKey = sub.getPublicKey();
assertEquals("Wrong PublicKey returned", getPubKey(), returnedPubKey);
}
use of java.security.PublicKey in project robovm by robovm.
the class IdentityScope2Test method test_getIdentityLjava_security_PublicKey.
/**
* java.security.IdentityScope#getIdentity(java.security.PublicKey)
*/
public void test_getIdentityLjava_security_PublicKey() throws Exception {
IdentityScopeSubclass sub = new IdentityScopeSubclass("test", new IdentityScopeSubclass());
Identity id = new IdentitySubclass();
id.setPublicKey(getPubKey());
sub.addIdentity(id);
Identity returnedId = sub.getIdentity(getPubKey());
assertEquals("Test 1: Returned Identity not the same as the added one;", id, returnedId);
assertNull("Test 2: Null value expected.", sub.getIdentity((PublicKey) null));
PublicKey anotherKey = KeyPairGenerator.getInstance("DSA").genKeyPair().getPublic();
assertNull("Test 3: Null value expected.", sub.getIdentity(anotherKey));
}
use of java.security.PublicKey in project robovm by robovm.
the class ECUtil method generatePublicKeyParameter.
public static AsymmetricKeyParameter generatePublicKeyParameter(PublicKey key) throws InvalidKeyException {
if (key instanceof ECPublicKey) {
ECPublicKey k = (ECPublicKey) key;
ECParameterSpec s = k.getParameters();
if (s == null) {
s = BouncyCastleProvider.CONFIGURATION.getEcImplicitlyCa();
return new ECPublicKeyParameters(((BCECPublicKey) k).engineGetQ(), new ECDomainParameters(s.getCurve(), s.getG(), s.getN(), s.getH(), s.getSeed()));
} else {
return new ECPublicKeyParameters(k.getQ(), new ECDomainParameters(s.getCurve(), s.getG(), s.getN(), s.getH(), s.getSeed()));
}
} else if (key instanceof java.security.interfaces.ECPublicKey) {
java.security.interfaces.ECPublicKey pubKey = (java.security.interfaces.ECPublicKey) key;
ECParameterSpec s = EC5Util.convertSpec(pubKey.getParams(), false);
return new ECPublicKeyParameters(EC5Util.convertPoint(pubKey.getParams(), pubKey.getW(), false), new ECDomainParameters(s.getCurve(), s.getG(), s.getN(), s.getH(), s.getSeed()));
} else {
// see if we can build a key from key.getEncoded()
try {
byte[] bytes = key.getEncoded();
if (bytes == null) {
throw new InvalidKeyException("no encoding for EC public key");
}
PublicKey publicKey = BouncyCastleProvider.getPublicKey(SubjectPublicKeyInfo.getInstance(bytes));
if (publicKey instanceof java.security.interfaces.ECPublicKey) {
return ECUtil.generatePublicKeyParameter(publicKey);
}
} catch (Exception e) {
throw new InvalidKeyException("cannot identify EC public key: " + e.toString());
}
}
throw new InvalidKeyException("cannot identify EC public key.");
}
use of java.security.PublicKey in project robovm by robovm.
the class ServerHandshakeImpl method unwrap.
/**
* Proceses inbound handshake messages
* @param bytes
*/
@Override
public void unwrap(byte[] bytes) {
io_stream.append(bytes);
while (io_stream.available() > 0) {
int handshakeType;
int length;
io_stream.mark();
try {
handshakeType = io_stream.read();
length = io_stream.readUint24();
if (io_stream.available() < length) {
io_stream.reset();
return;
}
switch(handshakeType) {
case // CLIENT_HELLO
1:
if (clientHello != null && this.status != FINISHED) {
// Client hello has been received during handshake
unexpectedMessage();
return;
}
// if protocol planed to send Hello Request message
// - cancel this demand.
needSendHelloRequest = false;
clientHello = new ClientHello(io_stream, length);
if (nonBlocking) {
delegatedTasks.add(new DelegatedTask(new Runnable() {
public void run() {
processClientHello();
}
}, this));
return;
}
processClientHello();
break;
case // CLIENT CERTIFICATE
11:
if (isResuming || certificateRequest == null || serverHelloDone == null || clientCert != null) {
unexpectedMessage();
return;
}
clientCert = new CertificateMessage(io_stream, length);
if (clientCert.certs.length == 0) {
if (parameters.getNeedClientAuth()) {
fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "HANDSHAKE FAILURE: no client certificate received");
}
} else {
String authType = clientCert.getAuthType();
try {
parameters.getTrustManager().checkClientTrusted(clientCert.certs, authType);
} catch (CertificateException e) {
fatalAlert(AlertProtocol.BAD_CERTIFICATE, "Untrusted Client Certificate ", e);
}
session.peerCertificates = clientCert.certs;
}
break;
case // CERTIFICATE_VERIFY
15:
if (isResuming || clientKeyExchange == null || clientCert == null || //client certificate
clientKeyExchange.isEmpty() || // parameters
certificateVerify != null || changeCipherSpecReceived) {
unexpectedMessage();
return;
}
certificateVerify = new CertificateVerify(io_stream, length);
String authType = clientCert.getAuthType();
DigitalSignature ds = new DigitalSignature(authType);
ds.init(clientCert.certs[0]);
byte[] md5_hash = null;
byte[] sha_hash = null;
if ("RSA".equals(authType)) {
md5_hash = io_stream.getDigestMD5withoutLast();
sha_hash = io_stream.getDigestSHAwithoutLast();
} else if ("DSA".equals(authType)) {
sha_hash = io_stream.getDigestSHAwithoutLast();
// The Signature should be empty in case of anonymous signature algorithm:
// } else if ("DH".equals(authType)) {
}
ds.setMD5(md5_hash);
ds.setSHA(sha_hash);
if (!ds.verifySignature(certificateVerify.signedHash)) {
fatalAlert(AlertProtocol.DECRYPT_ERROR, "DECRYPT ERROR: CERTIFICATE_VERIFY incorrect signature");
}
break;
case // CLIENT_KEY_EXCHANGE
16:
if (isResuming || serverHelloDone == null || clientKeyExchange != null || (clientCert == null && parameters.getNeedClientAuth())) {
unexpectedMessage();
return;
}
if (session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_RSA || session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_RSA_EXPORT) {
clientKeyExchange = new ClientKeyExchange(io_stream, length, serverHello.server_version[1] == 1, true);
Cipher c = null;
try {
c = Cipher.getInstance("RSA/ECB/PKCS1Padding");
c.init(Cipher.UNWRAP_MODE, privKey);
preMasterSecret = c.unwrap(clientKeyExchange.exchange_keys, "preMasterSecret", Cipher.SECRET_KEY).getEncoded();
// check preMasterSecret:
if (preMasterSecret.length != 48 || preMasterSecret[0] != clientHello.client_version[0] || preMasterSecret[1] != clientHello.client_version[1]) {
// incorrect preMasterSecret
// prevent an attack (see TLS 1.0 spec., 7.4.7.1.)
preMasterSecret = new byte[48];
parameters.getSecureRandom().nextBytes(preMasterSecret);
}
} catch (Exception e) {
fatalAlert(AlertProtocol.INTERNAL_ERROR, "INTERNAL ERROR", e);
}
} else {
// diffie hellman key exchange
clientKeyExchange = new ClientKeyExchange(io_stream, length, serverHello.server_version[1] == 1, false);
if (clientKeyExchange.isEmpty()) {
// TODO check that client cert. DH params
// matched server cert. DH params
// client cert. contains fixed DH parameters
preMasterSecret = ((DHPublicKey) clientCert.certs[0].getPublicKey()).getY().toByteArray();
} else {
try {
KeyFactory kf = KeyFactory.getInstance("DH");
KeyAgreement agreement = KeyAgreement.getInstance("DH");
PublicKey clientPublic = kf.generatePublic(new DHPublicKeySpec(new BigInteger(1, clientKeyExchange.exchange_keys), serverKeyExchange.par1, serverKeyExchange.par2));
agreement.init(privKey);
agreement.doPhase(clientPublic, true);
preMasterSecret = agreement.generateSecret();
} catch (Exception e) {
fatalAlert(AlertProtocol.INTERNAL_ERROR, "INTERNAL ERROR", e);
return;
}
}
}
computerMasterSecret();
break;
case // FINISHED
20:
if (!isResuming && !changeCipherSpecReceived) {
unexpectedMessage();
return;
}
clientFinished = new Finished(io_stream, length);
verifyFinished(clientFinished.getData());
session.context = parameters.getServerSessionContext();
parameters.getServerSessionContext().putSession(session);
if (!isResuming) {
sendChangeCipherSpec();
} else {
session.lastAccessedTime = System.currentTimeMillis();
status = FINISHED;
}
break;
default:
unexpectedMessage();
return;
}
} catch (IOException e) {
// io stream dosn't contain complete handshake message
io_stream.reset();
return;
}
}
}
Aggregations