Example usage for java.security.interfaces RSAPrivateKey getEncoded

List of usage examples for java.security.interfaces RSAPrivateKey getEncoded

Introduction

In this page you can find the example usage for java.security.interfaces RSAPrivateKey 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:cn.util.RSAUtils.java

public static void main(String[] args) throws Exception {
    // TODO Auto-generated method stub
    //      HashMap<String, Object> map = RSAUtils.getKeys();
    //      //??//from  w  w w .j av a  2s.c  o  m
    //      RSAPublicKey publicKey = (RSAPublicKey) map.get("public");
    //      RSAPrivateKey privateKey = (RSAPrivateKey) map.get("private");

    //
    String ming = "wow";
    //??
    RSAPublicKey pubKey = RSAUtils.getPublicKey();
    RSAPrivateKey priKey = RSAUtils.getPrivateKey();
    System.err.println(":" + Base64Util.encryptBASE64(pubKey.getEncoded()));
    System.err.println("?:" + Base64Util.encryptBASE64(priKey.getEncoded()));

    //?
    String mi = RSAUtils.encryptByPublicKey(ming);
    System.err.println("?:" + mi);
    //?
    //mi="aYlJTFE+cQjwsVkhmQrFnlwSPSidfPFbSaez8qw47xEfqwhPHX9na+7KoFwere3F2Incr0OoBhNt\nK8cqKwHtzuvJMW3/rz0X8n9Jld22lrsh9TOcEiq3Xwk3jTfNhGNnOEQIsOYVZs3Qqumdm0tAu7y6\nBHSE8kbfhRIPsqOys+0=";

    String[] mis = mi.split("#");

    String ming1 = "";
    for (String string : mis) {
        ming1 += RSAUtils.decryptByPrivateKey(string);
    }
    System.err.println("?:" + ming);
    System.err.println("?:" + ming1);
    // String a = "cVqjXrpazESBCFmZy5HxIy+C5o0PbYk9iCtBHBCGi8TMRPp2LpsVblrZIGrCw4s/fPEJp5pL7pBfZw4HDx412OfQpMCxezTltNNRWQBbFYCz/FHj6GeX7KAnkZhTC4hTZSHp1EyIa5EMsF6xdFtHuki98KS+75L3Z1Iln1efk2Y=";
    //      System.out.println(RSAUtils.decryptByPrivateKey(a));
    //      System.out.println(RSAUtils.decryptByPrivateKey(null));
    //      

    RSAPrivateKey privateKey = getPrivateKey();
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.DECRYPT_MODE, privateKey);
    //
    //int key_len = privateKey.getModulus().bitLength() / 8;

    String srcstring = "NKUsmMdJpSeAVFSk3hMwBoWsA7t/wOMc8hfzo2dwPIULOo1y0AUwPTDxVLw7AK1888rdyp/3U38y5eQUjuNQH68XN4jm7MHdRm+bnO6XUHuZLiXNFkLpVCAM5hVh6TTcOz3QIE9rhP+Up1WRxnq/PDuM/cXIeNWjBLbW4Iic9/w=#fRdhSf+a3xVktmJ6J0AJTW30wqpwQslN0Bxdyzpyr6u6VEj/Vo/5MpzZsVeIyBU/CzVvvkrvs5LKTagaA3M4thH3mz4gfMTrw746n4NhujZEUEehvNQIFdUBjKWPAI0XUtdcQQTtdUJbIWmuhTYxKParm0G8cNz5DSTRUTIw2fQ=#a9CaDtGkhVQNwgxHl0oJ8I/383pE3kE8yF76OyDtfeQsT50izuk44xQ34ersgzKkKSA8IB0W3SSw2bedsaj8A9dxrSf+S8S8w/Sg3G3/IA8pKaQqJD4idTCUFxjczf32aQbv+eUbs7fenAPKb3rpn+R+Q/c5y6jTEG5h+H27MsY=#N/dn52TTgJ+EoxTSp3weagZ+ggrIPl4rtKfzo0f/j2lMtXMfCQN7xgGiwDpv4Rele/58NV2X0ezDXjB3wtVugIA3nhKSNnsjEs/os1Zl2XO1EKuTnLGSJFSPS6yyr4o0wxHEeA52qA1UXaYS9clpjraXCDWuRrTpyQfONVDXGZ4=#P48NIZj+L8stk0CCNwAQmKZPH0/7GfOhhc9s/MONVPHBPRYo9N47Kb71PJszhrLsoEM2/VZD1Ech4HH8UmWhW6XPnVAWy/lS1nZDD/GEoTZvoN4Rw7oiWUGj2i+2SMyjcET9mnVPBUrgTmP8He5OFV6oIa1mAN95V4UkbXwYApw=#h79I/zTTAc2TA7j4k2wq5hrotElhskZudnuTViRvR2Ot9rAlFzdl1WasY0e+9pi7dCi40F5+2U7eVNuWLA9qvFKwgUSxA+z6FI++p0fAGsboJna9qwcplByYWh6DFPiPVFlRD2CTOZU+U/rfFn8wRT/qgLGyNI23/2el0fC1Bb0=";

    String stringarray[] = srcstring.split("#");

    List<byte[]> srcArrays = new ArrayList<byte[]>();

    for (String stemp : stringarray) {
        byte[] byte_temp = Base64Util.decryptBASE64(stemp);
        byte_temp = cipher.doFinal(byte_temp);
        srcArrays.add(byte_temp);

    }

    byte[] byte_sta = sysCopy(srcArrays);

    System.err.println(new String(byte_sta));
}

