List of usage examples for java.security KeyPair getPublic
public PublicKey getPublic()
From source file:org.cloudfoundry.identity.uaa.oauth.SignerProvider.java
protected void pemEncodePublicKey(KeyPair keyPair) { String begin = "-----BEGIN PUBLIC KEY-----\n"; String end = "\n-----END PUBLIC KEY-----"; byte[] data = keyPair.getPublic().getEncoded(); String base64encoded = new String(base64encoder.encode(data)); verifierKey = begin + base64encoded + end; }
From source file:com.orange.oidc.tim.service.KryptoUtils.java
public static String getJwkPrivate(KeyPair kp) { try {//from w w w . j ava 2 s. c om JSONObject jk = new JSONObject(); jk.put("kty", "RSA"); // generate random kid for tim_app_key SecureRandom random = new SecureRandom(); String kid = new BigInteger(130, random).toString(32); jk.put("kid", kid); jk.put("e", "AQAB"); KeyFactory kfactory = KeyFactory.getInstance("RSA"); RSAPrivateKeySpec privkspec = (RSAPrivateKeySpec) kfactory.getKeySpec(kp.getPrivate(), RSAPrivateKeySpec.class); RSAPublicKeySpec pubkspec = (RSAPublicKeySpec) kfactory.getKeySpec(kp.getPublic(), RSAPublicKeySpec.class); // Log.d("getJwkPrivate n",pubkspec.getPublicExponent().toString()); // Log.d("getJwkPrivate d",privkspec.getPrivateExponent().toString()); jk.put("n", encodeB64(pubkspec.getModulus().toByteArray())); jk.put("d", encodeB64(privkspec.getPrivateExponent().toByteArray())); JSONArray ja = new JSONArray(); ja.put(jk); JSONObject jo = new JSONObject(); jo.put("keys", ja); return jo.toString(); } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:com.aqnote.shared.cryptology.cert.gen.CertGenerator.java
public X509Certificate createClass3EndCert(long sno, X500Name sdn, Map<String, String> exts, PublicKey pubKey, KeyPair pKeyPair) throws Exception { PublicKey pPubKey = pKeyPair.getPublic(); PrivateKey pPrivKey = pKeyPair.getPrivate(); X500Name idn = X500NameUtil.createClass3CaPrincipal(); BigInteger _sno = BigInteger.valueOf(sno <= 0 ? System.currentTimeMillis() : sno); Date nb = new Date(System.currentTimeMillis() - HALF_DAY); Date na = new Date(nb.getTime() + FIVE_YEAR); X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(idn, _sno, nb, na, sdn, pubKey); addSubjectKID(certBuilder, pubKey);/*w w w.j a va2s .co m*/ addAuthorityKID(certBuilder, pPubKey); certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(MOST_EKU)); certBuilder.addExtension(Extension.keyUsage, false, new KeyUsage(END_KEY_USAGE)); if (exts != null) { Set<String> key = exts.keySet(); for (Iterator<String> it = key.iterator(); it.hasNext();) { String oid = it.next(); String value = exts.get(oid); if (!StringUtils.isBlank(value)) { certBuilder.addExtension(new ASN1ObjectIdentifier(oid), false, new DEROctetString(value.getBytes())); } } } X509Certificate certificate = signCert(certBuilder, pPrivKey); certificate.checkValidity(new Date()); certificate.verify(pPubKey); setPKCS9Info(certificate); return certificate; }
From source file:com.aqnote.shared.encrypt.cert.gen.BCCertGenerator.java
public X509Certificate createClass3EndCert(long sno, X500Name sdn, Map<String, String> exts, KeyPair keyPair, KeyPair pKeyPair) throws Exception { PublicKey pPubKey = pKeyPair.getPublic(); PrivateKey pPrivKey = pKeyPair.getPrivate(); X500Name idn = X500NameUtil.createClass3RootPrincipal(); BigInteger _sno = BigInteger.valueOf(sno <= 0 ? System.currentTimeMillis() : sno); Date nb = new Date(System.currentTimeMillis() - HALF_DAY); Date na = new Date(nb.getTime() + FIVE_YEAR); PublicKey pubKey = keyPair.getPublic(); X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(idn, _sno, nb, na, sdn, pubKey); addSubjectKID(certBuilder, pubKey);/* ww w . j a v a2 s. c o m*/ addAuthorityKID(certBuilder, pPubKey); certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(MOST_EKU)); certBuilder.addExtension(Extension.keyUsage, false, new KeyUsage(END_KEY_USAGE)); if (exts != null) { Set<String> key = exts.keySet(); for (Iterator<String> it = key.iterator(); it.hasNext();) { String oid = it.next(); String value = exts.get(oid); if (!StringUtils.isBlank(value)) { certBuilder.addExtension(new ASN1ObjectIdentifier(oid), false, new DEROctetString(value.getBytes())); } } } X509Certificate certificate = signCert(certBuilder, pPrivKey); certificate.checkValidity(new Date()); certificate.verify(pPubKey); setPKCS9Info(certificate); return certificate; }
From source file:co.cask.cdap.security.tools.KeyStores.java
/** * Generate an X.509 certificate//w w w. ja v a 2 s .com * * @param dn Distinguished name for the owner of the certificate, it will also be the signer of the certificate. * @param pair Key pair used for signing the certificate. * @param days Validity of the certificate. * @param algorithm Name of the signature algorithm used. * @return A X.509 certificate */ private static X509Certificate getCertificate(String dn, KeyPair pair, int days, String algorithm) throws IOException, CertificateException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { // Calculate the validity interval of the certificate Date from = new Date(); Date to = DateUtils.addDays(from, days); CertificateValidity interval = new CertificateValidity(from, to); // Generate a random number to use as the serial number for the certificate BigInteger sn = new BigInteger(64, new SecureRandom()); // Create the name of the owner based on the provided distinguished name X500Name owner = new X500Name(dn); // Create an info objects with the provided information, which will be used to create the certificate X509CertInfo info = new X509CertInfo(); info.set(X509CertInfo.VALIDITY, interval); info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn)); // This certificate will be self signed, hence the subject and the issuer are same. info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(owner)); info.set(X509CertInfo.ISSUER, new CertificateIssuerName(owner)); info.set(X509CertInfo.KEY, new CertificateX509Key(pair.getPublic())); info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3)); AlgorithmId algo = new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid); info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algo)); // Create the certificate and sign it with the private key X509CertImpl cert = new X509CertImpl(info); PrivateKey privateKey = pair.getPrivate(); cert.sign(privateKey, algorithm); return cert; }
From source file:edu.wisc.doit.tcrypt.controller.DownloadController.java
@RequestMapping("/download") public void downloadKey(@RequestParam("serviceName") String serviceName, @RequestParam("keyType") String keyType, HttpServletRequest request, HttpServletResponse response) throws Exception { try {//from w w w . j av a 2 s. com KeyPair sk = (KeyPair) request.getSession().getAttribute("serviceKey_" + serviceName); response.setContentType("application/x-pem-file"); response.setHeader("Content-Disposition", "attachment; filename=\"" + keyType + "-" + serviceName + ".pem" + "\""); Key key = "private".equalsIgnoreCase(keyType) ? sk.getPrivate() : sk.getPublic(); try (final PEMWriter pemWriter = new PEMWriter(new PrintWriter(response.getOutputStream()))) { pemWriter.writeObject(key); } } catch (Exception e) { logger.error("Issue downloading the key " + keyType, e); throw new Exception(e); } }
From source file:edu.vt.middleware.crypt.asymmetric.AsymmetricCli.java
/** * Generate a new encryption public/private key pair using CLI arguments. * * @param line Parsed command line arguments container. * * @throws Exception On encryption errors. */// w w w .j av a 2 s . c o m protected void genKeyPair(final CommandLine line) throws Exception { validateOptions(line); final AsymmetricAlgorithm alg = newAlgorithm(line); final int size = Integer.parseInt(line.getOptionValue(OPT_GENKEYPAIR)); System.err.println("Generating " + alg + " key pair of " + size + " bits"); final KeyPair keyPair = PublicKeyUtils.generate(alg.getAlgorithm(), size); final File pubKeyFile = new File(line.getOptionValue(OPT_OUTFILE)); final File privKeyFile = new File(line.getOptionValue(OPT_PRIVKEYPATH)); CryptWriter.writeEncodedKey(keyPair.getPublic(), pubKeyFile); System.err.println("Wrote X.509 DER-encoded public key to " + pubKeyFile); CryptWriter.writeEncodedKey(keyPair.getPrivate(), privKeyFile); System.err.println("Wrote PKCS#8 DER-encoded private key to " + privKeyFile); }
From source file:edu.vt.alerts.android.library.tasks.RegistrationTask.java
private PKCS10CertificationRequest generateCSR(KeyPair keyPair) throws Exception { JcaPKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder( new X500Name("CN=edu.vt.alerts.mobile.android"), keyPair.getPublic()); ContentSigner signer = new JcaContentSignerBuilder(CSR_SIGNER_ALGORITHM).setProvider(CSR_SIGNER_PROVIDER) .build(keyPair.getPrivate()); return builder.build(signer); }
From source file:org.apache.sshd.server.kex.AbstractDHGServer.java
public boolean next(Buffer buffer) throws Exception { SshConstants.Message cmd = buffer.getCommand(); if (cmd != SshConstants.Message.SSH_MSG_KEXDH_INIT) { throw new SshException(SshConstants.SSH2_DISCONNECT_KEY_EXCHANGE_FAILED, "Protocol error: expected packet " + SshConstants.Message.SSH_MSG_KEXDH_INIT + ", got " + cmd); }/*from w w w .j a va 2 s .co m*/ log.info("Received SSH_MSG_KEXDH_INIT"); e = buffer.getMPIntAsBytes(); dh.setF(e); K = dh.getK(); byte[] K_S; KeyPair kp = session.getHostKey(); String algo = session.getNegociated(SshConstants.PROPOSAL_SERVER_HOST_KEY_ALGS); Signature sig = NamedFactory.Utils.create(session.getFactoryManager().getSignatureFactories(), algo); sig.init(kp.getPublic(), kp.getPrivate()); buffer = new Buffer(); buffer.putRawPublicKey(kp.getPublic()); K_S = buffer.getCompactData(); buffer.clear(); buffer.putString(V_C); buffer.putString(V_S); buffer.putString(I_C); buffer.putString(I_S); buffer.putString(K_S); buffer.putMPInt(e); buffer.putMPInt(f); buffer.putMPInt(K); sha.update(buffer.array(), 0, buffer.available()); H = sha.digest(); byte[] sigH; buffer.clear(); sig.update(H, 0, H.length); buffer.putString(algo); buffer.putString(sig.sign()); sigH = buffer.getCompactData(); if (log.isDebugEnabled()) { log.debug("K_S: " + BufferUtils.printHex(K_S)); log.debug("f: " + BufferUtils.printHex(f)); log.debug("sigH: " + BufferUtils.printHex(sigH)); } // Send response log.info("Send SSH_MSG_KEXDH_REPLY"); buffer.clear(); buffer.rpos(5); buffer.wpos(5); buffer.putCommand(SshConstants.Message.SSH_MSG_KEXDH_REPLY_KEX_DH_GEX_GROUP); buffer.putString(K_S); buffer.putString(f); buffer.putString(sigH); session.writePacket(buffer); return true; }
From source file:com.google.u2f.key.impl.U2FKeyReferenceImpl.java
@Override public RegisterResponse register(RegisterRequest registerRequest) throws U2FException { Log.info(">> register"); byte[] applicationSha256 = registerRequest.getApplicationSha256(); byte[] challengeSha256 = registerRequest.getChallengeSha256(); Log.info(" -- Inputs --"); Log.info(" applicationSha256: " + Hex.encodeHexString(applicationSha256)); Log.info(" challengeSha256: " + Hex.encodeHexString(challengeSha256)); byte userPresent = userPresenceVerifier.verifyUserPresence(); if ((userPresent & UserPresenceVerifier.USER_PRESENT_FLAG) == 0) { throw new U2FException("Cannot verify user presence"); }/* www.j ava 2 s.c o m*/ KeyPair keyPair = keyPairGenerator.generateKeyPair(applicationSha256, challengeSha256); byte[] keyHandle = keyHandleGenerator.generateKeyHandle(applicationSha256, keyPair); dataStore.storeKeyPair(keyHandle, keyPair); byte[] userPublicKey = keyPairGenerator.encodePublicKey(keyPair.getPublic()); byte[] signedData = RawMessageCodec.encodeRegistrationSignedBytes(applicationSha256, challengeSha256, keyHandle, userPublicKey); Log.info("Signing bytes " + Hex.encodeHexString(signedData)); byte[] signature = crypto.sign(signedData, certificatePrivateKey); Log.info(" -- Outputs --"); Log.info(" userPublicKey: " + Hex.encodeHexString(userPublicKey)); Log.info(" keyHandle: " + Hex.encodeHexString(keyHandle)); Log.info(" vendorCertificate: " + vendorCertificate); Log.info(" signature: " + Hex.encodeHexString(signature)); Log.info("<< register"); return new RegisterResponse(userPublicKey, keyHandle, vendorCertificate, signature); }