Example usage for java.security KeyPair getPrivate

List of usage examples for java.security KeyPair getPrivate

Introduction

In this page you can find the example usage for java.security KeyPair getPrivate.

Prototype

public PrivateKey getPrivate() 

Source Link

Document

Returns a reference to the private key component of this key pair.

Usage

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

/**
 * ??//from  w w  w . ja  va 2s.co m
 * 
 * @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:hh.learnj.test.license.test.rsacoder.RSACoder.java

/**
 * ?/*from   w  w  w  .j  av  a2  s  .  com*/
 * 
 * @return Map Map
 */
public static Map<String, Object> initKey() throws Exception {
    // ?
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
    // ??
    keyPairGenerator.initialize(KEY_SIZE);
    // ?
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    // 
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    // ?
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    // map
    Map<String, Object> keyMap = new HashMap<String, Object>();
    keyMap.put(PUBLIC_KEY, publicKey);
    keyMap.put(PRIVATE_KEY, privateKey);
    return keyMap;

}

From source file:com.google.jenkins.plugins.credentials.oauth.P12ServiceAccountConfigTestUtil.java

private static KeyStore createKeyStore(KeyPair keyPair) throws KeyStoreException, CertificateException,
        NoSuchAlgorithmException, IOException, OperatorCreationException, NoSuchProviderException {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    keyStore.load(null, null);//from www . ja  v a2s . co m
    keyStore.setKeyEntry(DEFAULT_P12_ALIAS, keyPair.getPrivate(), DEFAULT_P12_SECRET.toCharArray(),
            new Certificate[] { generateCertificate(keyPair) });
    return keyStore;
}

From source file:com.vmware.identity.openidconnect.client.TestUtils.java

static X509Certificate generateCertificate(KeyPair keyPair, String dn, String subjectAltName) throws Exception {
    ContentSigner sigGen = new JcaContentSignerBuilder("SHA1withRSA").build(keyPair.getPrivate());

    Date startDate = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000);
    Date endDate = new Date(System.currentTimeMillis() + 365 * 24 * 60 * 60 * 1000);

    X509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder(new X500Name("CN=" + dn),
            new BigInteger(64, new SecureRandom()), startDate, endDate, new X500Name("CN=" + dn),
            keyPair.getPublic());//w w  w . j ava 2 s  .  co m
    if (subjectAltName != null) {
        v3CertGen
                .addExtension(Extension.subjectAlternativeName, true,
                        new GeneralNames(new GeneralName(GeneralName.otherName,
                                new DERSequence(new ASN1Encodable[] {
                                        new DERObjectIdentifier("1.3.6.1.4.1.311.20.2.3"),
                                        new DERTaggedObject(true, 0, new DERUTF8String(subjectAltName)) }))));
    }

    X509CertificateHolder certHolder = v3CertGen.build(sigGen);
    X509Certificate x509Certificate = new JcaX509CertificateConverter().getCertificate(certHolder);
    return x509Certificate;
}

From source file:org.artifactory.security.crypto.CryptoHelper.java

public static SecretKey generatePbeKeyFromKeyPair(KeyPair keyPair) {
    return generatePbeKey(ArtifactoryBase64.toBase64(keyPair.getPrivate().getEncoded()));
}

From source file:im.whistle.crypt.Crypt.java

/**
 * Generates a private/public key pair.//  w  ww.  j a v  a 2s.  c  o m
 * @param args Arguments, element at 0 is the key size
 * @param callback Callback
 */
public static void genkeys(JSONArray args, AsyncCallback<JSONArray> callback) {
    try {
        Log.i("whistle", "Generating key pair ...");
        PRNGProvider.init(); // Ensure OpenSSL fix
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        int bits = args.getInt(0);
        int exp = args.getInt(1);
        keyPairGenerator.initialize(new RSAKeyGenParameterSpec(bits, BigInteger.valueOf(exp)));
        KeyPair keyPair = keyPairGenerator.genKeyPair();
        String priv = "-----BEGIN RSA PRIVATE KEY-----\n"
                + Base64.encodeToString(keyPair.getPrivate().getEncoded(), Base64.DEFAULT).trim()
                + "\n-----END RSA PRIVATE KEY-----";
        String pub = "-----BEGIN PUBLIC KEY-----\n"
                + Base64.encodeToString(keyPair.getPublic().getEncoded(), Base64.DEFAULT).trim()
                + "\n-----END PUBLIC KEY-----";
        JSONArray res = new JSONArray();
        res.put(priv);
        res.put(pub);
        callback.success(res);
    } catch (Exception ex) {
        Log.w("whistle", "Key pair generation failed: " + ex.getMessage());
        callback.error(ex);
    }
}

From source file:net.firejack.platform.web.security.x509.KeyUtils.java

