List of usage examples for java.security KeyPair getPrivate
public PrivateKey getPrivate()
From source file:net.padlocksoftware.padlock.validator.ValidatorTest.java
License:asdf
@Test public void testExpiredFloat() throws Exception { KeyPair pair = KeyManager.createKeyPair(); License license = LicenseFactory.createLicense(); license.setFloatingExpirationPeriod(1L); LicenseSigner signer = LicenseSigner.createLicenseSigner((DSAPrivateKey) pair.getPrivate()); signer.sign(license);// w w w . j av a 2 s . c om String key = new String(Hex.encodeHex(pair.getPublic().getEncoded())); Validator validator = new Validator(license, key); validator.validate(); boolean ex = false; try { validator.validate(); } catch (ValidatorException e) { ex = true; } assertTrue(ex); }
From source file:com.sshtools.j2ssh.transport.kex.DhGroup1Sha1.java
/** * * * @param clientId/*from w ww . ja v a2 s .com*/ * @param serverId * @param clientKexInit * @param serverKexInit * * @throws IOException * @throws AlgorithmOperationException * @throws KeyExchangeException */ public void performClientExchange(String clientId, String serverId, byte[] clientKexInit, byte[] serverKexInit, boolean firstPacketFollows, boolean useFirstPacket, boolean firstExch // ignored ) throws IOException { log.info("Starting client side key exchange."); transport.getMessageStore().registerMessage(SshMsgKexDhInit.SSH_MSG_KEXDH_INIT, SshMsgKexDhInit.class); transport.getMessageStore().registerMessage(SshMsgKexDhReply.SSH_MSG_KEXDH_REPLY, SshMsgKexDhReply.class); this.clientId = clientId; this.serverId = serverId; this.clientKexInit = clientKexInit; this.serverKexInit = serverKexInit; //int minBits = g.bitLength(); //int maxBits = q.bitLength(); //Random rnd = ConfigurationLoader.getRND(); // Generate a random bit count for the random x value /*int genBits = (int) ( ( (maxBits - minBits + 1) * rnd.nextFloat()) + minBits); x = new BigInteger(genBits, rnd); // Calculate e e = g.modPow(x, p);*/ try { DHParameterSpec dhSkipParamSpec = new DHParameterSpec(p, g); dhKeyPairGen.initialize(dhSkipParamSpec); KeyPair dhKeyPair = dhKeyPairGen.generateKeyPair(); dhKeyAgreement.init(dhKeyPair.getPrivate()); x = ((DHPrivateKey) dhKeyPair.getPrivate()).getX(); e = ((DHPublicKey) dhKeyPair.getPublic()).getY(); } catch (InvalidKeyException ex) { throw new AlgorithmOperationException("Failed to generate DH value"); } catch (InvalidAlgorithmParameterException ex) { throw new AlgorithmOperationException("Failed to generate DH value"); } // Prepare the message SshMsgKexDhInit msg = new SshMsgKexDhInit(e); // Send it try { transport.sendMessage(msg, this); } catch (SshException tpe) { throw new KeyExchangeException("Failed to send key exchange initailaztion message"); } int[] messageId = new int[1]; messageId[0] = SshMsgKexDhReply.SSH_MSG_KEXDH_REPLY; SshMsgKexDhReply reply = (SshMsgKexDhReply) transport.readMessage(messageId); hostKey = reply.getHostKey(); signature = reply.getSignature(); f = reply.getF(); // Calculate diffe hellman k value secret = f.modPow(x, p); // Calculate the exchange hash calculateExchangeHash(); }
From source file:com.sshtools.j2ssh.transport.kex.DhGroup1Sha1.java
/** * * * @param clientId/*from w w w .j a va 2 s. c o m*/ * @param serverId * @param clientKexInit * @param serverKexInit * @param prvKey * * @throws IOException * @throws KeyExchangeException */ public void performServerExchange(String clientId, String serverId, byte[] clientKexInit, byte[] serverKexInit, SshPrivateKey prvKey, boolean firstPacketFollows, boolean useFirstPacket) throws IOException { try { this.clientId = clientId; this.serverId = serverId; this.clientKexInit = clientKexInit; this.serverKexInit = serverKexInit; /*int minBits = g.bitLength(); int maxBits = q.bitLength(); Random rnd = ConfigurationLoader.getRND(); // Generate a random bit count for the random x value int genBits = (int) ( ( (maxBits - minBits + 1) * rnd.nextFloat()) + minBits); y = new BigInteger(genBits, rnd);*/ try { DHParameterSpec dhSkipParamSpec = new DHParameterSpec(p, g); dhKeyPairGen.initialize(dhSkipParamSpec); KeyPair dhKeyPair = dhKeyPairGen.generateKeyPair(); dhKeyAgreement.init(dhKeyPair.getPrivate()); y = ((DHPrivateKey) dhKeyPair.getPrivate()).getX(); f = ((DHPublicKey) dhKeyPair.getPublic()).getY(); } catch (InvalidKeyException ex) { throw new AlgorithmOperationException("Failed to generate DH y value"); } catch (InvalidAlgorithmParameterException ex) { throw new AlgorithmOperationException("Failed to generate DH y value"); } // Calculate f //f = g.modPow(y, p); // Wait for the e value and calculate the other parameters int[] messageId = new int[1]; messageId[0] = SshMsgKexDhInit.SSH_MSG_KEXDH_INIT; SshMsgKexDhInit msg = (SshMsgKexDhInit) transport.readMessage(messageId); if (firstPacketFollows && !useFirstPacket) { // Ignore the first packet since the guess was incorrect msg = (SshMsgKexDhInit) transport.readMessage(messageId); } e = msg.getE(); // Calculate k secret = e.modPow(y, p); hostKey = prvKey.getPublicKey().getEncoded(); calculateExchangeHash(); signature = prvKey.generateSignature(exchangeHash); SshMsgKexDhReply reply = new SshMsgKexDhReply(hostKey, f, signature); transport.sendMessage(reply, this); } catch (SshException e) { throw new KeyExchangeException(e.getMessage()); } }
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.//from ww w. j a v a 2s .co 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.apache.accumulo.test.util.CertUtils.java
public void createSelfSignedCert(File targetKeystoreFile, String keyName, String keystorePassword) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException, OperatorCreationException, AccumuloSecurityException, NoSuchProviderException { if (targetKeystoreFile.exists()) { throw new FileExistsException(targetKeystoreFile); }/*w ww . j a v a 2s . c om*/ KeyPair kp = generateKeyPair(); X509CertificateObject cert = generateCert(keyName, kp, true, kp.getPublic(), kp.getPrivate()); char[] password = keystorePassword.toCharArray(); KeyStore keystore = KeyStore.getInstance(keystoreType); keystore.load(null, null); keystore.setCertificateEntry(keyName + "Cert", cert); keystore.setKeyEntry(keyName + "Key", kp.getPrivate(), password, new Certificate[] { cert }); try (FileOutputStream fos = new FileOutputStream(targetKeystoreFile)) { keystore.store(fos, password); } }
From source file:org.apache.usergrid.security.ApigeeSSO2ProviderIT.java
@Test public void testNewPublicKeyFetch() 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); PublicKey publicKeyNew = kpNew.getPublic(); PrivateKey privateKeyNew = kpNew.getPrivate(); // create mock provider with old and old key MockApigeeSSO2ProviderNewKey provider = new MockApigeeSSO2ProviderNewKey(publicKey, publicKeyNew); provider.setManagement(setup.getMgmtSvc()); // create user, claims and a token for those things. Sign with new public key User user = createUser();/*ww w. j a v 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 provider can validate the token, get user, return token info TokenInfo tokenInfo = provider.validateAndReturnTokenInfo(token, 86400L); Assert.assertNotNull(tokenInfo); // assert that provider called for new key Assert.assertTrue(provider.isGetPublicKeyCalled()); // try it again, but this time it should fail due to freshness value provider.setPublicKey(publicKey); // set old key // 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); } }
From source file:com.owncloud.android.util.EncryptionTestIT.java
@Test public void encryptPrivateKey() throws Exception { String keyPhrase = "moreovertelevisionfactorytendencyindependenceinternationalintellectualimpress" + "interestvolunteer"; KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(4096, new SecureRandom()); KeyPair keyPair = keyGen.generateKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); byte[] privateKeyBytes = privateKey.getEncoded(); String privateKeyString = EncryptionUtils.encodeBytesToBase64String(privateKeyBytes); String encryptedString = EncryptionUtils.encryptPrivateKey(privateKeyString, keyPhrase); String decryptedString = EncryptionUtils.decryptPrivateKey(encryptedString, keyPhrase); assertEquals(privateKeyString, decryptedString); }
From source file:net.padlocksoftware.padlock.validator.ValidatorTest.java
License:asdf
@Test public void testPrior() throws Exception { KeyPair pair = KeyManager.createKeyPair(); License license = LicenseFactory.createLicense(); license.setStartDate(new Date(System.currentTimeMillis() + 20000L)); LicenseSigner signer = LicenseSigner.createLicenseSigner((DSAPrivateKey) pair.getPrivate()); signer.sign(license);//w w w . j av a 2 s . com String key = new String(Hex.encodeHex(pair.getPublic().getEncoded())); Validator validator = new Validator(license, key); boolean ex = false; try { validator.validate(); } catch (ValidatorException e) { ex = true; } assertTrue(ex); }
From source file:net.firejack.platform.web.security.x509.KeyUtils.java
public static X509Certificate generateCertificate(String domain, int days, KeyPair keyPair) throws GeneralSecurityException, IOException { X509CertInfo info = new X509CertInfo(); Date from = new Date(); Date to = new Date(from.getTime() + days * 86400000l); CertificateValidity interval = new CertificateValidity(from, to); BigInteger sn = new BigInteger(64, new SecureRandom()); X500Name owner = new X500Name("DC=" + domain); info.set(X509CertInfo.VALIDITY, interval); info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn)); info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(owner)); info.set(X509CertInfo.ISSUER, new CertificateIssuerName(owner)); info.set(X509CertInfo.KEY, new CertificateX509Key(keyPair.getPublic())); info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3)); AlgorithmId algo = new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid); info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algo)); X509CertImpl cert = new X509CertImpl(info); cert.sign(keyPair.getPrivate(), "MD5WithRSA"); return cert;/*w w w . j ava 2s. c om*/ }