From source file:hh.learnj.test.license.test.rsa.RSATest.java

/**
 * ?/*  w  w  w .  j a  v a  2  s .  co  m*/
 * 
 * @throws Exception
 */
static void generatorKeyPair() throws Exception {
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(ALGORITHM_RSA);
    keyPairGen.initialize(1024);
    KeyPair keyPair = keyPairGen.generateKeyPair();
    RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
    byte[] keyBs = rsaPublicKey.getEncoded();
    publicKey = encodeBase64(keyBs);
    System.out.println("?\r\n" + publicKey);
    RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
    keyBs = rsaPrivateKey.getEncoded();
    privateKey = encodeBase64(keyBs);
    System.out.println("??\r\n" + privateKey);
}

From source file:com.security.ch08_rsa.RSACoderTextKey.java

/**
 * ?/*from   w  ww. j ava 2s.  c o m*/
 *
 * @return Map Map
 * @throws Exception
 */
public static Map<String, String> initKey(UUID licenseCode) throws Exception {
    // ?
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);

    // ??
    //        keyPairGen.initialize(KEY_SIZE);
    keyPairGen.initialize(KEY_SIZE, new SecureRandom(licenseCode.toString().getBytes(UTF_8)));

    // ?
    KeyPair keyPair = keyPairGen.generateKeyPair();

    // 
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

    // ?
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

    // ?
    Map<String, String> keyMap = new HashMap<String, String>();

    keyMap.put(PUBLIC_KEY, Base64.encodeBase64String(publicKey.getEncoded()));
    keyMap.put(PRIVATE_KEY, Base64.encodeBase64String(privateKey.getEncoded()));
    keyMap.put(LICENSE_CODE, licenseCode.toString());

    return keyMap;
}

From source file:com.kuzumeji.platform.standard.SecurityService.java

/**
 * RSA???//from   w  w  w  . ja v  a2s  .c  o m
 * <dl>
 * <dt>?
 * <dd>RSA???
 * </dl>
 * @param name RSA???
 * @param keyPair RSA?
 */
