List of usage examples for java.security KeyPair getPublic
public PublicKey getPublic()
From source file:org.cesecore.keys.util.KeyTools.java
public static void checkValidKeyLength(String keyspec) throws InvalidKeyException, InvalidAlgorithmParameterException { final String keyAlg = keyspecToKeyalg(keyspec); final int len; if (keyAlg.equals(AlgorithmConstants.KEYALGORITHM_RSA)) { len = Integer.valueOf(keyspec); } else if (keyAlg.equals(AlgorithmConstants.KEYALGORITHM_DSA)) { len = Integer.valueOf(keyspec.substring(3)); } else {//from w w w.j ava2 s .c o m // Assume it's elliptic curve final KeyPair kp = KeyTools.genKeys(keyspec, keyAlg); len = KeyTools.getKeyLength(kp.getPublic()); } checkValidKeyLength(keyAlg, len); }
From source file:org.apache.usergrid.security.ApigeeSSO2ProviderIT.java
@Test public void testMalformedToken() throws Exception { // create keypair KeyPair kp = RsaProvider.generateKeyPair(1024); PublicKey publicKey = kp.getPublic(); // create provider with private key ApigeeSSO2Provider provider = new MockApigeeSSO2Provider(); provider.setManagement(setup.getMgmtSvc()); provider.setPublicKey(publicKey);/*from w w w. ja v a 2 s . co m*/ // test that token is malformed try { provider.getClaims("{;aklsjd;fkajsd;fkjasd;lfkj}"); Assert.fail("Should have failed due to malformed token"); } catch (BadTokenException e) { Assert.assertTrue(e.getCause() instanceof MalformedJwtException); } }
From source file:org.gluu.com.ox_push2.u2f.v2.cert.KeyPairGeneratorImpl.java
public String keyPairToJson(KeyPair keyPair) throws U2FException { ECPrivateKey privateKey = (ECPrivateKey) keyPair.getPrivate(); ECPublicKey publicKey = (ECPublicKey) keyPair.getPublic(); BigInteger x = publicKey.getQ().getAffineXCoord().toBigInteger(); BigInteger y = publicKey.getQ().getAffineYCoord().toBigInteger(); BigInteger d = privateKey.getD(); try {/*from w w w. j a va2 s . c om*/ JSONObject jsonPrivateKey = new JSONObject(); jsonPrivateKey.put("d", Utils.encodeHexString(d.toByteArray())); JSONObject jsonPublicKey = new JSONObject(); jsonPublicKey.put("x", Utils.encodeHexString(x.toByteArray())); jsonPublicKey.put("y", Utils.encodeHexString(y.toByteArray())); JSONObject jsonKeyPair = new JSONObject(); jsonKeyPair.put("privateKey", jsonPrivateKey); jsonKeyPair.put("publicKey", jsonPublicKey); String keyPairJson = jsonKeyPair.toString(); if (BuildConfig.DEBUG) Log.d(TAG, "JSON key pair: " + keyPairJson); return keyPairJson; } catch (JSONException ex) { throw new U2FException("Failed to serialize key pair to JSON", ex); } }
From source file:com.subgraph.vega.internal.http.proxy.ssl.CertificateCreator.java
private void initialize() throws IOException, CertificateException { if (certificateStore.containsCaCertificate()) { caCertificate = certificateStore.getCaCertificate(); caPrivateKey = certificateStore.getCaPrivateKey(); caPublicKey = caCertificate.getPublicKey(); caPemCertificate = createPemCertificate(caCertificate); return;// w w w . j a v a2s. c o m } final KeyPair caKeyPair = keyGenerator.generateKeyPair(); caPublicKey = caKeyPair.getPublic(); caPrivateKey = caKeyPair.getPrivate(); caCertificate = generateCertificate(caSubject, caKeyPair.getPublic(), caSubject, caPublicKey, caPrivateKey, true); certificateStore.saveCaCertificate(caCertificate, caPrivateKey); caPemCertificate = createPemCertificate(caCertificate); }
From source file:org.apache.usergrid.security.ApigeeSSO2ProviderIT.java
@Test public void testBasicOperation() throws Exception { // create keypair KeyPair kp = RsaProvider.generateKeyPair(1024); PublicKey publicKey = kp.getPublic(); PrivateKey privateKey = kp.getPrivate(); // create provider with private key ApigeeSSO2Provider provider = new MockApigeeSSO2Provider(); provider.setManagement(setup.getMgmtSvc()); provider.setPublicKey(publicKey);/* ww w .j a va 2s. co m*/ // create user, claims and a token for those things User user = createUser(); long exp = System.currentTimeMillis() + 10000; Map<String, Object> claims = createClaims(user.getUsername(), user.getEmail(), exp); String token = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.RS256, privateKey).compact(); // test that provider can validate the token, get user, return token info TokenInfo tokenInfo = provider.validateAndReturnTokenInfo(token, 86400L); Assert.assertNotNull(tokenInfo); }
From source file:craterdog.security.RsaAesMessageCryptexTest.java
/** * This test method performs a round-trip session key generation, encryption, signing, * encoding, decoding, signature verification, and decryption tests using the MessageCryptex * class.//from w w w . j a va 2 s. c o m * * @throws IOException */ @Test public void testMessageRoundTrip() throws IOException { logger.info("Testing round trip message encryption..."); logger.info(" Generating the public/private key pairs..."); RsaCertificateManager manager = new RsaCertificateManager(); KeyPair senderPair = manager.generateKeyPair(); PrivateKey senderPrivateKey = senderPair.getPrivate(); PublicKey senderPublicKey = senderPair.getPublic(); KeyPair receiverPair = manager.generateKeyPair(); PrivateKey receiverPrivateKey = receiverPair.getPrivate(); PublicKey receiverPublicKey = receiverPair.getPublic(); logger.info(" Sender generating shared session key..."); SecretKey sessionKey = cryptex.generateSharedKey(); logger.info(" Sender encrypting session key..."); byte[] encryptedSessionKey = cryptex.encryptSharedKey(receiverPublicKey, sessionKey); logger.info(" Sender signing the encrypted session key..."); byte[] signature = cryptex.signBytes(senderPrivateKey, encryptedSessionKey); logger.info(" Sender base 64 encoding the encrypted key and signature..."); String encodedSessionKey = cryptex.encodeBytes(encryptedSessionKey); logger.info(" EncodedSessionKey: " + encodedSessionKey); String encodedSignature = cryptex.encodeBytes(signature); logger.info(" EncodedSignature: " + encodedSignature); logger.info(" Sender encrypting the request using session key..."); String request = "This is a request..."; InputStream clearInput = new ByteArrayInputStream(request.getBytes("UTF-8")); ByteArrayOutputStream encryptedOutput = new ByteArrayOutputStream(); cryptex.encryptStream(sessionKey, clearInput, encryptedOutput); logger.info(" Sender sending the encrypted request to the receiver..."); InputStream encryptedInput = new ByteArrayInputStream(encryptedOutput.toByteArray()); logger.info(" Receiver decoding the encrypted session key and its signature..."); signature = cryptex.decodeString(encodedSignature); encryptedSessionKey = cryptex.decodeString(encodedSessionKey); logger.info(" Receiver validating the signature of the encrypted session key..."); if (!cryptex.bytesAreValid(senderPublicKey, encryptedSessionKey, signature)) { fail("The session key signature was invalid."); } logger.info(" Receiver decrypting the session key..."); sessionKey = cryptex.decryptSharedKey(receiverPrivateKey, encryptedSessionKey); logger.info(" Receiver decrypting the request using the session key..."); ByteArrayOutputStream decryptedOutput = new ByteArrayOutputStream(); cryptex.decryptStream(sessionKey, encryptedInput, decryptedOutput); assertEquals("The decrypted request was different from the original request", request, new String(decryptedOutput.toByteArray())); logger.info(" Receiver handling the request and preparing the response..."); String response = "This is the response..."; logger.info(" Receiver encrypting the response using the session key..."); clearInput = new ByteArrayInputStream(response.getBytes("UTF-8")); encryptedOutput = new ByteArrayOutputStream(); cryptex.encryptStream(sessionKey, clearInput, encryptedOutput); logger.info(" Receiver sending the encrypted response to the sender..."); encryptedInput = new ByteArrayInputStream(encryptedOutput.toByteArray()); logger.info(" Sender decrypting the response using the session key..."); decryptedOutput = new ByteArrayOutputStream(); cryptex.decryptStream(sessionKey, encryptedInput, decryptedOutput); assertEquals("The decrypted response was different from the original response", response, new String(decryptedOutput.toByteArray())); logger.info("Round trip message encryption test completed.\n"); }
From source file:io.getlime.security.powerauth.app.server.service.behavior.ApplicationServiceBehavior.java
/** * Create a new application with given name. * * @param name Application name * @param keyConversionUtilities Utility class for the key conversion * @return Response with new application information *///from w w w . j a va2 s.c om public CreateApplicationResponse createApplication(String name, CryptoProviderUtil keyConversionUtilities) { ApplicationEntity application = new ApplicationEntity(); application.setName(name); application = applicationRepository.save(application); KeyGenerator keyGen = new KeyGenerator(); KeyPair kp = keyGen.generateKeyPair(); PrivateKey privateKey = kp.getPrivate(); PublicKey publicKey = kp.getPublic(); // Generate the default master key pair MasterKeyPairEntity keyPair = new MasterKeyPairEntity(); keyPair.setApplication(application); keyPair.setMasterKeyPrivateBase64( BaseEncoding.base64().encode(keyConversionUtilities.convertPrivateKeyToBytes(privateKey))); keyPair.setMasterKeyPublicBase64( BaseEncoding.base64().encode(keyConversionUtilities.convertPublicKeyToBytes(publicKey))); keyPair.setTimestampCreated(new Date()); keyPair.setName(name + " Default Keypair"); masterKeyPairRepository.save(keyPair); // Create the default application version byte[] applicationKeyBytes = keyGen.generateRandomBytes(16); byte[] applicationSecretBytes = keyGen.generateRandomBytes(16); ApplicationVersionEntity version = new ApplicationVersionEntity(); version.setApplication(application); version.setName("default"); version.setSupported(true); version.setApplicationKey(BaseEncoding.base64().encode(applicationKeyBytes)); version.setApplicationSecret(BaseEncoding.base64().encode(applicationSecretBytes)); applicationVersionRepository.save(version); CreateApplicationResponse response = new CreateApplicationResponse(); response.setApplicationId(application.getId()); response.setApplicationName(application.getName()); return response; }
From source file:ie.peternagy.jcrypto.algo.EllipticCurveWrapper.java
/** * Generate a set of Elliptic Curve keys *//*w w w .j ava 2 s . co m*/ public void generateKeys() { tryLoadKeys(); if (isInitialized(true) && isInitialized(false)) { return; } try { ECGenParameterSpec ecGenSpec = new ECGenParameterSpec(EC_CURVE); KeyPairGenerator g = KeyPairGenerator.getInstance(ALGORITHM_NAME); g.initialize(ecGenSpec, CryptoSecurityUtil.getSecureRandom()); KeyPair pair = g.generateKeyPair(); privateKey = pair.getPrivate(); publicKey = pair.getPublic(); writeKeys(); } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException ex) { Logger.getLogger(EllipticCurveWrapper.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:org.apache.usergrid.security.ApigeeSSO2ProviderIT.java
@Test public void testExpiredToken() throws Exception { // create keypair KeyPair kp = RsaProvider.generateKeyPair(1024); PublicKey publicKey = kp.getPublic(); PrivateKey privateKey = kp.getPrivate(); // create provider with private key ApigeeSSO2Provider provider = new MockApigeeSSO2Provider(); provider.setManagement(setup.getMgmtSvc()); provider.setPublicKey(publicKey);//from w w w.j a va 2s .c o m // create user, claims and a token for those things User user = createUser(); long exp = System.currentTimeMillis() - 1500; Map<String, Object> claims = createClaims(user.getUsername(), user.getEmail(), exp); String token = Jwts.builder().setClaims(claims).setExpiration(new Date()) .signWith(SignatureAlgorithm.RS256, privateKey).compact(); Thread.sleep(500); // wait for claims to timeout // test that token is expired try { provider.validateAndReturnTokenInfo(token, 86400L); Assert.fail("Should have failed due to expired token"); } catch (BadTokenException e) { Assert.assertTrue(e.getCause() instanceof ExpiredJwtException); } }
From source file:org.apache.usergrid.security.ApigeeSSO2ProviderIT.java
@Test public void testBadSignature() throws Exception { // create old keypair KeyPair kp = RsaProvider.generateKeyPair(1024); PublicKey publicKey = kp.getPublic(); PrivateKey privateKey = kp.getPrivate(); // create new keypair KeyPair kpNew = RsaProvider.generateKeyPair(1024); PrivateKey privateKeyNew = kpNew.getPrivate(); // create mock provider with old public key ApigeeSSO2Provider provider = new MockApigeeSSO2ProviderNewKey(publicKey, publicKey); provider.setManagement(setup.getMgmtSvc()); // create user, claims and a token for those things. Sign with new public key User user = createUser();/*from w w w .j av a 2s .c o m*/ long exp = System.currentTimeMillis() + 10000; Map<String, Object> claims = createClaims(user.getUsername(), user.getEmail(), exp); String token = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.RS256, privateKeyNew).compact(); // test that signature exception thrown try { provider.validateAndReturnTokenInfo(token, 86400L); Assert.fail("Should have failed due to bad signature"); } catch (BadTokenException e) { Assert.assertTrue(e.getCause() instanceof SignatureException); } }