List of usage examples for java.security KeyPair getPrivate
public PrivateKey getPrivate()
From source file:org.apache.karaf.shell.ssh.keygenerator.PemWriter.java
public void writeKeyPair(String resource, KeyPair kp) throws IOException, FileNotFoundException { Collection<Object> items = new ArrayList<>(); items.add(new PEMItem(kp.getPrivate().getEncoded(), "PRIVATE KEY")); byte[] bytes = PEMUtil.encode(items); try (FileOutputStream os = new FileOutputStream(keyFile)) { os.write(bytes);//from ww w . ja v a 2s. c o m } }
From source file:org.apache.karaf.shell.ssh.keygenerator.OpenSSHGeneratorKeyFileProviderTest.java
@Test public void convertSimpleKey() throws Exception { File temp = File.createTempFile(this.getClass().getCanonicalName(), ".pem"); temp.deleteOnExit();/*from w ww . j ava 2 s .com*/ SimpleGeneratorHostKeyProvider simpleGenerator = new SimpleGeneratorHostKeyProvider(temp); simpleGenerator.setKeySize(2048); simpleGenerator.setAlgorithm("DSA"); List<KeyPair> keys = simpleGenerator.loadKeys(); KeyPair simpleKeyPair = keys.stream().findFirst().get(); Assert.assertEquals("DSA", simpleKeyPair.getPrivate().getAlgorithm()); OpenSSHKeyPairProvider provider = new OpenSSHKeyPairProvider(temp, "DSA", 2048); KeyPair convertedKeyPair = provider.loadKeys().iterator().next(); Assert.assertEquals("DSA", convertedKeyPair.getPrivate().getAlgorithm()); Assert.assertArrayEquals(simpleKeyPair.getPrivate().getEncoded(), convertedKeyPair.getPrivate().getEncoded()); Assert.assertArrayEquals(simpleKeyPair.getPublic().getEncoded(), convertedKeyPair.getPublic().getEncoded()); //also test that the original file has been replaced PKCS8Key pkcs8 = new PKCS8Key(Files.newInputStream(temp.toPath()), null); KeyPair keyPair = new KeyPair(pkcs8.getPublicKey(), pkcs8.getPrivateKey()); Assert.assertArrayEquals(simpleKeyPair.getPrivate().getEncoded(), keyPair.getPrivate().getEncoded()); }
From source file:info.fcrp.keepitsafe.bean.CryptBeanTest.java
@Test public void assymetric() throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(1024, new SecureRandom()); KeyPair kp = kpg.generateKeyPair(); PrivateKey priKey = kp.getPrivate(); PublicKey pubKey = kp.getPublic(); Cipher c = Cipher.getInstance("RSA"); String plain = "plain"; byte[] plainBytes = plain.getBytes(); c.init(Cipher.ENCRYPT_MODE, pubKey); c.update(plainBytes);/*from w w w . j a v a 2 s . c om*/ byte[] encBytes = c.doFinal(); String enc = Base64.encodeBase64String(encBytes); assertNotSame(plain, enc); c.init(Cipher.DECRYPT_MODE, priKey); c.update(encBytes); byte[] decBytes = c.doFinal(); String dec = new String(decBytes); assertEquals(plain, dec); }
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.wso2.iot.agent.utils.CommonUtils.java
/** * Generates keys, CSR and certificates for the devices. * @param context - Application context. * @param listener - DeviceCertCreationListener which provide device . *//*from w w w . j a v a2 s. co m*/ public static void generateDeviceCertificate(final Context context, final DeviceCertCreationListener listener) throws AndroidAgentException { if (context.getFileStreamPath(Constants.DEVICE_CERTIFCATE_NAME).exists()) { try { listener.onDeviceCertCreated( new BufferedInputStream(context.openFileInput(Constants.DEVICE_CERTIFCATE_NAME))); } catch (FileNotFoundException e) { Log.e(TAG, e.getMessage()); } } else { try { ServerConfig utils = new ServerConfig(); final KeyPair deviceKeyPair = KeyPairGenerator.getInstance(Constants.DEVICE_KEY_TYPE) .generateKeyPair(); X500Principal subject = new X500Principal(Constants.DEVICE_CSR_INFO); PKCS10CertificationRequest csr = new PKCS10CertificationRequest(Constants.DEVICE_KEY_ALGO, subject, deviceKeyPair.getPublic(), null, deviceKeyPair.getPrivate()); EndPointInfo endPointInfo = new EndPointInfo(); endPointInfo.setHttpMethod(org.wso2.iot.agent.proxy.utils.Constants.HTTP_METHODS.POST); endPointInfo.setEndPoint(utils.getAPIServerURL(context) + Constants.SCEP_ENDPOINT); endPointInfo.setRequestParams(Base64.encodeToString(csr.getEncoded(), Base64.DEFAULT)); new APIController().invokeAPI(endPointInfo, new APIResultCallBack() { @Override public void onReceiveAPIResult(Map<String, String> result, int requestCode) { try { CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); InputStream in = new ByteArrayInputStream( Base64.decode(result.get("response"), Base64.DEFAULT)); X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(null); keyStore.setKeyEntry(Constants.DEVICE_CERTIFCATE_ALIAS, (Key) deviceKeyPair.getPrivate(), Constants.DEVICE_CERTIFCATE_PASSWORD.toCharArray(), new java.security.cert.Certificate[] { cert }); keyStore.store(byteArrayOutputStream, Constants.DEVICE_CERTIFCATE_PASSWORD.toCharArray()); FileOutputStream outputStream = context.openFileOutput(Constants.DEVICE_CERTIFCATE_NAME, Context.MODE_PRIVATE); outputStream.write(byteArrayOutputStream.toByteArray()); byteArrayOutputStream.close(); outputStream.close(); try { listener.onDeviceCertCreated(new BufferedInputStream( context.openFileInput(Constants.DEVICE_CERTIFCATE_NAME))); } catch (FileNotFoundException e) { Log.e(TAG, e.getMessage()); } } catch (CertificateException | KeyStoreException | NoSuchAlgorithmException | IOException e) { Log.e(TAG, e.getMessage(), e); } } }, Constants.SCEP_REQUEST_CODE, context, true); } catch (NoSuchAlgorithmException e) { throw new AndroidAgentException("No algorithm for key generation", e); } catch (SignatureException e) { throw new AndroidAgentException("Invalid Signature", e); } catch (NoSuchProviderException e) { throw new AndroidAgentException("Invalid provider", e); } catch (InvalidKeyException e) { throw new AndroidAgentException("Invalid key", e); } } }
From source file:com.trsst.client.Client.java
private final static SignatureOptions getSignatureOptions(Signature signer, KeyPair signingKeys) throws SecurityException { SignatureOptions options = signer.getDefaultSignatureOptions(); options.setSigningAlgorithm("http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1"); options.setSignLinks(false); // don't sign atom:links options.setPublicKey(signingKeys.getPublic()); options.setSigningKey(signingKeys.getPrivate()); return options; }
From source file:jenkins.security.RSAConfidentialKey.java
/** * Obtains the private key (lazily.)//from w w w . ja v a 2s . 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:org.globus.gsi.bc.BouncyCastleOpenSSLKeyTest.java
public void testEncrypt() throws Exception { KeyPair keyPair = getKeyPair(); OpenSSLKey key = new BouncyCastleOpenSSLKey(keyPair.getPrivate()); assertTrue(!key.isEncrypted());//from ww w.j a v a2s. c o m key.encrypt(pwd); assertTrue(key.isEncrypted()); }
From source file:org.globus.gsi.bc.BouncyCastleOpenSSLKeyTest.java
public void testEncryptAES() throws Exception { KeyPair keyPair = getKeyPair(); OpenSSLKey key = new BouncyCastleOpenSSLKey(keyPair.getPrivate()); assertTrue(!key.isEncrypted());//from w w w .j ava 2 s . co m key.setEncryptionAlgorithm("AES-128-CBC"); key.encrypt(pwd); assertTrue(key.isEncrypted()); }
From source file:org.globus.gsi.bc.BouncyCastleOpenSSLKeyTest.java
public void testDecryptedToString() throws Exception { KeyPair keyPair = getKeyPair(); OpenSSLKey inKey = new BouncyCastleOpenSSLKey(keyPair.getPrivate()); assertTrue(!inKey.isEncrypted());/*from ww w.jav a 2s . co m*/ ByteArrayInputStream in = null; in = new ByteArrayInputStream(toString(inKey).getBytes()); OpenSSLKey outKey = new BouncyCastleOpenSSLKey(in); assertTrue(!outKey.isEncrypted()); in = new ByteArrayInputStream(toString(outKey).getBytes()); OpenSSLKey outKey2 = new BouncyCastleOpenSSLKey(in); assertTrue(!outKey2.isEncrypted()); }