Example usage for java.security PrivateKey getEncoded

List of usage examples for java.security PrivateKey getEncoded

Introduction

In this page you can find the example usage for java.security PrivateKey getEncoded.

Prototype

public byte[] getEncoded();

Source Link

Document

Returns the key in its primary encoding format, or null if this key does not support encoding.

Usage

From source file:de.alpharogroup.crypto.key.PrivateKeyExtensions.java

/**
 * Transform the given {@link PrivateKey} to a hexadecimal {@link String} value.
 *
 * @param privateKey//from  w  w  w. j av  a2  s.  c  o  m
 *            the private key
 * @param lowerCase
 *            the flag if the result shell be transform in lower case. If true the result is
 * @return the new hexadecimal {@link String} value.
 */
public static String toHexString(final PrivateKey privateKey, final boolean lowerCase) {
    final String hexString = HexExtensions.toHexString(privateKey.getEncoded(), lowerCase);
    return hexString;
}

From source file:hudson.plugins.ec2.EC2AxisPrivateKey.java

static String digest(PrivateKey k) throws IOException {
    try {/* www  .ja v a2  s  . co  m*/
        MessageDigest md5 = MessageDigest.getInstance("SHA1");

        DigestInputStream in = new DigestInputStream(new ByteArrayInputStream(k.getEncoded()), md5);
        try {
            while (in.read(new byte[128]) > 0)
                ; // simply discard the input
        } finally {
            in.close();
        }
        StringBuilder buf = new StringBuilder();
        char[] hex = Hex.encodeHex(md5.digest());
        for (int i = 0; i < hex.length; i += 2) {
            if (buf.length() > 0)
                buf.append(':');
            buf.append(hex, i, 2);
        }
        return buf.toString();
    } catch (NoSuchAlgorithmException e) {
        throw new AssertionError(e);
    }
}

From source file:com.vimukti.accounter.developer.api.PublicKeyGenerator.java

private static void generate() throws NoSuchAlgorithmException, NoSuchProviderException,
        InvalidKeySpecException, KeyStoreException, CertificateException, IOException, URISyntaxException {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    random.setSeed("VimTech".getBytes("UTF-8"));
    keyGen.initialize(1024, random);/*from   w w w  .j a  v  a2s .c  o  m*/

    KeyPair pair = keyGen.generateKeyPair();
    PrivateKey priv = pair.getPrivate();
    PublicKey pub = pair.getPublic();
    System.out.println(priv);
    System.out.println(pub);

    byte[] encoded = pub.getEncoded();
    byte[] encodeBase64 = Base64.encodeBase64(encoded);
    System.out.println("Public Key:" + new String(encodeBase64));

    byte[] encodedPrv = priv.getEncoded();
    byte[] encodeBase64Prv = Base64.encodeBase64(encodedPrv);
    System.out.println("Private Key:" + new String(encodeBase64Prv));

    byte[] decodeBase64 = Base64.decodeBase64(encodeBase64);
    X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(decodeBase64);
    KeyFactory keyFactory = KeyFactory.getInstance("DSA");

    System.out.println(keyFactory.generatePublic(pubKeySpec).equals(pub));
}

From source file:net.arccotangent.pacchat.filesystem.KeyManager.java

private static void saveKeys(PrivateKey privkey, PublicKey pubkey) {
    km_log.i("Saving keys to disk.");

    X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubkey.getEncoded());
    PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(privkey.getEncoded());

    try {//from  w w  w.  j  a  v a  2 s .  com
        km_log.i(pubkeyFile.createNewFile() ? "Creation of public key file successful."
                : "Creation of public key file failed!");

        FileOutputStream pubOut = new FileOutputStream(pubkeyFile);
        pubOut.write(Base64.encodeBase64(pubSpec.getEncoded()));
        pubOut.flush();
        pubOut.close();

    } catch (IOException e) {
        km_log.e("Error while saving public key!");
        e.printStackTrace();
    }

    try {
        km_log.i(privkeyFile.createNewFile() ? "Creation of private key file successful."
                : "Creation of private key file failed!");

        FileOutputStream privOut = new FileOutputStream(privkeyFile);
        privOut.write(Base64.encodeBase64(privSpec.getEncoded()));
        privOut.flush();
        privOut.close();

    } catch (IOException e) {
        km_log.e("Error while saving private key!");
        e.printStackTrace();
    }

    km_log.i("Finished saving keys to disk. Operation appears successful.");
}

From source file:cloudeventbus.pki.CertificateUtils.java

