Java Code Examples for java.security.PrivateKey#getEncoded()
The following examples show how to use
java.security.PrivateKey#getEncoded() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RsaAesCryptoManager.java From pandroid with Apache License 2.0 | 6 votes |
protected void saveKeyPair(KeyPair keyPair) { PrivateKey privateKey = keyPair.getPrivate(); PublicKey publicKey = keyPair.getPublic(); // Store Public Key. X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec( publicKey.getEncoded()); try { FileOutputStream fos = context.openFileOutput(PREF_FILE + File.pathSeparator + "public.key", Context.MODE_PRIVATE); fos.write(x509EncodedKeySpec.getEncoded()); fos.close(); // Store Private Key. PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec( privateKey.getEncoded()); fos = context.openFileOutput(PREF_FILE + File.pathSeparator + "private.key", Context.MODE_PRIVATE); fos.write(pkcs8EncodedKeySpec.getEncoded()); fos.close(); } catch (Exception e) { logWrapper.e(TAG, e); } }
Example 2
Source File: OtrAndroidKeyManagerImpl.java From Zom-Android-XMPP with GNU General Public License v3.0 | 6 votes |
public void storeKeyPair (String userId, KeyPair keyPair) { // Store Private Key. PrivateKey privKey = keyPair.getPrivate(); PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privKey.getEncoded()); this.store.setProperty(userId + ".privateKey", pkcs8EncodedKeySpec.getEncoded()); try { // Store Public Key. PublicKey pubKey = keyPair.getPublic(); storePublicKey(userId, pubKey); //this will do saving } catch (Exception e) { throw new RuntimeException ("Error init local keypair"); } }
Example 3
Source File: KeyManager.java From Alpine with Apache License 2.0 | 6 votes |
/** * Saves a key pair. * * @param keyPair the key pair to save * @throws IOException if the files cannot be written * @since 1.0.0 */ public void save(final KeyPair keyPair) throws IOException { LOGGER.info("Saving key pair"); final PrivateKey privateKey = keyPair.getPrivate(); final PublicKey publicKey = keyPair.getPublic(); // Store Public Key final File publicKeyFile = getKeyPath(publicKey); publicKeyFile.getParentFile().mkdirs(); // make directories if they do not exist final X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey.getEncoded()); try (OutputStream fos = Files.newOutputStream(publicKeyFile.toPath())) { fos.write(x509EncodedKeySpec.getEncoded()); } // Store Private Key. final File privateKeyFile = getKeyPath(privateKey); privateKeyFile.getParentFile().mkdirs(); // make directories if they do not exist final PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded()); try (OutputStream fos = Files.newOutputStream(privateKeyFile.toPath())) { fos.write(pkcs8EncodedKeySpec.getEncoded()); } }
Example 4
Source File: KeyProtector.java From Bytecoder with Apache License 2.0 | 5 votes |
/** * Protects the given cleartext private key, using the password provided at * construction time. */ byte[] protect(PrivateKey key) throws Exception { // create a random salt (8 bytes) byte[] salt = new byte[8]; SunJCE.getRandom().nextBytes(salt); // create PBE parameters from salt and iteration count PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, ITERATION_COUNT); // create PBE key from password PBEKeySpec pbeKeySpec = new PBEKeySpec(this.password); SecretKey sKey = null; PBEWithMD5AndTripleDESCipher cipher; try { sKey = new PBEKey(pbeKeySpec, "PBEWithMD5AndTripleDES", false); // encrypt private key cipher = new PBEWithMD5AndTripleDESCipher(); cipher.engineInit(Cipher.ENCRYPT_MODE, sKey, pbeSpec, null); } finally { pbeKeySpec.clearPassword(); if (sKey != null) sKey.destroy(); } byte[] plain = key.getEncoded(); byte[] encrKey = cipher.engineDoFinal(plain, 0, plain.length); Arrays.fill(plain, (byte) 0x00); // wrap encrypted private key in EncryptedPrivateKeyInfo // (as defined in PKCS#8) AlgorithmParameters pbeParams = AlgorithmParameters.getInstance("PBE", SunJCE.getInstance()); pbeParams.init(pbeSpec); AlgorithmId encrAlg = new AlgorithmId (new ObjectIdentifier(PBE_WITH_MD5_AND_DES3_CBC_OID), pbeParams); return new EncryptedPrivateKeyInfo(encrAlg,encrKey).getEncoded(); }
Example 5
Source File: JsonXdhTest.java From wycheproof with Apache License 2.0 | 5 votes |
/** * An alternative way to generate an XDH key is to use specific names for the algorithm (i.e. * "X25519" or "X448"). These names fully specify key size and algorithm. * * <p>This test generates a key pair with such an algorithm name, serializes the keys, prints them * and the imports the keys back again. This allows to debug issues such as * https://bugs.openjdk.java.net/browse/JDK-8213493 */ public void testKeyGenerationWithName(String algorithmName) throws Exception { KeyPairGenerator kpg; try { kpg = KeyPairGenerator.getInstance(algorithmName); } catch (NoSuchAlgorithmException ex) { System.out.println(algorithmName + " is not supported"); return; } KeyPair kp = kpg.generateKeyPair(); PrivateKey priv = kp.getPrivate(); PublicKey pub = kp.getPublic(); // Encodings are a bit of a problem. byte[] privEncoded = priv.getEncoded(); System.out.println( algorithmName + " privat key format:" + priv.getFormat() + " encoded:" + TestUtil.bytesToHex(privEncoded)); byte[] pubEncoded = pub.getEncoded(); System.out.println( algorithmName + " public key format:" + pub.getFormat() + " encoded:" + TestUtil.bytesToHex(pubEncoded)); KeyFactory kf = KeyFactory.getInstance("XDH"); PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(privEncoded); PrivateKey unusedPrivKey2 = kf.generatePrivate(privKeySpec); X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pubEncoded); PublicKey unusedPubKey2 = kf.generatePublic(pubKeySpec); }
Example 6
Source File: KeyProtector.java From openjdk-8 with GNU General Public License v2.0 | 5 votes |
/** * Protects the given cleartext private key, using the password provided at * construction time. */ byte[] protect(PrivateKey key) throws Exception { // create a random salt (8 bytes) byte[] salt = new byte[8]; SunJCE.getRandom().nextBytes(salt); // create PBE parameters from salt and iteration count PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, 20); // create PBE key from password PBEKeySpec pbeKeySpec = new PBEKeySpec(this.password); SecretKey sKey = new PBEKey(pbeKeySpec, "PBEWithMD5AndTripleDES"); pbeKeySpec.clearPassword(); // encrypt private key PBEWithMD5AndTripleDESCipher cipher; cipher = new PBEWithMD5AndTripleDESCipher(); cipher.engineInit(Cipher.ENCRYPT_MODE, sKey, pbeSpec, null); byte[] plain = key.getEncoded(); byte[] encrKey = cipher.engineDoFinal(plain, 0, plain.length); // wrap encrypted private key in EncryptedPrivateKeyInfo // (as defined in PKCS#8) AlgorithmParameters pbeParams = AlgorithmParameters.getInstance("PBE", SunJCE.getInstance()); pbeParams.init(pbeSpec); AlgorithmId encrAlg = new AlgorithmId (new ObjectIdentifier(PBE_WITH_MD5_AND_DES3_CBC_OID), pbeParams); return new EncryptedPrivateKeyInfo(encrAlg,encrKey).getEncoded(); }
Example 7
Source File: RsaUtilTest.java From YiBo with Apache License 2.0 | 5 votes |
@Test public void myTest() throws NoSuchAlgorithmException { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); KeyPair keyPair = keyPairGenerator.generateKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); byte[] privateKeyBytes = privateKey.getEncoded(); String privateKeyStr = new String(Base64.encodeBase64(privateKeyBytes)); System.out.println("private key:" + privateKeyStr); PublicKey publicKey = keyPair.getPublic(); byte[] publicKeyBytes = publicKey.getEncoded(); String publicKeyStr = new String(Base64.encodeBase64(publicKeyBytes)); System.out.println("public key:" + publicKeyStr); System.out.println("**************************"); String plain = "我测试"; String cipherText = RsaUtil.encrypt(plain, publicKey); System.out.println(cipherText); String dePlain = RsaUtil.decrypt(cipherText, privateKey); System.out.println(dePlain); System.out.println("**************************"); String encrypted = RsaUtil.encryptWithPrivateKey("我靠我靠我靠", privateKeyStr.getBytes()); System.out.println(encrypted); String decrypted = RsaUtil.decryptWithPublicKey(encrypted, publicKeyStr.getBytes()); System.out.println(decrypted); System.out.println("**************************"); String encrypted2 = RsaUtil.encryptWithPublicKey("我靠我靠我靠", publicKeyStr.getBytes()); System.out.println(encrypted2); String decrypted2 = RsaUtil.decryptWithPrivateKey(encrypted2, privateKeyStr.getBytes()); System.out.println(decrypted2); }
Example 8
Source File: KeyProtector.java From jdk8u-jdk with GNU General Public License v2.0 | 5 votes |
/** * Protects the given cleartext private key, using the password provided at * construction time. */ byte[] protect(PrivateKey key) throws Exception { // create a random salt (8 bytes) byte[] salt = new byte[8]; SunJCE.getRandom().nextBytes(salt); // create PBE parameters from salt and iteration count PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, 20); // create PBE key from password PBEKeySpec pbeKeySpec = new PBEKeySpec(this.password); SecretKey sKey = new PBEKey(pbeKeySpec, "PBEWithMD5AndTripleDES"); pbeKeySpec.clearPassword(); // encrypt private key PBEWithMD5AndTripleDESCipher cipher; cipher = new PBEWithMD5AndTripleDESCipher(); cipher.engineInit(Cipher.ENCRYPT_MODE, sKey, pbeSpec, null); byte[] plain = key.getEncoded(); byte[] encrKey = cipher.engineDoFinal(plain, 0, plain.length); // wrap encrypted private key in EncryptedPrivateKeyInfo // (as defined in PKCS#8) AlgorithmParameters pbeParams = AlgorithmParameters.getInstance("PBE", SunJCE.getInstance()); pbeParams.init(pbeSpec); AlgorithmId encrAlg = new AlgorithmId (new ObjectIdentifier(PBE_WITH_MD5_AND_DES3_CBC_OID), pbeParams); return new EncryptedPrivateKeyInfo(encrAlg,encrKey).getEncoded(); }
Example 9
Source File: KeyProtector.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
/** * Protects the given cleartext private key, using the password provided at * construction time. */ byte[] protect(PrivateKey key) throws Exception { // create a random salt (8 bytes) byte[] salt = new byte[8]; SunJCE.getRandom().nextBytes(salt); // create PBE parameters from salt and iteration count PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, 20); // create PBE key from password PBEKeySpec pbeKeySpec = new PBEKeySpec(this.password); SecretKey sKey = new PBEKey(pbeKeySpec, "PBEWithMD5AndTripleDES"); pbeKeySpec.clearPassword(); // encrypt private key PBEWithMD5AndTripleDESCipher cipher; cipher = new PBEWithMD5AndTripleDESCipher(); cipher.engineInit(Cipher.ENCRYPT_MODE, sKey, pbeSpec, null); byte[] plain = key.getEncoded(); byte[] encrKey = cipher.engineDoFinal(plain, 0, plain.length); // wrap encrypted private key in EncryptedPrivateKeyInfo // (as defined in PKCS#8) AlgorithmParameters pbeParams = AlgorithmParameters.getInstance("PBE", SunJCE.getInstance()); pbeParams.init(pbeSpec); AlgorithmId encrAlg = new AlgorithmId (new ObjectIdentifier(PBE_WITH_MD5_AND_DES3_CBC_OID), pbeParams); return new EncryptedPrivateKeyInfo(encrAlg,encrKey).getEncoded(); }
Example 10
Source File: CertUtils.java From cloudstack with Apache License 2.0 | 5 votes |
public static String privateKeyToPem(final PrivateKey key) throws IOException { final PemObject pemObject = new PemObject("PRIVATE KEY", key.getEncoded()); final StringWriter sw = new StringWriter(); try (final PemWriter pw = new PemWriter(sw)) { pw.writeObject(pemObject); } return sw.toString(); }
Example 11
Source File: KeyProtector.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
/** * Protects the given cleartext private key, using the password provided at * construction time. */ byte[] protect(PrivateKey key) throws Exception { // create a random salt (8 bytes) byte[] salt = new byte[8]; SunJCE.getRandom().nextBytes(salt); // create PBE parameters from salt and iteration count PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, ITERATION_COUNT); // create PBE key from password PBEKeySpec pbeKeySpec = new PBEKeySpec(this.password); SecretKey sKey = new PBEKey(pbeKeySpec, "PBEWithMD5AndTripleDES"); pbeKeySpec.clearPassword(); // encrypt private key PBEWithMD5AndTripleDESCipher cipher; cipher = new PBEWithMD5AndTripleDESCipher(); cipher.engineInit(Cipher.ENCRYPT_MODE, sKey, pbeSpec, null); byte[] plain = key.getEncoded(); byte[] encrKey = cipher.engineDoFinal(plain, 0, plain.length); // wrap encrypted private key in EncryptedPrivateKeyInfo // (as defined in PKCS#8) AlgorithmParameters pbeParams = AlgorithmParameters.getInstance("PBE", SunJCE.getInstance()); pbeParams.init(pbeSpec); AlgorithmId encrAlg = new AlgorithmId (new ObjectIdentifier(PBE_WITH_MD5_AND_DES3_CBC_OID), pbeParams); return new EncryptedPrivateKeyInfo(encrAlg,encrKey).getEncoded(); }
Example 12
Source File: KeyProtector.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
/** * Protects the given cleartext private key, using the password provided at * construction time. */ byte[] protect(PrivateKey key) throws Exception { // create a random salt (8 bytes) byte[] salt = new byte[8]; SunJCE.getRandom().nextBytes(salt); // create PBE parameters from salt and iteration count PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, ITERATION_COUNT); // create PBE key from password PBEKeySpec pbeKeySpec = new PBEKeySpec(this.password); SecretKey sKey = null; PBEWithMD5AndTripleDESCipher cipher; try { sKey = new PBEKey(pbeKeySpec, "PBEWithMD5AndTripleDES"); // encrypt private key cipher = new PBEWithMD5AndTripleDESCipher(); cipher.engineInit(Cipher.ENCRYPT_MODE, sKey, pbeSpec, null); } finally { pbeKeySpec.clearPassword(); if (sKey != null) sKey.destroy(); } byte[] plain = key.getEncoded(); byte[] encrKey = cipher.engineDoFinal(plain, 0, plain.length); Arrays.fill(plain, (byte)0x00); // wrap encrypted private key in EncryptedPrivateKeyInfo // (as defined in PKCS#8) AlgorithmParameters pbeParams = AlgorithmParameters.getInstance("PBE", SunJCE.getInstance()); pbeParams.init(pbeSpec); AlgorithmId encrAlg = new AlgorithmId (new ObjectIdentifier(PBE_WITH_MD5_AND_DES3_CBC_OID), pbeParams); return new EncryptedPrivateKeyInfo(encrAlg,encrKey).getEncoded(); }
Example 13
Source File: KeyProtector.java From jdk8u60 with GNU General Public License v2.0 | 5 votes |
/** * Protects the given cleartext private key, using the password provided at * construction time. */ byte[] protect(PrivateKey key) throws Exception { // create a random salt (8 bytes) byte[] salt = new byte[8]; SunJCE.getRandom().nextBytes(salt); // create PBE parameters from salt and iteration count PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, 20); // create PBE key from password PBEKeySpec pbeKeySpec = new PBEKeySpec(this.password); SecretKey sKey = new PBEKey(pbeKeySpec, "PBEWithMD5AndTripleDES"); pbeKeySpec.clearPassword(); // encrypt private key PBEWithMD5AndTripleDESCipher cipher; cipher = new PBEWithMD5AndTripleDESCipher(); cipher.engineInit(Cipher.ENCRYPT_MODE, sKey, pbeSpec, null); byte[] plain = key.getEncoded(); byte[] encrKey = cipher.engineDoFinal(plain, 0, plain.length); // wrap encrypted private key in EncryptedPrivateKeyInfo // (as defined in PKCS#8) AlgorithmParameters pbeParams = AlgorithmParameters.getInstance("PBE", SunJCE.getInstance()); pbeParams.init(pbeSpec); AlgorithmId encrAlg = new AlgorithmId (new ObjectIdentifier(PBE_WITH_MD5_AND_DES3_CBC_OID), pbeParams); return new EncryptedPrivateKeyInfo(encrAlg,encrKey).getEncoded(); }
Example 14
Source File: KeyProtector.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
/** * Protects the given cleartext private key, using the password provided at * construction time. */ byte[] protect(PrivateKey key) throws Exception { // create a random salt (8 bytes) byte[] salt = new byte[8]; SunJCE.getRandom().nextBytes(salt); // create PBE parameters from salt and iteration count PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, ITERATION_COUNT); // create PBE key from password PBEKeySpec pbeKeySpec = new PBEKeySpec(this.password); SecretKey sKey = null; PBEWithMD5AndTripleDESCipher cipher; try { sKey = new PBEKey(pbeKeySpec, "PBEWithMD5AndTripleDES"); // encrypt private key cipher = new PBEWithMD5AndTripleDESCipher(); cipher.engineInit(Cipher.ENCRYPT_MODE, sKey, pbeSpec, null); } finally { pbeKeySpec.clearPassword(); if (sKey != null) sKey.destroy(); } byte[] plain = key.getEncoded(); byte[] encrKey = cipher.engineDoFinal(plain, 0, plain.length); Arrays.fill(plain, (byte)0x00); // wrap encrypted private key in EncryptedPrivateKeyInfo // (as defined in PKCS#8) AlgorithmParameters pbeParams = AlgorithmParameters.getInstance("PBE", SunJCE.getInstance()); pbeParams.init(pbeSpec); AlgorithmId encrAlg = new AlgorithmId (new ObjectIdentifier(PBE_WITH_MD5_AND_DES3_CBC_OID), pbeParams); return new EncryptedPrivateKeyInfo(encrAlg,encrKey).getEncoded(); }
Example 15
Source File: KeyProtector.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 5 votes |
/** * Protects the given cleartext private key, using the password provided at * construction time. */ byte[] protect(PrivateKey key) throws Exception { // create a random salt (8 bytes) byte[] salt = new byte[8]; SunJCE.getRandom().nextBytes(salt); // create PBE parameters from salt and iteration count PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, 20); // create PBE key from password PBEKeySpec pbeKeySpec = new PBEKeySpec(this.password); SecretKey sKey = new PBEKey(pbeKeySpec, "PBEWithMD5AndTripleDES"); pbeKeySpec.clearPassword(); // encrypt private key PBEWithMD5AndTripleDESCipher cipher; cipher = new PBEWithMD5AndTripleDESCipher(); cipher.engineInit(Cipher.ENCRYPT_MODE, sKey, pbeSpec, null); byte[] plain = key.getEncoded(); byte[] encrKey = cipher.engineDoFinal(plain, 0, plain.length); // wrap encrypted private key in EncryptedPrivateKeyInfo // (as defined in PKCS#8) AlgorithmParameters pbeParams = AlgorithmParameters.getInstance("PBE", SunJCE.getInstance()); pbeParams.init(pbeSpec); AlgorithmId encrAlg = new AlgorithmId (new ObjectIdentifier(PBE_WITH_MD5_AND_DES3_CBC_OID), pbeParams); return new EncryptedPrivateKeyInfo(encrAlg,encrKey).getEncoded(); }
Example 16
Source File: JCEUtils.java From java-11-examples with Apache License 2.0 | 4 votes |
public static byte[] serializePrivateKey(PrivateKey privateKey) { return privateKey.getEncoded(); }
Example 17
Source File: ServerConnection.java From protect with MIT License | 4 votes |
public void authenticateAndEstablishAuthKey() { if (authKey != null || socketOutStream == null || socketInStream == null) { return; } try { // if (conf.getProcessId() > remoteId) { // I asked for the connection, so I'm first on the auth protocol // DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); // } else { // I received a connection request, so I'm second on the auth protocol // DataInputStream dis = new DataInputStream(socket.getInputStream()); // } // Derive DH private key from replica's own RSA private key // TODO: Derive DH private value from private key or figure out how to use a // random one // TODO: Use KeyAgreement class PrivateKey signingKey = controller.getStaticConf().getPrivateKey(); BigInteger DHPrivKey = new BigInteger(signingKey.getEncoded()); // Create DH public key BigInteger myDHPubKey = controller.getStaticConf().getDHG().modPow(DHPrivKey, controller.getStaticConf().getDHP()); // turn it into a byte array byte[] bytes = myDHPubKey.toByteArray(); byte[] signature = TOMUtil.signMessage(signingKey, bytes); // send my DH public key and signature socketOutStream.writeInt(bytes.length); socketOutStream.write(bytes); socketOutStream.writeInt(signature.length); socketOutStream.write(signature); // receive remote DH public key and signature int dataLength = socketInStream.readInt(); bytes = new byte[dataLength]; int read = 0; do { read += socketInStream.read(bytes, read, dataLength - read); } while (read < dataLength); byte[] remote_Bytes = bytes; dataLength = socketInStream.readInt(); bytes = new byte[dataLength]; read = 0; do { read += socketInStream.read(bytes, read, dataLength - read); } while (read < dataLength); byte[] remote_Signature = bytes; // verify signature PublicKey remoteRSAPubkey = controller.getStaticConf().getPublicKey(remoteId); if (!TOMUtil.verifySignature(remoteRSAPubkey, remote_Bytes, remote_Signature)) { System.out.println(remoteId + " sent an invalid signature!"); shutdown(); return; } BigInteger remoteDHPubKey = new BigInteger(remote_Bytes); // Create secret key BigInteger secretKey = remoteDHPubKey.modPow(DHPrivKey, controller.getStaticConf().getDHP()); System.out.println("-- Diffie-Hellman complete with " + remoteId); SecretKeyFactory fac = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); PBEKeySpec spec = new PBEKeySpec(secretKey.toString().toCharArray()); // PBEKeySpec spec = new PBEKeySpec(PASSWORD.toCharArray()); authKey = fac.generateSecret(spec); macSend = Mac.getInstance(controller.getStaticConf().getHmacAlgorithm()); macSend.init(authKey); macReceive = Mac.getInstance(controller.getStaticConf().getHmacAlgorithm()); macReceive.init(authKey); macSize = macSend.getMacLength(); } catch (Exception ex) { ex.printStackTrace(); } }
Example 18
Source File: CryptoUtils.java From crate with Apache License 2.0 | 4 votes |
static byte[] getPrivateKeyBytes(PrivateKey privateKey) { PKCS8EncodedKeySpec encodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded()); return encodedKeySpec.getEncoded(); }
Example 19
Source File: TestPublicPrivateKeys.java From http4e with Apache License 2.0 | 4 votes |
private static void generateKeys( String keyAlgorithm, int numBits) { try { // Get the public/private key pair KeyPairGenerator keyGen = KeyPairGenerator.getInstance(keyAlgorithm); keyGen.initialize(numBits); KeyPair keyPair = keyGen.genKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); PublicKey publicKey = keyPair.getPublic(); System.out.println( "\n" + "Generating key/value pair using " + privateKey.getAlgorithm() + " algorithm"); // Get the bytes of the public and private keys byte[] privateKeyBytes = privateKey.getEncoded(); byte[] publicKeyBytes = publicKey.getEncoded(); // Get the formats of the encoded bytes String formatPrivate = privateKey.getFormat(); // PKCS#8 String formatPublic = publicKey.getFormat(); // X.509 System.out.println(" Private Key Format : " + formatPrivate); System.out.println(" Public Key Format : " + formatPublic); // The bytes can be converted back to public and private key objects KeyFactory keyFactory = KeyFactory.getInstance(keyAlgorithm); EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes); PrivateKey privateKey2 = keyFactory.generatePrivate(privateKeySpec); EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes); PublicKey publicKey2 = keyFactory.generatePublic(publicKeySpec); // The original and new keys are the same System.out.println( " Are both private keys equal? " + privateKey.equals(privateKey2)); System.out.println( " Are both public keys equal? " + publicKey.equals(publicKey2)); } catch (InvalidKeySpecException specException) { System.out.println("Exception"); System.out.println("Invalid Key Spec Exception"); } catch (NoSuchAlgorithmException e) { System.out.println("Exception"); System.out.println("No such algorithm: " + keyAlgorithm); } }
Example 20
Source File: Pkcs8Util.java From keystore-explorer with GNU General Public License v3.0 | 2 votes |
/** * PKCS #8 encode a private key. * * @return The encoding * @param privateKey * The private key */ public static byte[] get(PrivateKey privateKey) { return privateKey.getEncoded(); }