List of usage examples for java.security KeyPair getPublic
public PublicKey getPublic()
From source file:org.candlepin.CRLBenchmark.java
@Setup(Level.Trial) public void buildMassiveCRL() throws Exception { X500Name issuer = new X500Name("CN=Test Issuer"); KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(2048);//from w w w .j a va 2s . co m KeyPair keyPair = generator.generateKeyPair(); Provider bc = new BouncyCastleProvider(); ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider(bc) .build(keyPair.getPrivate()); X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(issuer, new Date()); crlBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(keyPair.getPublic())); /* With a CRL number of 127, incrementing it should cause the number of bytes in the length * portion of the TLV to increase by one.*/ crlBuilder.addExtension(X509Extension.cRLNumber, false, new CRLNumber(new BigInteger("127"))); for (int i = 0; i < 2000000; i++) { crlBuilder.addCRLEntry(new BigInteger(String.valueOf(i)), new Date(), CRLReason.unspecified); } X509CRLHolder holder = crlBuilder.build(signer); X509CRL crl = new JcaX509CRLConverter().setProvider(bc).getCRL(holder); crlFile = File.createTempFile("crl", ".der"); System.out.println("\nWrote test crl to " + crlFile.getAbsolutePath()); FileUtils.writeByteArrayToFile(crlFile, crl.getEncoded()); }
From source file:org.sonatype.sisu.encryptor.RsaAesEncryptor.java
public void generateKeys(OutputStream publicKeyOut, OutputStream privateKeyOut) throws GeneralSecurityException, IOException { KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); generator.initialize(KEY_SIZE * 8, random); KeyPair keyPair = generator.generateKeyPair(); OutputStream privateOut = new Base64OutputStream(privateKeyOut); PrivateKey privateKey = keyPair.getPrivate(); privateOut.write(privateKey.getEncoded()); IOUtil.close(privateOut);/* ww w . j ava 2 s .c o m*/ OutputStream publicOut = new Base64OutputStream(publicKeyOut); PublicKey publicKey = keyPair.getPublic(); publicOut.write(publicKey.getEncoded()); IOUtil.close(publicOut); }
From source file:kr.ac.cau.mecs.cass.processor.SigninProcessor.java
@Override public Signal process(Signal signal) { Signal resignal = new Signal(); resignal.setReceiver(signal.getSender()); resignal.setSender("CASS"); resignal.setAction(new Action(Action.ACT_SIGNIN)); if (signal.getPayload() != null && (signal.getPayload().getPayload() instanceof JSONObjectPayload)) { JSONObject jobj = (JSONObject) signal.getPayload().getPayload().getData(); if (jobj.has("userid") && jobj.has("userpw")) { String userid = jobj.optString("userid"); String userpw = jobj.optString("userpw"); //valid payload DBUserEntity _user = UserEntityDAO.getByUserID(session, userid); if (_user != null && _user.getPassword().equals(userpw)) { //valid credential... JSONObject jres = new JSONObject(); if (_user.getAccessToken() == null) { System.out.println("new token"); _user.setAccessToken(new DBAccessTokenEntity()); _user.getAccessToken().setUser(_user); session.save(_user.getAccessToken()); }/* ww w . j a v a 2s .c o m*/ KeyPair keypair = AccessTokenUtil.generateKeyPair(System.currentTimeMillis()); String usertoken = BCrypt.hashpw(userid, BCrypt.gensalt(12)); String authtoken = AccessTokenUtil.signData(usertoken, keypair.getPrivate()); _user.getAccessToken().setPrivateKey(AccessTokenUtil.encodePrivateKey(keypair.getPrivate())); _user.getAccessToken().setPublicKey(AccessTokenUtil.encodePublicKey(keypair.getPublic())); _user.getAccessToken().setAccessToken(authtoken); _user.getAccessToken().setUserToken(usertoken); jres.putOpt("authToken", authtoken); jres.putOpt("userToken", usertoken); session.update(_user); resignal.setPayload(new Payload(new JSONObjectPayload(jres))); } else { setGenericMessage(resignal, "invalid credential"); } } else { setGenericMessage(resignal, "invalid payload type"); } } else { //inform user invalid payload type setGenericMessage(resignal, "invalid payload type"); } return resignal; }
From source file:org.apache.sshd.client.auth.UserAuthPublicKey.java
public UserAuthPublicKey(ClientSessionImpl session, String username, KeyPair key) throws IOException { try {//from w ww . j a v a 2 s .co m log.info("Send SSH_MSG_USERAUTH_REQUEST for publickey"); Buffer buffer = session.createBuffer(SshConstants.Message.SSH_MSG_USERAUTH_REQUEST, 0); int pos1 = buffer.wpos() - 1; buffer.putString(username); buffer.putString("ssh-connection"); buffer.putString("publickey"); buffer.putByte((byte) 1); buffer.putString( (key.getPublic() instanceof RSAPublicKey) ? KeyPairProvider.SSH_RSA : KeyPairProvider.SSH_DSS); int pos2 = buffer.wpos(); buffer.putPublicKey(key.getPublic()); Signature verif = NamedFactory.Utils.create(session.getFactoryManager().getSignatureFactories(), (key.getPublic() instanceof RSAPublicKey) ? KeyPairProvider.SSH_RSA : KeyPairProvider.SSH_DSS); verif.init(key.getPublic(), key.getPrivate()); Buffer bs = new Buffer(); bs.putString(session.getKex().getH()); bs.putCommand(SshConstants.Message.SSH_MSG_USERAUTH_REQUEST); bs.putString(username); bs.putString("ssh-connection"); bs.putString("publickey"); bs.putByte((byte) 1); bs.putString( (key.getPublic() instanceof RSAPublicKey) ? KeyPairProvider.SSH_RSA : KeyPairProvider.SSH_DSS); bs.putPublicKey(key.getPublic()); verif.update(bs.array(), bs.rpos(), bs.available()); bs = new Buffer(); bs.putString( (key.getPublic() instanceof RSAPublicKey) ? KeyPairProvider.SSH_RSA : KeyPairProvider.SSH_DSS); bs.putBytes(verif.sign()); buffer.putBytes(bs.array(), bs.rpos(), bs.available()); session.writePacket(buffer); } catch (IOException e) { throw e; } catch (Exception e) { throw (IOException) new IOException("Error performing public key authentication").initCause(e); } }
From source file:edu.vt.middleware.crypt.signature.SignatureAlgorithmTest.java
/** * @param signature A crypto signature algorithm to test. * @param keys Public/private key pair used for signing. * @param converter Converter used to convert sig bytes to String. * * @throws Exception On test failure.// w w w . ja v a 2 s.c o m */ @Test(groups = { "functest", "signature" }, dataProvider = "testdata") public void testRandomizedSignVerify(final SignatureAlgorithm signature, final KeyPair keys, final Converter converter) throws Exception { logger.info("Testing randomized signature algorithm " + signature + " with converter " + converter); signature.setRandomProvider(new SecureRandom()); signature.setSignKey(keys.getPrivate()); signature.initSign(); if (converter == null) { final byte[] signedBytes = signature.sign(CLEARTEXT.getBytes()); signature.setVerifyKey(keys.getPublic()); signature.initVerify(); AssertJUnit.assertTrue(signature.verify(CLEARTEXT.getBytes(), signedBytes)); } else { final String sig = signature.sign(CLEARTEXT.getBytes(), converter); signature.setVerifyKey(keys.getPublic()); signature.initVerify(); AssertJUnit.assertTrue(signature.verify(CLEARTEXT.getBytes(), sig, converter)); } }
From source file:org.kaaproject.kaa.client.KaaClientTest.java
protected void initStorageMock(PersistentStorage storage) throws NoSuchAlgorithmException, IOException { KeyPair kp = KeyUtil.generateKeyPair(); Mockito.when(storage.exists(KaaClientProperties.CLIENT_PUBLIC_KEY_NAME_DEFAULT)).thenReturn(true); Mockito.when(storage.exists(KaaClientProperties.CLIENT_PRIVATE_KEY_NAME_DEFAULT)).thenReturn(true); Mockito.when(storage.openForRead(KaaClientProperties.CLIENT_PUBLIC_KEY_NAME_DEFAULT)) .thenReturn(new ByteArrayInputStream(kp.getPublic().getEncoded())); Mockito.when(storage.openForRead(KaaClientProperties.CLIENT_PRIVATE_KEY_NAME_DEFAULT)) .thenReturn(new ByteArrayInputStream(kp.getPrivate().getEncoded())); Mockito.when(storage.openForWrite(Mockito.anyString())).thenReturn(Mockito.mock(OutputStream.class)); }
From source file:org.kde.kdeconnect.NetworkPackageTest.java
public void testEncryption() throws JSONException { NetworkPackage original = new NetworkPackage("com.test"); original.set("hello", "hola"); NetworkPackage copy = NetworkPackage.unserialize(original.serialize()); NetworkPackage decrypted = new NetworkPackage(""); KeyPair keyPair; try {/*from ww w . j a v a 2s . c o m*/ KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048); keyPair = keyGen.genKeyPair(); } catch (Exception e) { e.printStackTrace(); Log.e("KDE/initializeRsaKeys", "Exception"); return; } PrivateKey privateKey = keyPair.getPrivate(); assertNotNull(privateKey); PublicKey publicKey = keyPair.getPublic(); assertNotNull(publicKey); // Encrypt and decrypt np assertEquals(original.getType(), "com.test"); try { NetworkPackage encrypted = RsaHelper.encrypt(original, publicKey); assertEquals(encrypted.getType(), NetworkPackage.PACKAGE_TYPE_ENCRYPTED); decrypted = RsaHelper.decrypt(encrypted, privateKey); assertEquals(decrypted.getType(), "com.test"); } catch (Exception e) { e.printStackTrace(); } // np should be equal to np2 assertEquals(decrypted.getLong("id"), copy.getLong("id")); assertEquals(decrypted.getType(), copy.getType()); assertEquals(decrypted.getJSONArray("body"), copy.getJSONArray("body")); String json = "{\"body\":{\"nowPlaying\":\"A really long song name - A really long artist name\",\"player\":\"A really long player name\",\"the_meaning_of_life_the_universe_and_everything\":\"42\"},\"id\":945945945,\"type\":\"kdeconnect.a_really_really_long_package_type\"}\n"; NetworkPackage longJsonNp = NetworkPackage.unserialize(json); try { NetworkPackage encrypted = RsaHelper.encrypt(longJsonNp, publicKey); decrypted = RsaHelper.decrypt(encrypted, privateKey); String decryptedJson = decrypted.serialize(); JSONAssert.assertEquals(json, decryptedJson, true); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.gluu.oxpush2.u2f.v2.device.U2FKeyImpl.java
@Override public EnrollmentResponse register(EnrollmentRequest enrollmentRequest) throws U2FException { if (BuildConfig.DEBUG) Log.d(TAG, ">> register"); String application = enrollmentRequest.getApplication(); String challenge = enrollmentRequest.getChallenge(); if (BuildConfig.DEBUG) Log.d(TAG, "-- Inputs --"); if (BuildConfig.DEBUG) Log.d(TAG, "application: " + application); if (BuildConfig.DEBUG) Log.d(TAG, "challenge: " + challenge); byte userPresent = userPresenceVerifier.verifyUserPresence(); if ((userPresent & AuthenticateRequest.USER_PRESENT_FLAG) == 0) { throw new U2FException("Cannot verify user presence"); }/*from w w w . j a v a 2 s . c om*/ KeyPair keyPair = keyPairGenerator.generateKeyPair(); byte[] keyHandle = keyPairGenerator.generateKeyHandle(); TokenEntry tokenEntry = new TokenEntry(keyPairGenerator.keyPairToJson(keyPair), enrollmentRequest.getApplication(), enrollmentRequest.getIssuer()); dataStore.storeTokenEntry(keyHandle, tokenEntry); byte[] userPublicKey = keyPairGenerator.encodePublicKey(keyPair.getPublic()); byte[] applicationSha256 = DigestUtils.sha256(application); byte[] challengeSha256 = DigestUtils.sha256(challenge); byte[] signedData = rawMessageCodec.encodeRegistrationSignedBytes(applicationSha256, challengeSha256, keyHandle, userPublicKey); if (BuildConfig.DEBUG) Log.d(TAG, "Signing bytes " + Utils.encodeHexString(signedData)); byte[] signature = keyPairGenerator.sign(signedData, certificatePrivateKey); if (BuildConfig.DEBUG) Log.d(TAG, "-- Outputs --"); if (BuildConfig.DEBUG) Log.d(TAG, "userPublicKey: " + Utils.encodeHexString(userPublicKey)); if (BuildConfig.DEBUG) Log.d(TAG, "keyHandle: " + Utils.base64UrlEncode(keyHandle)); if (BuildConfig.DEBUG) Log.d(TAG, "vendorCertificate: " + vendorCertificate); if (BuildConfig.DEBUG) Log.d(TAG, "signature: " + Utils.encodeHexString(signature)); if (BuildConfig.DEBUG) Log.d(TAG, "<< register"); return new EnrollmentResponse(userPublicKey, keyHandle, vendorCertificate, signature); }
From source file:org.apache.karaf.shell.ssh.keygenerator.OpenSSHGeneratorKeyFileProviderTest.java
@Test public void convertSimpleKey() throws Exception { File temp = File.createTempFile(this.getClass().getCanonicalName(), ".pem"); temp.deleteOnExit();//from w w w.ja v a 2s.c o m SimpleGeneratorHostKeyProvider simpleGenerator = new SimpleGeneratorHostKeyProvider(temp); simpleGenerator.setKeySize(2048); simpleGenerator.setAlgorithm("DSA"); List<KeyPair> keys = simpleGenerator.loadKeys(); KeyPair simpleKeyPair = keys.stream().findFirst().get(); Assert.assertEquals("DSA", simpleKeyPair.getPrivate().getAlgorithm()); OpenSSHKeyPairProvider provider = new OpenSSHKeyPairProvider(temp, "DSA", 2048); KeyPair convertedKeyPair = provider.loadKeys().iterator().next(); Assert.assertEquals("DSA", convertedKeyPair.getPrivate().getAlgorithm()); Assert.assertArrayEquals(simpleKeyPair.getPrivate().getEncoded(), convertedKeyPair.getPrivate().getEncoded()); Assert.assertArrayEquals(simpleKeyPair.getPublic().getEncoded(), convertedKeyPair.getPublic().getEncoded()); //also test that the original file has been replaced PKCS8Key pkcs8 = new PKCS8Key(Files.newInputStream(temp.toPath()), null); KeyPair keyPair = new KeyPair(pkcs8.getPublicKey(), pkcs8.getPrivateKey()); Assert.assertArrayEquals(simpleKeyPair.getPrivate().getEncoded(), keyPair.getPrivate().getEncoded()); }
From source file:org.cesecore.mock.authentication.SimpleAuthenticationProviderSessionBean.java
/** * This is the pug of authentication; loves everybody. *///from w ww. j av a 2 s. c om @Override public AuthenticationToken authenticate(AuthenticationSubject subject) { // A small check if we have added a "fail" credential to the subject. // If we have we will return null, so we can test authentication failure. Set<?> usercredentials = subject.getCredentials(); if ((usercredentials != null) && (usercredentials.size() > 0)) { Object o = usercredentials.iterator().next(); if (o instanceof String) { String str = (String) o; if (StringUtils.equals("fail", str)) { if (log.isDebugEnabled()) { log.debug("Found a 'fail' credential, returning null"); } return null; } } } X509Certificate certificate = null; // If we have a certificate as input, use that, otherwise generate a self signed certificate Set<?> inputcreds = subject.getCredentials(); if (inputcreds != null) { for (Object object : inputcreds) { if (object instanceof X509Certificate) { certificate = (X509Certificate) object; if (log.isDebugEnabled()) { log.debug("Found a certificate credential that we will use, fp=" + CertTools.getFingerprintAsString(certificate)); } } } } // If there was no certificate input, create a self signed if (certificate == null) { if (log.isDebugEnabled()) { log.debug("No certificate input, will create a self-signed one"); } String dn = DEFAULT_DN; // If we have created a subject with an X500Principal we will use this DN to create the dummy certificate. if (subject != null) { Set<Principal> principals = subject.getPrincipals(); if ((principals != null) && (principals.size() > 0)) { Principal p = principals.iterator().next(); if (p instanceof X500Principal) { X500Principal xp = (X500Principal) p; dn = xp.getName(); } } } KeyPair keys = null; try { keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); } catch (InvalidAlgorithmParameterException e) { throw new InvalidAuthenticationTokenException("Could not create authentication token.", e); } try { certificate = CertTools.genSelfCert(dn, 365, null, keys.getPrivate(), keys.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA, true); } catch (CertificateEncodingException e) { throw new CertificateCreationException("Error encountered when creating certificate", e); } catch (IllegalStateException e) { throw new CertificateCreationException("Error encountered when creating certificate", e); } catch (OperatorCreationException e) { throw new CertificateCreationException("Error encountered when creating certificate", e); } catch (CertificateException e) { throw new CertificateCreationException("Error encountered when creating certificate", e); } catch (IOException e) { throw new CertificateCreationException("Error encountered when creating certificate", e); } if (log.isDebugEnabled()) { log.debug("Creates a self signed authentication certificate, fp=" + CertTools.getFingerprintAsString(certificate)); } } // Add the credentials and new principal Set<X509Certificate> credentials = new HashSet<X509Certificate>(); credentials.add(certificate); Set<X500Principal> principals = new HashSet<X500Principal>(); principals.add(certificate.getSubjectX500Principal()); // We cannot use the X509CertificateAuthenticationToken here, since it can only be used internally in a JVM. AuthenticationToken result = new TestX509CertificateAuthenticationToken(principals, credentials); return result; }