public static InputStream readCrypt(File file, File keystore) {
    if (!file.exists())
        return null;

    InputStream stream = null;/*w w w  . j  av  a2 s.c  o  m*/
    try {
        if (keystore.exists()) {
            KeyPair keyPair = load(keystore);
            byte[] decrypt = decrypt(keyPair.getPrivate(), FileUtils.readFileToByteArray(file));
            stream = new ByteArrayInputStream(decrypt);
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }

    return stream;
}

From source file:com.owncloud.android.utils.PushUtils.java

private static int generateRsa2048KeyPair() {
    String keyPath = MainApp.getStoragePath() + File.separator + MainApp.getDataFolder() + File.separator
            + KEYPAIR_FOLDER;/* w ww  .  ja va  2 s  . c  o  m*/

    String privateKeyPath = keyPath + File.separator + KEYPAIR_FILE_NAME + KEYPAIR_PRIV_EXTENSION;
    String publicKeyPath = keyPath + File.separator + KEYPAIR_FILE_NAME + KEYPAIR_PUB_EXTENSION;
    File keyPathFile = new File(keyPath);

    if (!new File(privateKeyPath).exists() && !new File(publicKeyPath).exists()) {
        try {
            if (!keyPathFile.exists()) {
                keyPathFile.mkdir();
            }
            KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
            keyGen.initialize(2048);

            KeyPair pair = keyGen.generateKeyPair();
            int statusPrivate = saveKeyToFile(pair.getPrivate(), privateKeyPath);
            int statusPublic = saveKeyToFile(pair.getPublic(), publicKeyPath);

            if (statusPrivate == 0 && statusPublic == 0) {
                // all went well
                return 0;
            } else {
                return -2;
            }
        } catch (NoSuchAlgorithmException e) {
            Log_OC.d(TAG, "RSA algorithm not supported");
        }
    } else {
        // we already have the key
        return -1;
    }

    // we failed to generate the key
    return -2;
}

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

/**
 * ?DSA??p,q,g,j,x,y// w w w.  j a  v a 2  s .  com
 * 
 * @param seed
 *            ??
 * @throws Exception
 * @author huangbuji
 *         <p />
 *         Create at 2014-2-8 ?4:45:26
 */
@SuppressWarnings("restriction")
public static void genKey(String seed) throws Exception {
    KeyPairGenerator keygen = KeyPairGenerator.getInstance("DSA");
    SecureRandom random = new SecureRandom();
    random.setSeed(seed.getBytes("utf8"));
    keygen.initialize(1024, random);

    KeyPair keyPair = keygen.generateKeyPair();
    DSAPublicKeyImpl publicKey = (DSAPublicKeyImpl) keyPair.getPublic();
    DSAPrivateKey privateKey = (DSAPrivateKey) keyPair.getPrivate();
    DSAParams dsaParams = privateKey.getParams();
    Base64 base64 = new Base64();
    String p = new String(base64.encode(dsaParams.getP().toByteArray()), "utf8");
    String q = new String(base64.encode(dsaParams.getQ().toByteArray()), "utf8");
    String g = new String(base64.encode(dsaParams.getG().toByteArray()), "utf8");
    String x = new String(base64.encode(privateKey.getX().toByteArray()), "utf8");
    String y = new String(base64.encode(publicKey.getY().toByteArray()), "utf8");
    System.out.println("P: " + p);
    System.out.println("Q: " + q);
    System.out.println("G: " + g);
    System.out.println("X: " + x);
    System.out.println("Y: " + y);

    String publicKeyString = new String(base64.encode(publicKey.getEncoded()), "utf8");
    String privateKeyString = new String(base64.encode(privateKey.getEncoded()), "utf8");
    System.err.println("public: " + publicKeyString);
    System.err.println("private: " + privateKeyString);

    File publicFile = new File("D:/binPublic.ky");
    File privateFile = new File("D:/binPrivate.ky");
    FileOutputStream out = new FileOutputStream(publicFile);
    out.write(publicKey.getEncoded());
    out.flush();
    out.close();
    out = new FileOutputStream(privateFile);
    out.write(privateKey.getEncoded());
    out.flush();
    out.close();
}

From source file:com.intuit.s3encrypt.S3Encrypt.java

public static void saveKeyPair(String filename, KeyPair keyPair) throws IOException {
    PublicKey publicKey = keyPair.getPublic();
    PrivateKey privateKey = keyPair.getPrivate();

    // Save public key to file.
    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey.getEncoded());
    FileOutputStream keyfos = new FileOutputStream(filename + ".pub");
    keyfos.write(x509EncodedKeySpec.getEncoded());
    keyfos.close();/*w  w  w  .  ja  v  a2  s  .  c  o m*/

    // Save private key to file.
    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
    keyfos = new FileOutputStream(filename);
    keyfos.write(pkcs8EncodedKeySpec.getEncoded());
    keyfos.close();

}