public static void savePrivateKey(PrivateKey privateKey, String fileName) throws IOException {
    try (final OutputStream outputStream = Files.newOutputStream(Paths.get(fileName),
            StandardOpenOption.CREATE_NEW)) {
        outputStream.write(privateKey.getEncoded());
    }/*from  ww w  .j av a  2  s  .  c o m*/
}

From source file:io.vertx.config.vault.utils.Certificates.java

/**
 * See https://stackoverflow.com/questions/3313020/write-x509-certificate-into-pem-formatted-string-in-java
 *
 * @param key  An RSA private key//from  www  .ja  v a2  s  .  co m
 * @param file a file to which the private key will be written in PEM format
 * @throws FileNotFoundException
 */
private static void writePrivateKeyToPem(final PrivateKey key, File file) throws IOException {
    final Base64.Encoder encoder = Base64.getEncoder();

    final String keyHeader = "-----BEGIN PRIVATE KEY-----\n";
    final String keyFooter = "\n-----END PRIVATE KEY-----";
    final byte[] keyBytes = key.getEncoded();
    final String keyContents = new String(encoder.encode(keyBytes));
    final String keyPem = keyHeader + keyContents + keyFooter;
    FileUtils.write(file, keyPem);
}

From source file:com.aqnote.shared.cryptology.asymmetric.dsa.DSAKeyPairGenTest.java

public static void generator() throws NoSuchAlgorithmException, FileNotFoundException, IOException {
    KeyPairGenerator keygen = KeyPairGenerator.getInstance(ALGORITHM);

    // ???/*from  w w w .ja v a 2s .  com*/
    SecureRandom secrand = new SecureRandom();
    secrand.setSeed(seed); // ??
    // ??, ??keysize ?. 512  1024  64 ?
    keygen.initialize(512, secrand);
    // ?pubkey?prikey
    KeyPair keys = keygen.generateKeyPair(); // ?
    PublicKey pubkey = keys.getPublic();
    PrivateKey prikey = keys.getPrivate();

    byte[] pubkeyByteArray = Base64.encodeBase64(pubkey.getEncoded());
    OutputStream os = new FileOutputStream(new File(PUBKEY_FILE_NAME));
    ByteArrayInputStream bais = new ByteArrayInputStream(pubkeyByteArray);
    StreamUtil.io(bais, os);
    bais.close();
    os.close();

    byte[] prikeyByteArray = Base64.encodeBase64(prikey.getEncoded());
    os = new FileOutputStream(new File(PRIKEY_FILE_NAME));
    bais = new ByteArrayInputStream(prikeyByteArray);
    StreamUtil.io(bais, os);
    bais.close();
    os.close();
}

From source file:com.znsx.util.licence.LicenceUtil.java

/**
 * ??//  ww w. j av a2 s . com
 * 
 * @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:com.boubei.tss.modules.license.LicenseFactory.java

/**
 * ???/* w  ww  . j  av  a  2 s.  c  o m*/
 * ????hacker??license
 * @throws Exception
 */
public static void generateKey() throws Exception {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
    keyGen.initialize(1024, new SecureRandom());
    KeyPair pair = keyGen.generateKeyPair();
    PrivateKey priv = pair.getPrivate();
    PublicKey pub = pair.getPublic();

    log.info("?");
    DataOutputStream out = new DataOutputStream(new FileOutputStream(PUBLIC_KEY_FILE));
    out.writeBytes(EasyUtils.encodeHex(pub.getEncoded()));
    out.close();
    log.info("??" + PUBLIC_KEY_FILE);

    out = new DataOutputStream(new FileOutputStream(PRIVATE_KEY_FILE));
    out.writeBytes(EasyUtils.encodeHex(priv.getEncoded()));
    out.close();
    log.info("??" + PRIVATE_KEY_FILE);
}

From source file:com.vexsoftware.votifier.crypto.RSAIO.java

/**
 * Saves the key pair to the disk./*from   w w  w. j a v  a  2s.  c o  m*/
 * 
 * @param directory
 *            The directory to save to
 * @param keyPair
 *            The key pair to save
 * @throws Exception
 *             If an error occurs
 */
public static void save(File directory, KeyPair keyPair) throws Exception {
    PrivateKey privateKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();

    // Store the public key.
    X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(publicKey.getEncoded());
    FileOutputStream out = new FileOutputStream(directory + "/public.key");
    out.write(DatatypeConverter.printBase64Binary(publicSpec.getEncoded()).getBytes());
    out.close();

    // Store the private key.
    PKCS8EncodedKeySpec privateSpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
    out = new FileOutputStream(directory + "/private.key");
    out.write(DatatypeConverter.printBase64Binary(privateSpec.getEncoded()).getBytes());
    out.close();
}