List of usage examples for java.security KeyPair getPublic
public PublicKey getPublic()
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);//from w w w.j av a2 s .c o m 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:com.owncloud.android.util.EncryptionTestIT.java
@Test public void generateCSR() throws Exception { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048, new SecureRandom()); KeyPair keyPair = keyGen.generateKeyPair(); assertFalse(CsrHelper.generateCsrPemEncodedString(keyPair, "").isEmpty()); assertFalse(EncryptionUtils.encodeBytesToBase64String(keyPair.getPublic().getEncoded()).isEmpty()); }
From source file:org.dasein.cloud.test.identity.IdentityResources.java
/** * @link http://stackoverflow.com/a/14582408/211197 * @return Encoded generated public key/* w w w .j a v a2 s. c o m*/ */ private @Nullable String generateKey() { KeyPairGenerator generator; try { generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(2048); KeyPair keyPair = generator.genKeyPair(); RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic(); ByteArrayOutputStream byteOs = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(byteOs); dos.writeInt("ssh-rsa".getBytes().length); dos.write("ssh-rsa".getBytes()); dos.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length); dos.write(rsaPublicKey.getPublicExponent().toByteArray()); dos.writeInt(rsaPublicKey.getModulus().toByteArray().length); dos.write(rsaPublicKey.getModulus().toByteArray()); String publicKeyEncoded = new String(Base64.encodeBase64(byteOs.toByteArray())); return "ssh-rsa " + publicKeyEncoded + " dasein"; } catch (Throwable e) { return null; } }
From source file:com.sshtools.j2ssh.transport.kex.DhGroup1Sha1.java
/** * * * @param clientId//w w w .java 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 w w w .j a v a 2 s . c om*/ */ @Test(groups = { "functest", "signature" }, dataProvider = "testdata") public void testSignVerify(final SignatureAlgorithm signature, final KeyPair keys, final Converter converter) throws Exception { logger.info("Testing signature algorithm " + signature + " with converter " + converter); 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:com.microsoft.azure.keyvault.cryptography.RsaKey.java
public RsaKey(String kid, KeyPair keyPair, Provider provider) { if (Strings.isNullOrWhiteSpace(kid)) { throw new IllegalArgumentException("kid"); }//www.j av a 2 s . co m if (keyPair == null) { throw new IllegalArgumentException("kid"); } if (keyPair.getPublic() == null || !(keyPair.getPublic() instanceof RSAPublicKey)) { throw new IllegalArgumentException("keyPair"); } _kid = kid; _keyPair = keyPair; _provider = provider; }
From source file:org.candlepin.CRLWriteBenchmark.java
@Setup(Level.Trial) public void buildMassiveCRL() throws Exception { issuer = new X500Name("CN=Test Issuer"); KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(2048);//from w ww. ja va 2 s .c o m KeyPair keyPair = generator.generateKeyPair(); bc = new BouncyCastleProvider(); 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.guanxi.idp.Bootstrap.java
public boolean createSelfSignedKeystore(String cn, String keystoreFile, String keystorePassword, String privateKeyPassword, String privateKeyAlias) { KeyStore ks = null;//from w ww . j a va 2s . co m try { ks = KeyStore.getInstance("JKS"); ks.load(null, null); KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA"); keyGen.initialize(1024, new SecureRandom()); KeyPair keypair = keyGen.generateKeyPair(); PrivateKey privkey = keypair.getPrivate(); PublicKey pubkey = keypair.getPublic(); Hashtable<DERObjectIdentifier, String> attrs = new Hashtable<DERObjectIdentifier, String>(); Vector<DERObjectIdentifier> ordering = new Vector<DERObjectIdentifier>(); ordering.add(X509Name.CN); attrs.put(X509Name.CN, cn); X509Name issuerDN = new X509Name(ordering, attrs); X509Name subjectDN = new X509Name(ordering, attrs); Date validFrom = new Date(); validFrom.setTime(validFrom.getTime() - (10 * 60 * 1000)); Date validTo = new Date(); validTo.setTime(validTo.getTime() + (20 * (24 * 60 * 60 * 1000))); X509V3CertificateGenerator x509 = new X509V3CertificateGenerator(); x509.setSignatureAlgorithm("SHA1withDSA"); x509.setIssuerDN(issuerDN); x509.setSubjectDN(subjectDN); x509.setPublicKey(pubkey); x509.setNotBefore(validFrom); x509.setNotAfter(validTo); x509.setSerialNumber(new BigInteger(128, new Random())); X509Certificate[] cert = new X509Certificate[1]; cert[0] = x509.generate(privkey, "BC"); java.security.cert.Certificate[] chain = new java.security.cert.Certificate[1]; chain[0] = cert[0]; ks.setKeyEntry(privateKeyAlias, privkey, privateKeyPassword.toCharArray(), cert); ks.setKeyEntry(privateKeyAlias, privkey, privateKeyPassword.toCharArray(), chain); ks.store(new FileOutputStream(keystoreFile), keystorePassword.toCharArray()); String IDP_RFC_CERT = "WEB-INF/guanxi_idp/keystore/guanxi_idp_cert.txt"; PEMWriter pemWriter = new PEMWriter(new FileWriter(servletContext.getRealPath(IDP_RFC_CERT))); pemWriter.writeObject(cert[0]); pemWriter.close(); return true; } catch (Exception se) { return false; } }
From source file:it.zero11.acme.Acme.java
protected String getHTTP01ChallengeContent(final KeyPair userKey, final String token) { return token + "." + JWKUtils.getWebKeyThumbprintSHA256(userKey.getPublic()); }
From source file:com.microsoft.azure.keyvault.extensions.RsaKey.java
public RsaKey(String kid, KeyPair keyPair) { if (Strings.isNullOrWhiteSpace(kid)) { throw new IllegalArgumentException("kid"); }//w w w .j a v a 2 s. c o m if (keyPair == null) { throw new IllegalArgumentException("kid"); } if (keyPair.getPublic() == null || !(keyPair.getPublic() instanceof RSAPublicKey)) { throw new IllegalArgumentException("keyPair"); } _keyPair = keyPair; _kid = kid; }