java.security.PrivateKey#getEncoded ( )源码实例Demo

下面列出了java.security.PrivateKey#getEncoded ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。


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");
    }
}
 
源代码2 项目: Alpine   文件: KeyManager.java

/**
 * 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());
    }
}
 
源代码3 项目: pandroid   文件: RsaAesCryptoManager.java

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);
    }
}
 
源代码4 项目: cloudstack   文件: CertUtils.java

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();
}
 
源代码5 项目: jdk8u-dev-jdk   文件: KeyProtector.java

/**
 * 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();
}
 
源代码6 项目: TencentKona-8   文件: KeyProtector.java

/**
 * 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();
}
 
源代码7 项目: jdk8u60   文件: KeyProtector.java

/**
 * 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();
}
 
源代码8 项目: openjdk-jdk8u   文件: KeyProtector.java

/**
 * 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();
}
 

/**
 * 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();
}
 
源代码10 项目: Bytecoder   文件: KeyProtector.java

/**
 * 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();
}
 
源代码11 项目: openjdk-jdk9   文件: KeyProtector.java

/**
 * 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();
}
 
源代码12 项目: jdk8u-jdk   文件: KeyProtector.java

/**
 * 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();
}
 
源代码13 项目: YiBo   文件: RsaUtilTest.java

@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);
}
 
源代码14 项目: openjdk-8   文件: KeyProtector.java

/**
 * 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();
}
 
源代码15 项目: wycheproof   文件: JsonXdhTest.java

/**
 * 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);
}
 
源代码16 项目: protect   文件: ServerConnection.java

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();
	}
}
 
源代码17 项目: java-11-examples   文件: JCEUtils.java

public static byte[] serializePrivateKey(PrivateKey privateKey) {
    return privateKey.getEncoded();
}
 
源代码18 项目: crate   文件: CryptoUtils.java

static byte[] getPrivateKeyBytes(PrivateKey privateKey) {
    PKCS8EncodedKeySpec encodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
    return encodedKeySpec.getEncoded();
}
 
源代码19 项目: http4e   文件: TestPublicPrivateKeys.java

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);

        }

    }
 
源代码20 项目: keystore-explorer   文件: Pkcs8Util.java

/**
 * PKCS #8 encode a private key.
 *
 * @return The encoding
 * @param privateKey
 *            The private key
 */
public static byte[] get(PrivateKey privateKey) {
	return privateKey.getEncoded();
}
 
 方法所在类