use of java.security.interfaces.RSAPublicKey in project wycheproof by google.
the class RsaSignatureTest method testBasic.
public void testBasic() throws Exception {
String algorithm = "SHA256WithRSA";
String hashAlgorithm = "SHA-256";
String message = "Hello";
int keysize = 2048;
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(keysize);
KeyPair keyPair = keyGen.generateKeyPair();
RSAPublicKey pub = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey priv = (RSAPrivateKey) keyPair.getPrivate();
byte[] messageBytes = message.getBytes("UTF-8");
Signature signer = Signature.getInstance(algorithm);
Signature verifier = Signature.getInstance(algorithm);
signer.initSign(priv);
signer.update(messageBytes);
byte[] signature = signer.sign();
verifier.initVerify(pub);
verifier.update(messageBytes);
assertTrue(verifier.verify(signature));
// Extract some parameters.
byte[] rawHash = MessageDigest.getInstance(hashAlgorithm).digest(messageBytes);
// Print keys and signature, so that it can be used to generate new test vectors.
System.out.println("Message:" + message);
System.out.println("Hash:" + TestUtil.bytesToHex(rawHash));
System.out.println("Public key:");
System.out.println("Modulus:" + pub.getModulus().toString());
System.out.println("E:" + pub.getPublicExponent().toString());
System.out.println("encoded:" + TestUtil.bytesToHex(pub.getEncoded()));
System.out.println("Private key:");
System.out.println("D:" + priv.getPrivateExponent().toString());
System.out.println("encoded:" + TestUtil.bytesToHex(priv.getEncoded()));
System.out.println("Signature:" + TestUtil.bytesToHex(signature));
}
use of java.security.interfaces.RSAPublicKey in project XobotOS by xamarin.
the class ServerHandshakeImpl method processClientHello.
/**
*
* Processes Client Hello message.
* Server responds to client hello message with server hello
* and (if necessary) server certificate, server key exchange,
* certificate request, and server hello done messages.
*/
void processClientHello() {
CipherSuite cipher_suite;
// check that clientHello contains CompressionMethod.null
checkCompression: {
for (int i = 0; i < clientHello.compression_methods.length; i++) {
if (clientHello.compression_methods[i] == 0) {
break checkCompression;
}
}
fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "HANDSHAKE FAILURE. Incorrect client hello message");
}
if (!ProtocolVersion.isSupported(clientHello.client_version)) {
fatalAlert(AlertProtocol.PROTOCOL_VERSION, "PROTOCOL VERSION. Unsupported client version " + clientHello.client_version[0] + clientHello.client_version[1]);
}
isResuming = false;
FIND: if (clientHello.session_id.length != 0) {
// client wishes to reuse session
SSLSessionImpl sessionToResume;
boolean reuseCurrent = false;
// reuse current session
if (session != null && Arrays.equals(session.id, clientHello.session_id)) {
if (session.isValid()) {
isResuming = true;
break FIND;
}
reuseCurrent = true;
}
// find session in cash
sessionToResume = findSessionToResume(clientHello.session_id);
if (sessionToResume == null || !sessionToResume.isValid()) {
if (!parameters.getEnableSessionCreation()) {
if (reuseCurrent) {
// we can continue current session
sendWarningAlert(AlertProtocol.NO_RENEGOTIATION);
status = NOT_HANDSHAKING;
clearMessages();
return;
}
// throw AlertException
fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "SSL Session may not be created");
}
session = null;
} else {
session = (SSLSessionImpl) sessionToResume.clone();
isResuming = true;
}
}
if (isResuming) {
cipher_suite = session.cipherSuite;
// clientHello.cipher_suites must include at least cipher_suite from the session
checkCipherSuite: {
for (int i = 0; i < clientHello.cipher_suites.length; i++) {
if (cipher_suite.equals(clientHello.cipher_suites[i])) {
break checkCipherSuite;
}
}
fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "HANDSHAKE FAILURE. Incorrect client hello message");
}
} else {
cipher_suite = selectSuite(clientHello.cipher_suites);
if (cipher_suite == null) {
fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "HANDSHAKE FAILURE. NO COMMON SUITE");
}
if (!parameters.getEnableSessionCreation()) {
fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "SSL Session may not be created");
}
session = new SSLSessionImpl(cipher_suite, parameters.getSecureRandom());
if (engineOwner != null) {
session.setPeer(engineOwner.getPeerHost(), engineOwner.getPeerPort());
} else {
session.setPeer(socketOwner.getInetAddress().getHostName(), socketOwner.getPort());
}
}
recordProtocol.setVersion(clientHello.client_version);
session.protocol = ProtocolVersion.getByVersion(clientHello.client_version);
session.clientRandom = clientHello.random;
// create server hello message
serverHello = new ServerHello(parameters.getSecureRandom(), clientHello.client_version, session.getId(), cipher_suite, //CompressionMethod.null
(byte) 0);
session.serverRandom = serverHello.random;
send(serverHello);
if (isResuming) {
sendChangeCipherSpec();
return;
}
// create and send server certificate message if needed
if (!cipher_suite.isAnonymous()) {
// need to send server certificate
X509Certificate[] certs = null;
String certType = cipher_suite.getServerKeyType();
if (certType == null) {
fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "NO CERT TYPE FOR " + cipher_suite.getName());
}
// obtain certificates from key manager
String alias = null;
X509KeyManager km = parameters.getKeyManager();
if (km instanceof X509ExtendedKeyManager) {
X509ExtendedKeyManager ekm = (X509ExtendedKeyManager) km;
if (this.socketOwner != null) {
alias = ekm.chooseServerAlias(certType, null, this.socketOwner);
} else {
alias = ekm.chooseEngineServerAlias(certType, null, this.engineOwner);
}
if (alias != null) {
certs = ekm.getCertificateChain(alias);
}
} else {
alias = km.chooseServerAlias(certType, null, this.socketOwner);
if (alias != null) {
certs = km.getCertificateChain(alias);
}
}
if (certs == null) {
fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "NO SERVER CERTIFICATE FOUND");
return;
}
session.localCertificates = certs;
serverCert = new CertificateMessage(certs);
privKey = km.getPrivateKey(alias);
send(serverCert);
}
// create and send server key exchange message if needed
RSAPublicKey rsakey = null;
DHPublicKeySpec dhkeySpec = null;
byte[] hash = null;
BigInteger p = null;
BigInteger g = null;
KeyPairGenerator kpg = null;
try {
if (cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_RSA_EXPORT) {
PublicKey pk = serverCert.certs[0].getPublicKey();
if (getRSAKeyLength(pk) > 512) {
// key is longer than 512 bits
kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(512);
}
} else if (cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_DHE_DSS || cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_DHE_DSS_EXPORT || cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_DHE_RSA || cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_DHE_RSA_EXPORT || cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_DH_anon || cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_DH_anon_EXPORT) {
kpg = KeyPairGenerator.getInstance("DH");
p = new BigInteger(1, DHParameters.getPrime());
g = new BigInteger("2");
DHParameterSpec spec = new DHParameterSpec(p, g);
kpg.initialize(spec);
}
} catch (Exception e) {
fatalAlert(AlertProtocol.INTERNAL_ERROR, "INTERNAL ERROR", e);
}
if (kpg != null) {
// need to send server key exchange message
DigitalSignature ds = new DigitalSignature(cipher_suite.authType);
KeyPair kp = null;
try {
kp = kpg.genKeyPair();
if (cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_RSA_EXPORT) {
rsakey = (RSAPublicKey) kp.getPublic();
} else {
DHPublicKey dhkey = (DHPublicKey) kp.getPublic();
KeyFactory kf = KeyFactory.getInstance("DH");
dhkeySpec = kf.getKeySpec(dhkey, DHPublicKeySpec.class);
}
if (!cipher_suite.isAnonymous()) {
// calculate signed_params
// init by private key which correspond to
// server certificate
ds.init(privKey);
// use emphemeral key for key exchange
privKey = kp.getPrivate();
ds.update(clientHello.getRandom());
ds.update(serverHello.getRandom());
byte[] tmp;
byte[] tmpLength = new byte[2];
//FIXME 1_byte==0x00
if (cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_RSA_EXPORT) {
tmp = ServerKeyExchange.toUnsignedByteArray(rsakey.getModulus());
tmpLength[0] = (byte) ((tmp.length & 0xFF00) >>> 8);
tmpLength[1] = (byte) (tmp.length & 0xFF);
ds.update(tmpLength);
ds.update(tmp);
tmp = ServerKeyExchange.toUnsignedByteArray(rsakey.getPublicExponent());
tmpLength[0] = (byte) ((tmp.length & 0xFF00) >>> 8);
tmpLength[1] = (byte) (tmp.length & 0xFF);
ds.update(tmpLength);
ds.update(tmp);
} else {
tmp = ServerKeyExchange.toUnsignedByteArray(dhkeySpec.getP());
tmpLength[0] = (byte) ((tmp.length & 0xFF00) >>> 8);
tmpLength[1] = (byte) (tmp.length & 0xFF);
ds.update(tmpLength);
ds.update(tmp);
tmp = ServerKeyExchange.toUnsignedByteArray(dhkeySpec.getG());
tmpLength[0] = (byte) ((tmp.length & 0xFF00) >>> 8);
tmpLength[1] = (byte) (tmp.length & 0xFF);
ds.update(tmpLength);
ds.update(tmp);
tmp = ServerKeyExchange.toUnsignedByteArray(dhkeySpec.getY());
tmpLength[0] = (byte) ((tmp.length & 0xFF00) >>> 8);
tmpLength[1] = (byte) (tmp.length & 0xFF);
ds.update(tmpLength);
ds.update(tmp);
}
hash = ds.sign();
} else {
// use emphemeral key for key exchange
privKey = kp.getPrivate();
}
} catch (Exception e) {
fatalAlert(AlertProtocol.INTERNAL_ERROR, "INTERNAL ERROR", e);
}
if (cipher_suite.keyExchange == CipherSuite.KEY_EXCHANGE_RSA_EXPORT) {
serverKeyExchange = new ServerKeyExchange(rsakey.getModulus(), rsakey.getPublicExponent(), null, hash);
} else {
serverKeyExchange = new ServerKeyExchange(p, g, dhkeySpec.getY(), hash);
}
send(serverKeyExchange);
}
// CERTIFICATE_REQUEST
certRequest: if (parameters.getWantClientAuth() || parameters.getNeedClientAuth()) {
X509Certificate[] accepted;
try {
X509TrustManager tm = parameters.getTrustManager();
accepted = tm.getAcceptedIssuers();
} catch (ClassCastException e) {
// don't send certificateRequest
break certRequest;
}
byte[] requestedClientCertTypes = { CipherSuite.TLS_CT_RSA_SIGN, CipherSuite.TLS_CT_DSS_SIGN };
certificateRequest = new CertificateRequest(requestedClientCertTypes, accepted);
send(certificateRequest);
}
// SERVER_HELLO_DONE
serverHelloDone = new ServerHelloDone();
send(serverHelloDone);
status = NEED_UNWRAP;
}
use of java.security.interfaces.RSAPublicKey in project android_frameworks_base by DirtyUnicorns.
the class AndroidKeyPairGeneratorTest method assertKeyPairCorrect.
private void assertKeyPairCorrect(KeyPair pair, String alias, String keyType, int keySize, AlgorithmParameterSpec spec, X500Principal dn, BigInteger serial, Date start, Date end) throws Exception {
final PublicKey pubKey = pair.getPublic();
assertNotNull("The PublicKey for the KeyPair should be not null", pubKey);
assertEquals(keyType, pubKey.getAlgorithm());
if ("EC".equalsIgnoreCase(keyType)) {
assertEquals("Curve should be what was specified during initialization", keySize, ((ECPublicKey) pubKey).getParams().getCurve().getField().getFieldSize());
} else if ("RSA".equalsIgnoreCase(keyType)) {
RSAPublicKey rsaPubKey = (RSAPublicKey) pubKey;
assertEquals("Modulus size should be what is specified during initialization", (keySize + 7) & ~7, (rsaPubKey.getModulus().bitLength() + 7) & ~7);
if (spec != null) {
RSAKeyGenParameterSpec params = (RSAKeyGenParameterSpec) spec;
assertEquals((keySize + 7) & ~7, (params.getKeysize() + 7) & ~7);
assertEquals(params.getPublicExponent(), rsaPubKey.getPublicExponent());
}
}
final PrivateKey privKey = pair.getPrivate();
assertNotNull("The PrivateKey for the KeyPair should be not null", privKey);
assertEquals(keyType, privKey.getAlgorithm());
if ("EC".equalsIgnoreCase(keyType)) {
assertTrue("EC private key must be instanceof ECKey: " + privKey.getClass().getName(), privKey instanceof ECKey);
assertEquals("Private and public key must have the same EC parameters", ((ECKey) pubKey).getParams(), ((ECKey) privKey).getParams());
} else if ("RSA".equalsIgnoreCase(keyType)) {
assertTrue("RSA private key must be instance of RSAKey: " + privKey.getClass().getName(), privKey instanceof RSAKey);
assertEquals("Private and public key must have the same RSA modulus", ((RSAKey) pubKey).getModulus(), ((RSAKey) privKey).getModulus());
}
final byte[] userCertBytes = mAndroidKeyStore.get(Credentials.USER_CERTIFICATE + alias);
assertNotNull("The user certificate should exist for the generated entry", userCertBytes);
final CertificateFactory cf = CertificateFactory.getInstance("X.509");
final Certificate userCert = cf.generateCertificate(new ByteArrayInputStream(userCertBytes));
assertTrue("Certificate should be in X.509 format", userCert instanceof X509Certificate);
final X509Certificate x509userCert = (X509Certificate) userCert;
assertEquals("Public key used to sign certificate should have the same algorithm as in KeyPair", pubKey.getAlgorithm(), x509userCert.getPublicKey().getAlgorithm());
assertEquals("PublicKey used to sign certificate should match one returned in KeyPair", pubKey, AndroidKeyStoreProvider.getAndroidKeyStorePublicKey(Credentials.USER_PRIVATE_KEY + alias, KeyStore.UID_SELF, x509userCert.getPublicKey().getAlgorithm(), x509userCert.getPublicKey().getEncoded()));
assertEquals("The Subject DN should be the one passed into the params", dn, x509userCert.getSubjectDN());
assertEquals("The Issuer DN should be the same as the Subject DN", dn, x509userCert.getIssuerDN());
assertEquals("The Serial should be the one passed into the params", serial, x509userCert.getSerialNumber());
assertDateEquals("The notBefore date should be the one passed into the params", start, x509userCert.getNotBefore());
assertDateEquals("The notAfter date should be the one passed into the params", end, x509userCert.getNotAfter());
// Assert that the cert's signature verifies using the public key from generated KeyPair
x509userCert.verify(pubKey);
// Assert that the cert's signature verifies using the public key from the cert itself.
x509userCert.verify(x509userCert.getPublicKey());
final byte[] caCerts = mAndroidKeyStore.get(Credentials.CA_CERTIFICATE + alias);
assertNull("A list of CA certificates should not exist for the generated entry", caCerts);
ExportResult exportResult = mAndroidKeyStore.exportKey(Credentials.USER_PRIVATE_KEY + alias, KeymasterDefs.KM_KEY_FORMAT_X509, null, null);
assertEquals(KeyStore.NO_ERROR, exportResult.resultCode);
final byte[] pubKeyBytes = exportResult.exportData;
assertNotNull("The keystore should return the public key for the generated key", pubKeyBytes);
assertTrue("Public key X.509 format should be as expected", Arrays.equals(pubKey.getEncoded(), pubKeyBytes));
}
use of java.security.interfaces.RSAPublicKey in project jdk8u_jdk by JetBrains.
the class NewSize7 method main.
public static void main(String[] args) throws Exception {
String FILE = "newsize7-ks";
new File(FILE).delete();
sun.security.tools.keytool.Main.main(("-debug -genkeypair -keystore " + FILE + " -alias a -dname cn=c -storepass changeit" + " -keypass changeit -keyalg rsa").split(" "));
KeyStore ks = KeyStore.getInstance("JKS");
try (FileInputStream fin = new FileInputStream(FILE)) {
ks.load(fin, null);
}
Files.delete(Paths.get(FILE));
RSAPublicKey r = (RSAPublicKey) ks.getCertificate("a").getPublicKey();
if (r.getModulus().bitLength() != 2048) {
throw new Exception("Bad keysize");
}
X509Certificate x = (X509Certificate) ks.getCertificate("a");
if (!x.getSigAlgName().equals("SHA256withRSA")) {
throw new Exception("Bad sigalg");
}
}
use of java.security.interfaces.RSAPublicKey in project jdk8u_jdk by JetBrains.
the class SpecTest method specTest.
/**
*
* @param kpair test key pair
* @param pubExponent expected public exponent.
* @return true if test passed. false if test failed.
*/
private static boolean specTest(KeyPair kpair, BigInteger pubExponent) {
boolean passed = true;
RSAPrivateKey priv = (RSAPrivateKey) kpair.getPrivate();
RSAPublicKey pub = (RSAPublicKey) kpair.getPublic();
// test the getModulus method
if ((priv instanceof RSAKey) && (pub instanceof RSAKey)) {
if (!priv.getModulus().equals(pub.getModulus())) {
System.err.println("priv.getModulus() = " + priv.getModulus());
System.err.println("pub.getModulus() = " + pub.getModulus());
passed = false;
}
if (!pubExponent.equals(pub.getPublicExponent())) {
System.err.println("pubExponent = " + pubExponent);
System.err.println("pub.getPublicExponent() = " + pub.getPublicExponent());
passed = false;
}
}
return passed;
}
Aggregations