List of usage examples for java.security KeyPair getPublic
public PublicKey getPublic()
From source file:hh.learnj.test.license.test.rsacoder.RSACoder.java
/** * ?// ww w.ja va2s . c o m * * @return Map Map */ public static Map<String, Object> initKey() throws Exception { // ? KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM); // ?? keyPairGenerator.initialize(KEY_SIZE); // ? KeyPair keyPair = keyPairGenerator.generateKeyPair(); // RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); // ? RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); // map Map<String, Object> keyMap = new HashMap<String, Object>(); keyMap.put(PUBLIC_KEY, publicKey); keyMap.put(PRIVATE_KEY, privateKey); return keyMap; }
From source file:org.computerist.ssltools.zap.ZapSslCertificateUtils.java
/** * Creates a new Root CA certificate and returns private and public key as * {@link KeyStore}. The {@link KeyStore#getDefaultType()} is used. * * @return//from w ww .j a v a2 s . co m * @throws NoSuchAlgorithmException If no providers are found * for 'RSA' key pair generator * or 'SHA1PRNG' Secure random number generator * @throws IllegalStateException in case of errors during assembling {@link KeyStore} */ public static final KeyStore createRootCA() throws NoSuchAlgorithmException { final Date startDate = Calendar.getInstance().getTime(); final Date expireDate = new Date(startDate.getTime() + (DEFAULT_VALID_DAYS * 24L * 60L * 60L * 1000L)); final KeyPairGenerator g = KeyPairGenerator.getInstance("RSA"); g.initialize(2048, SecureRandom.getInstance("SHA1PRNG")); final KeyPair keypair = g.genKeyPair(); final PrivateKey privKey = keypair.getPrivate(); final PublicKey pubKey = keypair.getPublic(); Random rnd = new Random(); // using the hash code of the user's name and home path, keeps anonymity // but also gives user a chance to distinguish between each other X500NameBuilder namebld = new X500NameBuilder(BCStyle.INSTANCE); namebld.addRDN(BCStyle.CN, "OWASP Zed Attack Proxy Root CA"); namebld.addRDN(BCStyle.L, Integer.toHexString(System.getProperty("user.name").hashCode()) + Integer.toHexString(System.getProperty("user.home").hashCode())); namebld.addRDN(BCStyle.O, "OWASP Root CA"); namebld.addRDN(BCStyle.OU, "OWASP ZAP Root CA"); namebld.addRDN(BCStyle.C, "xx"); X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(namebld.build(), BigInteger.valueOf(rnd.nextInt()), startDate, expireDate, namebld.build(), pubKey); KeyStore ks = null; try { certGen.addExtension(X509Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(pubKey)); certGen.addExtension(X509Extension.basicConstraints, true, new BasicConstraints(true)); certGen.addExtension(X509Extension.keyUsage, false, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.cRLSign)); Vector<DERObject> eku = new Vector<>(3, 1); eku.add(KeyPurposeId.id_kp_serverAuth); eku.add(KeyPurposeId.id_kp_clientAuth); eku.add(KeyPurposeId.anyExtendedKeyUsage); certGen.addExtension(X509Extension.extendedKeyUsage, false, new ExtendedKeyUsage(eku)); final ContentSigner sigGen = new JcaContentSignerBuilder("SHA1WithRSAEncryption").setProvider("BC") .build(privKey); final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC") .getCertificate(certGen.build(sigGen)); ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null, null); ks.setKeyEntry(FixedSslCertificateService.ZAPROXY_JKS_ALIAS, privKey, FixedSslCertificateService.PASSPHRASE, new Certificate[] { cert }); } catch (final Exception e) { throw new IllegalStateException("Errors during assembling root CA.", e); } return ks; }
From source file:com.znsx.util.licence.LicenceUtil.java
/** * ??/*from ww w. j a va 2 s.co m*/ * * @param seed * ?? * @return * @throws Exception */ public static Map<String, String> generateKey(String seed) throws Exception { Map<String, String> map = new HashMap<String, String>(2); KeyPairGenerator keygen = KeyPairGenerator.getInstance("DSA"); SecureRandom random = new SecureRandom(); random.setSeed(seed.getBytes("utf8")); keygen.initialize(1024, random); KeyPair keyPair = keygen.generateKeyPair(); PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); Base64 base64 = new Base64(); String publicKeyString = new String(base64.encode(publicKey.getEncoded()), "utf8"); String privateKeyString = new String(base64.encode(privateKey.getEncoded()), "utf8"); // BASE64Encoder encoder = new BASE64Encoder(); // map.put("public", encoder.encode(publicKey.getEncoded())); // map.put("private", encoder.encode(privateKey.getEncoded())); map.put("public", publicKeyString); map.put("private", privateKeyString); System.out.println("publicKey: " + map.get("public")); System.out.println("privateKey: " + map.get("private")); return map; }
From source file:de.pawlidi.openaletheia.utils.CipherUtils.java
/** * /* ww w. j a v a2 s. c o m*/ * @param keyPair * @return */ public static String getPublicKey(KeyPair keyPair) { if (keyPair != null && keyPair.getPublic() != null) { return Converter.toString(keyPair.getPublic().getEncoded()); } return null; }
From source file:net.arccotangent.pacchat.filesystem.KeyManager.java
private static void generateNewKeys() { km_log.i("Generating new keys."); KeyPair keyPair = RSA.generateRSAKeypair(4096); assert keyPair != null; PrivateKey privkey = keyPair.getPrivate(); PublicKey pubkey = keyPair.getPublic(); saveKeys(privkey, pubkey);//from www. j av a 2 s. c o m }
From source file:org.excalibur.core.util.SecurityUtils2.java
public static UserKey generateUserKey() throws Exception { KeyPairGenerator kpg = SecurityUtils.getKeyPairGenerator("RSA"); kpg.initialize(1024, new SecureRandom()); java.security.KeyPair kp = kpg.generateKeyPair(); String priv = getKeyMaterial(kp.getPrivate()); byte[] encoded = encode((RSAPublicKey) kp.getPublic()); // String pub = getKeyMaterial(kp.getPublic()).replaceAll(PUBLIC_KEY_START, "").replaceAll(PUBLIC_KEY_END, "").trim(); return new UserKey().setPrivateKeyMaterial(priv).setPublicKeyMaterial(new String(Base64.encode(encoded))) .setFingerPrint(getFingerPrint((RSAPublicKey) kp.getPublic())); }
From source file:com.znsx.util.licence.LicenceUtil.java
/** * ?DSA??p,q,g,j,x,y/*from w w w . ja va2s . c o m*/ * * @param seed * ?? * @throws Exception * @author huangbuji * <p /> * Create at 2014-2-8 ?4:45:26 */ @SuppressWarnings("restriction") public static void genKey(String seed) throws Exception { KeyPairGenerator keygen = KeyPairGenerator.getInstance("DSA"); SecureRandom random = new SecureRandom(); random.setSeed(seed.getBytes("utf8")); keygen.initialize(1024, random); KeyPair keyPair = keygen.generateKeyPair(); DSAPublicKeyImpl publicKey = (DSAPublicKeyImpl) keyPair.getPublic(); DSAPrivateKey privateKey = (DSAPrivateKey) keyPair.getPrivate(); DSAParams dsaParams = privateKey.getParams(); Base64 base64 = new Base64(); String p = new String(base64.encode(dsaParams.getP().toByteArray()), "utf8"); String q = new String(base64.encode(dsaParams.getQ().toByteArray()), "utf8"); String g = new String(base64.encode(dsaParams.getG().toByteArray()), "utf8"); String x = new String(base64.encode(privateKey.getX().toByteArray()), "utf8"); String y = new String(base64.encode(publicKey.getY().toByteArray()), "utf8"); System.out.println("P: " + p); System.out.println("Q: " + q); System.out.println("G: " + g); System.out.println("X: " + x); System.out.println("Y: " + y); String publicKeyString = new String(base64.encode(publicKey.getEncoded()), "utf8"); String privateKeyString = new String(base64.encode(privateKey.getEncoded()), "utf8"); System.err.println("public: " + publicKeyString); System.err.println("private: " + privateKeyString); File publicFile = new File("D:/binPublic.ky"); File privateFile = new File("D:/binPrivate.ky"); FileOutputStream out = new FileOutputStream(publicFile); out.write(publicKey.getEncoded()); out.flush(); out.close(); out = new FileOutputStream(privateFile); out.write(privateKey.getEncoded()); out.flush(); out.close(); }
From source file:com.security.ch08_rsa.RSACoderTextKey.java
/** * ?/*from ww w . j a v a 2s. co m*/ * * @return Map Map * @throws Exception */ public static Map<String, String> initKey(UUID licenseCode) throws Exception { // ? KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM); // ?? // keyPairGen.initialize(KEY_SIZE); keyPairGen.initialize(KEY_SIZE, new SecureRandom(licenseCode.toString().getBytes(UTF_8))); // ? KeyPair keyPair = keyPairGen.generateKeyPair(); // RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); // ? RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); // ? Map<String, String> keyMap = new HashMap<String, String>(); keyMap.put(PUBLIC_KEY, Base64.encodeBase64String(publicKey.getEncoded())); keyMap.put(PRIVATE_KEY, Base64.encodeBase64String(privateKey.getEncoded())); keyMap.put(LICENSE_CODE, licenseCode.toString()); return keyMap; }
From source file:org.kaaproject.kaa.common.endpoint.security.KeyUtil.java
/** * Validates RSA public and private key. * * @param keyPair the keypair// ww w . j a v a 2s.c o m * @return true if keys matches */ public static boolean validateKeyPair(KeyPair keyPair) { RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); if (publicKey.getModulus().bitLength() != privateKey.getModulus().bitLength()) { LOG.error("Keypair length matching error"); return false; } byte[] rawPayload = new byte[64]; new Random().nextBytes(rawPayload); MessageEncoderDecoder encDec = new MessageEncoderDecoder(privateKey, publicKey); byte[] encodedPayload; byte[] decodedPayload; try { encodedPayload = encDec.encodeData(rawPayload); decodedPayload = encDec.decodeData(encodedPayload); } catch (GeneralSecurityException ex) { LOG.error("Validation keypair error ", ex); return false; } return Arrays.equals(rawPayload, decodedPayload); }
From source file:com.github.aynu.mosir.core.standard.util.SecurityHelper.java
/** * RSA???/*from w ww . j av a2 s . com*/ * <dl> * <dt>? * <dd>RSA??????2048?????? * </dl> * @return RSA? */ public static KeyPair createKeyPair() { try { final KeyPairGenerator generator = KeyPairGenerator.getInstance(ALGO_KEY); generator.initialize(2048); final KeyPair pair = generator.generateKeyPair(); if (LOG.isDebugEnabled()) { final RSAPublicKey publicKey = (RSAPublicKey) pair.getPublic(); final RSAPrivateKey privateKey = (RSAPrivateKey) pair.getPrivate(); LOG.debug("public-modulus={}", Base64.encodeBase64String(publicKey.getModulus().toByteArray())); LOG.debug("public-exponent={}", Base64.encodeBase64String(publicKey.getPublicExponent().toByteArray())); LOG.debug("private-modulus={}", Base64.encodeBase64String(privateKey.getModulus().toByteArray())); LOG.debug("private-exponent={}", Base64.encodeBase64String(privateKey.getPrivateExponent().toByteArray())); } return pair; } catch (final NoSuchAlgorithmException e) { throw new StandardRuntimeException(e); } }