public void saveKeyPair(final String name, final KeyPair keyPair) {
    try {
        final Properties property = new PropertyService(PROPERTY_NAME).getProperty();
        final RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        property.setProperty(String.format(KEY_PUBLIC_ENCODED, name),
                Hex.encodeHexString(publicKey.getEncoded()));
        final RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        property.setProperty(String.format(KEY_PRIVATE_ENCODED, name),
                Hex.encodeHexString(privateKey.getEncoded()));
        try (FileOutputStream stream = new FileOutputStream(
                Thread.currentThread().getContextClassLoader().getResource(PROPERTY_NAME).getPath());) {
            property.store(stream, "RSAPublicKey and RSAPrivateKey");
        }
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.openbaton.nfvo.core.api.KeyManagement.java

@Override
public String generateKey(String projectId, String name) throws IOException, NoSuchAlgorithmException {
    log.debug("Generating keypair");
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(2048);// w ww .  ja  v a 2s. com
    KeyPair keyPair = keyGen.genKeyPair();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    String publicKeyString = encodePublicKey(publicKey, name);
    Key key = new Key();
    key.setName(name);
    key.setProjectId(projectId);
    key.setFingerprint(calculateFingerprint(publicKey.getEncoded()));
    key.setPublicKey(publicKeyString);
    log.debug(publicKeyString);
    keyRepository.save(key);
    log.info("Added new key: " + key);
    return parsePrivateKey(privateKey.getEncoded());
}

From source file:com.kuzumeji.platform.standard.SecurityServiceTest.java

@Test
public void testKeyPair() {
    // RSA???//from  w  w  w .  j  ava2s .co  m
    final KeyPair keyPair = testee.generateKeyPair();
    final RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    final RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    LOG.debug("?->{}", dumpKeyPair(publicKey));
    LOG.debug("?->{}", dumpKeyPair(privateKey));
    // RSA???/
    testee.saveKeyPair("testee", keyPair);
    final KeyPair keyPair2 = testee.loadKeyPair("testee");
    assertThat(keyPair2.getPublic().getAlgorithm(), is(publicKey.getAlgorithm()));
    assertThat(keyPair2.getPublic().getFormat(), is(publicKey.getFormat()));
    assertThat(keyPair2.getPublic().getEncoded(), is(publicKey.getEncoded()));
    assertThat(keyPair2.getPrivate().getAlgorithm(), is(privateKey.getAlgorithm()));
    assertThat(keyPair2.getPrivate().getFormat(), is(privateKey.getFormat()));
    assertThat(keyPair2.getPrivate().getEncoded(), is(privateKey.getEncoded()));
    // ???(??)
    final File file = testee.savePublicKeyFile(publicKey);
    LOG.debug("? : {}", file.getPath());
}

From source file:se.leap.bitmaskclient.ProviderAPI.java

private boolean loadCertificate(String cert_string) {
    try {/*from   ww w. ja v a2 s  .c  o m*/
        // API returns concatenated cert & key.  Split them for OpenVPN options
        String certificateString = null, keyString = null;
        String[] certAndKey = cert_string.split("(?<=-\n)");
        for (int i = 0; i < certAndKey.length - 1; i++) {
            if (certAndKey[i].contains("KEY")) {
                keyString = certAndKey[i++] + certAndKey[i];
            } else if (certAndKey[i].contains("CERTIFICATE")) {
                certificateString = certAndKey[i++] + certAndKey[i];
            }
        }

        RSAPrivateKey key = ConfigHelper.parseRsaKeyFromString(keyString);
        keyString = Base64.encodeToString(key.getEncoded(), Base64.DEFAULT);
        preferences.edit()
                .putString(Constants.PRIVATE_KEY,
                        "-----BEGIN RSA PRIVATE KEY-----\n" + keyString + "-----END RSA PRIVATE KEY-----")
                .commit();

        X509Certificate certificate = ConfigHelper.parseX509CertificateFromString(certificateString);
        certificateString = Base64.encodeToString(certificate.getEncoded(), Base64.DEFAULT);
        preferences.edit()
                .putString(Constants.CERTIFICATE,
                        "-----BEGIN CERTIFICATE-----\n" + certificateString + "-----END CERTIFICATE-----")
                .commit();
        return true;
    } catch (CertificateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    }
}