List of usage examples for java.security KeyPair getPublic
public PublicKey getPublic()
From source file:netinf.common.security.impl.CryptographyTest.java
@Test public void testBadReaderKeyAlgorithm() { InformationObject informationObject = createTestInformationObject(); Hashtable<String, PublicKey> readers = new Hashtable<String, PublicKey>(); readers = new Hashtable<String, PublicKey>(); try {/* www . j a v a 2 s.co m*/ KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA"); keyPairGenerator.initialize(1024); KeyPair pair = keyPairGenerator.generateKeyPair(); PublicKey publicKey = pair.getPublic(); readers.put("any name", publicKey); } catch (Exception e) { throw new NetInfUncheckedException("error creating keys"); } try { crypto.encrypt(informationObject, readers); Assert.fail("Exception expected. Wrong reader name given."); } catch (NetInfCheckedSecurityException securityException) { System.out.println(securityException.getMessage()); } }
From source file:org.kaaproject.kaa.server.transports.http.transport.HttpTestClient.java
/** * Initialization of request keys and encoder/decoder * * @param serverPublicKey - server public key * @throws Exception - if key generation failed. *//* w w w . j a va 2 s . c o m*/ private void init(PublicKey serverPublicKey) throws Exception { KeyPairGenerator clientKeyGen; try { clientKeyGen = KeyPairGenerator.getInstance("RSA"); clientKeyGen.initialize(2048); KeyPair clientKeyPair = clientKeyGen.genKeyPair(); clientPrivateKey = clientKeyPair.getPrivate(); clientPublicKey = clientKeyPair.getPublic(); } catch (NoSuchAlgorithmException e) { throw new Exception(e.toString()); } crypt = new MessageEncoderDecoder(clientPrivateKey, clientPublicKey, serverPublicKey); try { key = crypt.getEncodedSessionKey(); } catch (GeneralSecurityException e) { throw new Exception(e.toString()); } ByteBuffer publicKeyBuffer = ByteBuffer .wrap(EndpointObjectHash.fromSha1(clientPublicKey.getEncoded()).getData()); clientPublicKeyHash = EndpointObjectHash.fromBytes(publicKeyBuffer.array()); }
From source file:net.padlocksoftware.padlock.validator.ValidatorTest.java
License:asdf
/** * this test actually only works when there is no padlock license key referenced. Disabling the license * check to enforce a 2 week expiry period breaks this test. Thus I am disabling * // ww w. jav a 2s. c o m * @throws Exception */ @Test @Ignore public void testExpired() throws Exception { KeyPair pair = KeyManager.createKeyPair(); License license = LicenseFactory.createLicense(); license.setStartDate(new Date(100)); LicenseSigner signer = LicenseSigner.createLicenseSigner((DSAPrivateKey) pair.getPrivate()); signer.sign(license); 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:org.cesecore.audit.log.SecurityEventsLoggerSessionBeanTest.java
@Test public void test08Authorization() throws Exception { KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); X509Certificate certificate = CertTools.genSelfCert( "C=SE,O=Test,CN=Test SecurityEventsLoggerSessionTestNoAuth", 365, null, keys.getPrivate(), keys.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA, true); Set<X509Certificate> credentials = new HashSet<X509Certificate>(); credentials.add(certificate);/*w ww . jav a 2 s . co m*/ Set<X500Principal> principals = new HashSet<X500Principal>(); principals.add(certificate.getSubjectX500Principal()); AuthenticationToken adminTokenNoAuth = new X509CertificateAuthenticationToken(principals, credentials); try { securityEventsLogger.log(adminTokenNoAuth, EventTypes.AUTHENTICATION, EventStatus.SUCCESS, ModuleTypes.AUTHENTICATION, ServiceTypes.CORE); fail("should throw"); } catch (AuthorizationDeniedException e) { // NOPMD: ignore this is what we want } }
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);//from w w w . jav a2s . co m 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.netscape.cms.servlet.test.ConfigurationTest.java
private static String generateCRMFRequest(CryptoToken token, String keysize, String subjectdn, boolean dualkey) throws NoSuchAlgorithmException, TokenException, IOException, InvalidBERException { KeyPairGenerator kg = token.getKeyPairGenerator(KeyPairAlgorithm.RSA); Integer x = new Integer(keysize); int key_len = x.intValue(); kg.initialize(key_len);/*from w w w.j ava 2 s . co m*/ // 1st key pair KeyPair pair = kg.genKeyPair(); // create CRMF CertTemplate certTemplate = new CertTemplate(); certTemplate.setVersion(new INTEGER(2)); if (subjectdn != null) { X500Name name = new X500Name(subjectdn); ByteArrayInputStream cs = new ByteArrayInputStream(name.getEncoded()); Name n = (Name) Name.getTemplate().decode(cs); certTemplate.setSubject(n); } certTemplate.setPublicKey(new SubjectPublicKeyInfo(pair.getPublic())); SEQUENCE seq = new SEQUENCE(); CertRequest certReq = new CertRequest(new INTEGER(1), certTemplate, seq); byte popdata[] = { 0x0, 0x3, 0x0 }; ProofOfPossession pop = ProofOfPossession .createKeyEncipherment(POPOPrivKey.createThisMessage(new BIT_STRING(popdata, 3))); CertReqMsg crmfMsg = new CertReqMsg(certReq, pop, null); SEQUENCE s1 = new SEQUENCE(); // 1st : Encryption key s1.addElement(crmfMsg); // 2nd : Signing Key if (dualkey) { System.out.println("dualkey = true"); SEQUENCE seq1 = new SEQUENCE(); CertRequest certReqSigning = new CertRequest(new INTEGER(1), certTemplate, seq1); CertReqMsg signingMsg = new CertReqMsg(certReqSigning, pop, null); s1.addElement(signingMsg); } byte encoded[] = ASN1Util.encode(s1); // BASE64Encoder encoder = new BASE64Encoder(); // String Req1 = encoder.encodeBuffer(encoded); String Req1 = Utils.base64encode(encoded, true); return Req1; }
From source file:com.eucalyptus.www.X509Download.java
private static byte[] getX509Zip(User u) throws Exception { X509Certificate cloudCert = null; final X509Certificate x509; String userAccessKey = null;//w w w . jav a 2s .co m String userSecretKey = null; KeyPair keyPair = null; try { for (AccessKey k : u.getKeys()) { if (k.isActive()) { userAccessKey = k.getAccessKey(); userSecretKey = k.getSecretKey(); } } if (userAccessKey == null) { AccessKey k = u.createKey(); userAccessKey = k.getAccessKey(); userSecretKey = k.getSecretKey(); } keyPair = Certs.generateKeyPair(); x509 = Certs.generateCertificate(keyPair, u.getName()); x509.checkValidity(); u.addCertificate(x509); cloudCert = SystemCredentials.lookup(Eucalyptus.class).getCertificate(); } catch (Exception e) { LOG.fatal(e, e); throw e; } ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(byteOut); ZipArchiveEntry entry = null; String fingerPrint = Certs.getFingerPrint(keyPair.getPublic()); if (fingerPrint != null) { String baseName = X509Download.NAME_SHORT + "-" + u.getName() + "-" + fingerPrint.replaceAll(":", "").toLowerCase().substring(0, 8); zipOut.setComment("To setup the environment run: source /path/to/eucarc"); StringBuilder sb = new StringBuilder(); //TODO:GRZE:FIXME velocity String userNumber = u.getAccount().getAccountNumber(); sb.append("EUCA_KEY_DIR=$(cd $(dirname ${BASH_SOURCE:-$0}); pwd -P)"); final Optional<String> computeUrl = remotePublicify(Compute.class); if (computeUrl.isPresent()) { sb.append(entryFor("EC2_URL", null, computeUrl)); } else { sb.append("\necho WARN: Eucalyptus URL is not configured. >&2"); ServiceBuilder<? extends ServiceConfiguration> builder = ServiceBuilders.lookup(Compute.class); ServiceConfiguration localConfig = builder.newInstance(Internets.localHostAddress(), Internets.localHostAddress(), Internets.localHostAddress(), Eucalyptus.INSTANCE.getPort()); sb.append("\nexport EC2_URL=" + ServiceUris.remotePublicify(localConfig)); } sb.append(entryFor("S3_URL", "An OSG is either not registered or not configured. S3_URL is not set. " + "Please register an OSG and/or set a valid s3 endpoint and download credentials again. " + "Or set S3_URL manually to http://OSG-IP:8773/services/objectstorage", remotePublicify(ObjectStorage.class))); sb.append(entryFor("EUARE_URL", "EUARE URL is not configured.", remotePublicify(Euare.class))); sb.append(entryFor("TOKEN_URL", "TOKEN URL is not configured.", remotePublicify(Tokens.class))); sb.append(entryFor("AWS_AUTO_SCALING_URL", "Auto Scaling service URL is not configured.", remotePublicify(AutoScaling.class))); sb.append(entryFor("AWS_CLOUDFORMATION_URL", null, remotePublicify(CloudFormation.class))); sb.append(entryFor("AWS_CLOUDWATCH_URL", "Cloud Watch service URL is not configured.", remotePublicify(CloudWatch.class))); sb.append(entryFor("AWS_ELB_URL", "Load Balancing service URL is not configured.", remotePublicify(LoadBalancing.class))); sb.append("\nexport EUSTORE_URL=" + StackConfiguration.DEFAULT_EUSTORE_URL); sb.append("\nexport EC2_PRIVATE_KEY=${EUCA_KEY_DIR}/" + baseName + "-pk.pem"); sb.append("\nexport EC2_CERT=${EUCA_KEY_DIR}/" + baseName + "-cert.pem"); sb.append("\nexport EC2_JVM_ARGS=-Djavax.net.ssl.trustStore=${EUCA_KEY_DIR}/jssecacerts"); sb.append("\nexport EUCALYPTUS_CERT=${EUCA_KEY_DIR}/cloud-cert.pem"); sb.append("\nexport EC2_ACCOUNT_NUMBER='" + u.getAccount().getAccountNumber() + "'"); sb.append("\nexport EC2_ACCESS_KEY='" + userAccessKey + "'"); sb.append("\nexport EC2_SECRET_KEY='" + userSecretKey + "'"); sb.append("\nexport AWS_ACCESS_KEY='" + userAccessKey + "'"); sb.append("\nexport AWS_SECRET_KEY='" + userSecretKey + "'"); sb.append("\nexport AWS_CREDENTIAL_FILE=${EUCA_KEY_DIR}/iamrc"); sb.append("\nexport EC2_USER_ID='" + userNumber + "'"); sb.append( "\nalias ec2-bundle-image=\"ec2-bundle-image --cert ${EC2_CERT} --privatekey ${EC2_PRIVATE_KEY} --user ${EC2_ACCOUNT_NUMBER} --ec2cert ${EUCALYPTUS_CERT}\""); sb.append( "\nalias ec2-upload-bundle=\"ec2-upload-bundle -a ${EC2_ACCESS_KEY} -s ${EC2_SECRET_KEY} --url ${S3_URL}\""); sb.append("\n"); zipOut.putArchiveEntry(entry = new ZipArchiveEntry("eucarc")); entry.setUnixMode(0600); zipOut.write(sb.toString().getBytes("UTF-8")); zipOut.closeArchiveEntry(); sb = new StringBuilder(); sb.append("AWSAccessKeyId=").append(userAccessKey).append('\n'); sb.append("AWSSecretKey=").append(userSecretKey); zipOut.putArchiveEntry(entry = new ZipArchiveEntry("iamrc")); entry.setUnixMode(0600); zipOut.write(sb.toString().getBytes("UTF-8")); zipOut.closeArchiveEntry(); /** write the private key to the zip stream **/ zipOut.putArchiveEntry(entry = new ZipArchiveEntry("cloud-cert.pem")); entry.setUnixMode(0600); zipOut.write(PEMFiles.getBytes(cloudCert)); zipOut.closeArchiveEntry(); zipOut.putArchiveEntry(entry = new ZipArchiveEntry("jssecacerts")); entry.setUnixMode(0600); KeyStore tempKs = KeyStore.getInstance("jks"); tempKs.load(null); tempKs.setCertificateEntry("eucalyptus", cloudCert); ByteArrayOutputStream bos = new ByteArrayOutputStream(); tempKs.store(bos, "changeit".toCharArray()); zipOut.write(bos.toByteArray()); zipOut.closeArchiveEntry(); /** write the private key to the zip stream **/ zipOut.putArchiveEntry(entry = new ZipArchiveEntry(baseName + "-pk.pem")); entry.setUnixMode(0600); zipOut.write(PEMFiles.getBytes("RSA PRIVATE KEY", Crypto.getCertificateProvider().getEncoded(keyPair.getPrivate()))); zipOut.closeArchiveEntry(); /** write the X509 certificate to the zip stream **/ zipOut.putArchiveEntry(entry = new ZipArchiveEntry(baseName + "-cert.pem")); entry.setUnixMode(0600); zipOut.write(PEMFiles.getBytes(x509)); zipOut.closeArchiveEntry(); } /** close the zip output stream and return the bytes **/ zipOut.close(); return byteOut.toByteArray(); }
From source file:com.sshtools.j2ssh.transport.kex.DhGroup1Sha1.java
/** * * * @param clientId//from w w w. j av a2s .co m * @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:org.apache.nifi.toolkit.tls.util.TlsHelperTest.java
@Test public void testIssueCert() throws IOException, CertificateException, NoSuchAlgorithmException, OperatorCreationException, NoSuchProviderException, InvalidKeyException, SignatureException { X509Certificate issuer = loadCertificate( new InputStreamReader(getClass().getClassLoader().getResourceAsStream("rootCert.crt"))); KeyPair issuerKeyPair = loadKeyPair( new InputStreamReader(getClass().getClassLoader().getResourceAsStream("rootCert.key"))); String dn = "CN=testIssued, O=testOrg"; KeyPair keyPair = TlsHelper.generateKeyPair(keyPairAlgorithm, keySize); X509Certificate x509Certificate = CertificateUtils.generateIssuedCertificate(dn, keyPair.getPublic(), issuer, issuerKeyPair, signingAlgorithm, days); assertEquals(dn, x509Certificate.getSubjectX500Principal().toString()); assertEquals(issuer.getSubjectX500Principal().toString(), x509Certificate.getIssuerX500Principal().toString()); assertEquals(keyPair.getPublic(), x509Certificate.getPublicKey()); Date notAfter = x509Certificate.getNotAfter(); assertTrue(notAfter.after(inFuture(days - 1))); assertTrue(notAfter.before(inFuture(days + 1))); Date notBefore = x509Certificate.getNotBefore(); assertTrue(notBefore.after(inFuture(-1))); assertTrue(notBefore.before(inFuture(1))); assertEquals(signingAlgorithm, x509Certificate.getSigAlgName()); assertEquals(keyPairAlgorithm, x509Certificate.getPublicKey().getAlgorithm()); x509Certificate.verify(issuerKeyPair.getPublic()); }
From source file:org.apache.nifi.toolkit.tls.standalone.TlsToolkitStandaloneTest.java
private X509Certificate checkLoadCertPrivateKey(String algorithm) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException { KeyPair keyPair = TlsHelperTest.loadKeyPair(new File(tempDir, TlsToolkitStandalone.NIFI_KEY + ".key")); assertEquals(algorithm, keyPair.getPrivate().getAlgorithm()); assertEquals(algorithm, keyPair.getPublic().getAlgorithm()); X509Certificate x509Certificate = TlsHelperTest .loadCertificate(new File(tempDir, TlsToolkitStandalone.NIFI_CERT + ".pem")); assertEquals(keyPair.getPublic(), x509Certificate.getPublicKey()); return x509Certificate; }