List of usage examples for java.security KeyPair getPublic
public PublicKey getPublic()
From source file:org.ejbca.util.keystore.KeyTools.java
/** * Generates a keypair/*from w ww . java 2 s . co m*/ * * @param keySpec string specification of keys to generate, typical value is 1024 for RSA or DSA keys, or prime192v1 for ECDSA keys or null of algspec is to be used. * @param algSpec AlgorithmParameterSpec of keys to generate, typically an EXParameterSpec for EC keys, or null if keySpec is to be used. * @param keyAlg algorithm of keys to generate, typical value is RSA, DSA or ECDSA, see AlgorithmConstants.KEYALGORITHM_XX * * @see org.ejbca.core.model.AlgorithmConstants * @see org.bouncycastle.asn1.x9.X962NamedCurves * @see org.bouncycastle.asn1.nist.NISTNamedCurves * @see org.bouncycastle.asn1.sec.SECNamedCurves * * @return KeyPair the generated keypair * @throws InvalidAlgorithmParameterException * @see org.ejbca.core.model.AlgorithmConstants#KEYALGORITHM_RSA */ public static KeyPair genKeys(final String keySpec, final AlgorithmParameterSpec algSpec, final String keyAlg) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException { if (log.isTraceEnabled()) { log.trace(">genKeys(" + keySpec + ", " + keyAlg + ")"); } final KeyPairGenerator keygen = KeyPairGenerator.getInstance(keyAlg, "BC"); if (StringUtils.equals(keyAlg, AlgorithmConstants.KEYALGORITHM_ECDSA)) { AlgorithmParameterSpec ecSpec = null; if ((keySpec != null) && !StringUtils.equals(keySpec, "implicitlyCA")) { log.debug("Generating named curve ECDSA key pair: " + keySpec); // We have EC keys ecSpec = ECNamedCurveTable.getParameterSpec(keySpec); if (ecSpec == null) { throw new InvalidAlgorithmParameterException("keySpec " + keySpec + " is invalid for ECDSA."); } } else if (algSpec != null) { log.debug("Generating ECDSA key pair from AlgorithmParameterSpec: " + algSpec); ecSpec = algSpec; } else if (StringUtils.equals(keySpec, "implicitlyCA")) { log.debug("Generating implicitlyCA encoded ECDSA key pair"); // If the keySpec is null, we have "implicitlyCA" defined EC parameters // The parameters were already installed when we installed the provider // We just make sure that ecSpec == null here } else { throw new InvalidAlgorithmParameterException("No keySpec no algSpec and no implicitlyCA specified"); } keygen.initialize(ecSpec, new SecureRandom()); } else { // RSA or DSA keys final int keysize = Integer.parseInt(keySpec); keygen.initialize(keysize); } final KeyPair keys = keygen.generateKeyPair(); if (log.isDebugEnabled()) { final PublicKey pk = keys.getPublic(); final int len = getKeyLength(pk); log.debug("Generated " + keys.getPublic().getAlgorithm() + " keys with length " + len); } log.trace("<genKeys()"); return keys; }
From source file:cherry.foundation.crypto.RSACryptoSupportTest.java
private RSACryptoSupport createCrypto() throws Exception { KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA"); keygen.initialize(2048);/* w w w. j a va 2 s . c om*/ KeyPair key = keygen.generateKeyPair(); RSACryptoSupport crypto = new RSACryptoSupport(); crypto.setAlgorithm("RSA/ECB/PKCS1Padding"); crypto.setPublicKeyResource(new InMemoryResource(key.getPublic().getEncoded())); crypto.setPrivateKeyResource(new InMemoryResource(key.getPrivate().getEncoded())); crypto.afterPropertiesSet(); return crypto; }
From source file:jenkins.security.RSAConfidentialKey.java
/** * Obtains the private key (lazily.)/* ww w . j a va2s. c o m*/ * <p> * This method is not publicly exposed as per the design principle of {@link ConfidentialKey}. * Instead of exposing private key, define methods that use them in specific way, such as * {@link RSADigitalSignatureConfidentialKey}. * * @throws Error * If key cannot be loaded for some reasons, we fail. */ protected synchronized RSAPrivateKey getPrivateKey() { try { if (priv == null) { byte[] payload = load(); if (payload == null) { KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA"); gen.initialize(2048, new SecureRandom()); // going beyond 2048 requires crypto extension KeyPair keys = gen.generateKeyPair(); priv = (RSAPrivateKey) keys.getPrivate(); pub = (RSAPublicKey) keys.getPublic(); store(priv.getEncoded()); } else { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); priv = (RSAPrivateKey) keyFactory.generatePrivate(new PKCS8EncodedKeySpec(payload)); RSAPrivateCrtKey pks = (RSAPrivateCrtKey) priv; pub = (RSAPublicKey) keyFactory .generatePublic(new RSAPublicKeySpec(pks.getModulus(), pks.getPublicExponent())); } } return priv; } catch (IOException e) { throw new Error("Failed to load the key: " + getId(), e); } catch (GeneralSecurityException e) { throw new Error("Failed to load the key: " + getId(), e); } }
From source file:com.kuzumeji.platform.standard.SecurityServiceTest.java
@Test public void testSignature() { final KeyPair keyPair = testee.generateKeyPair(); final RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); final RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); final byte[] message = "?????????????".getBytes(); final byte[] signature = testee.signature(keyPair.getPrivate(), message); assertThat(testee.verify(keyPair.getPublic(), signature, message), is(true)); }
From source file:org.apache.karaf.shell.ssh.OpenSSHGeneratorFileKeyProvider.java
@Override protected void doWriteKeyPair(String resourceKey, KeyPair kp, OutputStream os) throws IOException, GeneralSecurityException { Collection<Object> items = new ArrayList<>(); items.add(kp.getPrivate());/*from ww w .jav a 2 s .c o m*/ items.add(kp.getPublic()); byte[] bytes = PEMUtil.encode(items); os.write(bytes); }
From source file:com.zxy.commons.codec.rsa.AbstractRSAUtils.java
/** * ??/*from w w w .jav a 2 s . c om*/ * * @param pubFile public file * @param priFile private file * @throws IOException IOException */ @SuppressWarnings("PMD.PrematureDeclaration") protected void generater(File pubFile, File priFile) throws IOException { try { KeyPairGenerator keygen = KeyPairGenerator.getInstance(ALGORITHM); SecureRandom secrand = new SecureRandom(); keygen.initialize(KEY_SIZE, secrand); KeyPair keys = keygen.genKeyPair(); PublicKey pubkey = keys.getPublic(); PrivateKey prikey = keys.getPrivate(); byte[] priKey = Base64.encodeBase64(prikey.getEncoded()); byte[] pubKey = Base64.encodeBase64(pubkey.getEncoded()); if (pubFile.exists()) { throw new IOException(pubFile.getPath() + " is exist!"); } if (priFile.exists()) { throw new IOException(priFile.getPath() + " is exist!"); } OutputStream pubOutput = new FileOutputStream(pubFile); try { IOUtils.write(pubKey, pubOutput); } finally { IOUtils.closeQuietly(pubOutput); } OutputStream priOutput = new FileOutputStream(priFile); try { IOUtils.write(priKey, priOutput); } finally { IOUtils.closeQuietly(priOutput); } } catch (NoSuchAlgorithmException e) { log.error("?", e); } }
From source file:net.solarnetwork.pki.bc.test.BCCertificateServiceTest.java
@Test public void signCertificate() throws Exception { X509Certificate cert = service.generateCertificate(TEST_DN, publicKey, privateKey); String csr = service.generatePKCS10CertificateRequestString(cert, privateKey); KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048, new SecureRandom()); KeyPair caKeypair = keyGen.generateKeyPair(); X509Certificate caCert = service.generateCertificationAuthorityCertificate(TEST_CA_DN, caKeypair.getPublic(), caKeypair.getPrivate()); X509Certificate signed = service.signCertificate(csr, caCert, caKeypair.getPrivate()); assertEquals("Issuer", caCert.getSubjectX500Principal(), signed.getIssuerX500Principal()); assertEquals("Subject", cert.getSubjectX500Principal(), signed.getSubjectX500Principal()); }
From source file:com.orange.oidc.tim.service.KryptoUtils.java
public static String getJwkPublic(KeyPair kp) { try {/*from w w w . j ava2s .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"); RSAPublicKeySpec kspec = (RSAPublicKeySpec) kfactory.getKeySpec(kp.getPublic(), RSAPublicKeySpec.class); jk.put("n", encodeB64(kspec.getModulus().toByteArray())); JSONArray ja = new JSONArray(); ja.put(jk); JSONObject jo = new JSONObject(); jo.put("keys", ja); // Log.d("getJwkPublic key: ",pubkey.toString()); // Log.d("getJwkPublic jwk: ",jo.toString()); return jo.toString(); } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:org.cesecore.keys.key.management.CertificateKeyAssociationDataTest.java
@Before public void generateCertificate() throws Exception { final KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); final Certificate certificate = CertTools.genSelfCert("C=SE,O=Test,CN=Test", 365, null, keys.getPrivate(), keys.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA, true); final List<String> tags = Arrays.asList(tag_array); ckad = new CertificateKeyAssociationData(certificate, tags, keyAlias); }
From source file:net.nicholaswilliams.java.licensing.TestLicenseManager.java
@BeforeClass public static void setUpClass() throws Exception { TestLicenseManager.control = EasyMock.createStrictControl(); TestLicenseManager.licenseProvider = TestLicenseManager.control.createMock(LicenseProvider.class); TestLicenseManager.publicKeyPasswordProvider = TestLicenseManager.control .createMock(PasswordProvider.class); TestLicenseManager.licensePasswordProvider = TestLicenseManager.control.createMock(PasswordProvider.class); TestLicenseManager.keyDataProvider = TestLicenseManager.control.createMock(PublicKeyDataProvider.class); TestLicenseManager.licenseValidator = TestLicenseManager.control.createMock(LicenseValidator.class); try {//from ww w.j a v a 2s. c o m LicenseManager.getInstance(); fail("Expected java.lang.IllegalArgumentException, got no exception."); } catch (IllegalArgumentException ignore) { } LicenseManagerProperties.setLicenseProvider(TestLicenseManager.licenseProvider); try { LicenseManager.getInstance(); fail("Expected java.lang.IllegalArgumentException, got no exception."); } catch (IllegalArgumentException ignore) { } LicenseManagerProperties.setPublicKeyDataProvider(TestLicenseManager.keyDataProvider); try { LicenseManager.getInstance(); fail("Expected java.lang.IllegalArgumentException, got no exception."); } catch (IllegalArgumentException ignore) { } LicenseManagerProperties.setPublicKeyPasswordProvider(TestLicenseManager.publicKeyPasswordProvider); LicenseManagerProperties.setLicensePasswordProvider(TestLicenseManager.licensePasswordProvider); LicenseManagerProperties.setLicenseValidator(TestLicenseManager.licenseValidator); LicenseManagerProperties.setCacheTimeInMinutes(0); LicenseManager.getInstance(); KeyPair keyPair = KeyPairGenerator.getInstance(KeyFileUtilities.keyAlgorithm).generateKeyPair(); TestLicenseManager.privateKey = keyPair.getPrivate(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyPair.getPublic().getEncoded()); IOUtils.write(Encryptor.encryptRaw(x509EncodedKeySpec.getEncoded(), TestLicenseManager.keyPassword), outputStream); TestLicenseManager.encryptedPublicKey = outputStream.toByteArray(); }