java.security.spec.PKCS8EncodedKeySpec Java Examples

The following examples show how to use java.security.spec.PKCS8EncodedKeySpec. 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: TokenUtils.java    From tomee with Apache License 2.0 7 votes vote down vote up
public static PrivateKey readPrivateKey(String resourceName) throws Exception {
    byte[] byteBuffer = new byte[16384];
    int length = currentThread().getContextClassLoader()
            .getResource(resourceName)
            .openStream()
            .read(byteBuffer);

    String key = new String(byteBuffer, 0, length).replaceAll("-----BEGIN (.*)-----", "")
            .replaceAll("-----END (.*)----", "")
            .replaceAll("\r\n", "")
            .replaceAll("\n", "")
            .trim();

    return KeyFactory.getInstance("RSA")
            .generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode(key)));
}
 
Example #2
Source File: DSAKeyFactory.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Generates a private key object from the provided key specification
 * (key material).
 *
 * @param keySpec the specification (key material) of the private key
 *
 * @return the private key
 *
 * @exception InvalidKeySpecException if the given key specification
 * is inappropriate for this key factory to produce a private key.
 */
protected PrivateKey engineGeneratePrivate(KeySpec keySpec)
throws InvalidKeySpecException {
    try {
        if (keySpec instanceof DSAPrivateKeySpec) {
            DSAPrivateKeySpec dsaPrivKeySpec = (DSAPrivateKeySpec)keySpec;
            return new DSAPrivateKey(dsaPrivKeySpec.getX(),
                                     dsaPrivKeySpec.getP(),
                                     dsaPrivKeySpec.getQ(),
                                     dsaPrivKeySpec.getG());

        } else if (keySpec instanceof PKCS8EncodedKeySpec) {
            return new DSAPrivateKey
                (((PKCS8EncodedKeySpec)keySpec).getEncoded());

        } else {
            throw new InvalidKeySpecException
                ("Inappropriate key specification");
        }
    } catch (InvalidKeyException e) {
        throw new InvalidKeySpecException
            ("Inappropriate key specification: " + e.getMessage());
    }
}
 
Example #3
Source File: RSAUtil.java    From lion with Apache License 2.0 6 votes vote down vote up
/**
 * RSA 解密
 *
 * @param ciphertext 密文
 * @param privateKey 私钥
 * @return 明文
 */
public static String decrypt(String ciphertext, String privateKey) {
    if (StringUtils.isEmpty(ciphertext) || StringUtils.isEmpty(privateKey)) {
        return null;
    }
    try {
        //64位解码加密后的字符串
        final byte[] bytes = Base64.getDecoder().decode(ciphertext.getBytes(ENCODEING));
        //base64编码的私钥
        byte[] decoded = Base64.getDecoder().decode(privateKey);
        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) KeyFactory.getInstance(RSA).generatePrivate(new PKCS8EncodedKeySpec(decoded));
        //RSA解密
        Cipher cipher = Cipher.getInstance(RSA);
        cipher.init(Cipher.DECRYPT_MODE, rsaPrivateKey);
        String result = new String(cipher.doFinal(bytes));
        return result;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
    return null;
}
 
Example #4
Source File: EncryptRSA.java    From translationstudio8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 解密
 * 
 * @param privateKeyArray
 * @param srcBytes
 * @return
 * @throws Exception
 */
public byte[] decrypt(byte[] privateKeyArray, byte[] srcBytes)
		throws Exception {
	PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyArray);
	KeyFactory kf = KeyFactory.getInstance(algorithm);
	PrivateKey keyPrivate = kf.generatePrivate(keySpec);

	Cipher cipher = Cipher.getInstance(algorithm,
			new org.bouncycastle.jce.provider.BouncyCastleProvider());
	cipher.init(Cipher.DECRYPT_MODE, keyPrivate);

	int blockSize = cipher.getBlockSize();
	ByteArrayOutputStream bout = new ByteArrayOutputStream(blockSize);
	int j = 0;
	while (srcBytes.length - j * blockSize > 0) {
		byte[] temp = cipher.doFinal(srcBytes, j * blockSize, blockSize);
		bout.write(temp);
		j++;
	}
	return bout.toByteArray();
}
 
Example #5
Source File: RsaUtil.java    From bootshiro with MIT License 6 votes vote down vote up
public static String rsaDecode(String data, String privateKey) {

        try {
            //解析字符串

            KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
            RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8EncodedKeySpec);

            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, rsaPrivateKey);
            return new String(cipher.doFinal(Base64.decodeBase64(data)), StandardCharsets.UTF_8);

        } catch (Exception e) {
            logger.warn(e.getMessage());
            return null;
        }
    }
 
Example #6
Source File: RSAUtils.java    From QuickSDK with MIT License 6 votes vote down vote up
/**
 * 使用私钥对数据进行RSA签名
 * @param content 待签名数据
 * @param privateKey 商户私钥
 * @param input_charset 编码格式
 * @return 签名值
 */
public static String sign(String content, String privateKey, String input_charset)
{
    try
    {
        PKCS8EncodedKeySpec priPKCS8 	= new PKCS8EncodedKeySpec( Base64.decode(privateKey) );
        KeyFactory keyf 				= KeyFactory.getInstance("RSA");
        PrivateKey priKey 				= keyf.generatePrivate(priPKCS8);

        java.security.Signature signature = java.security.Signature
                .getInstance(SIGNATURE_ALGORITHM);

        signature.initSign(priKey);
        signature.update( content.getBytes(input_charset) );

        byte[] signed = signature.sign();

        return Base64.encode(signed);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

    return null;
}
 
Example #7
Source File: LianlianTraderRSAUtil.java    From aaden-pay with Apache License 2.0 6 votes vote down vote up
/**
 * 签名处理
 * 
 * @param prikeyvalue
 *            :私钥
 * @param sign_str
 *            :签名源内容
 * @return
 */
public static String sign(String prikeyvalue, String sign_str) {
	try {
		PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(LianlianBase64.getBytesBASE64(prikeyvalue));
		KeyFactory keyf = KeyFactory.getInstance("RSA");
		PrivateKey myprikey = keyf.generatePrivate(priPKCS8);
		// 用私钥对信息生成数字签名
		java.security.Signature signet = java.security.Signature.getInstance("MD5withRSA");
		signet.initSign(myprikey);
		signet.update(sign_str.getBytes("UTF-8"));
		byte[] signed = signet.sign(); // 对信息的数字签名
		return new String(org.apache.commons.codec.binary.Base64.encodeBase64(signed));
	} catch (java.lang.Exception e) {
		e.printStackTrace();
	}
	return null;
}
 
Example #8
Source File: DSAKeyFactory.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Generates a private key object from the provided key specification
 * (key material).
 *
 * @param keySpec the specification (key material) of the private key
 *
 * @return the private key
 *
 * @exception InvalidKeySpecException if the given key specification
 * is inappropriate for this key factory to produce a private key.
 */
protected PrivateKey engineGeneratePrivate(KeySpec keySpec)
throws InvalidKeySpecException {
    try {
        if (keySpec instanceof DSAPrivateKeySpec) {
            DSAPrivateKeySpec dsaPrivKeySpec = (DSAPrivateKeySpec)keySpec;
            return new DSAPrivateKey(dsaPrivKeySpec.getX(),
                                     dsaPrivKeySpec.getP(),
                                     dsaPrivKeySpec.getQ(),
                                     dsaPrivKeySpec.getG());

        } else if (keySpec instanceof PKCS8EncodedKeySpec) {
            return new DSAPrivateKey
                (((PKCS8EncodedKeySpec)keySpec).getEncoded());

        } else {
            throw new InvalidKeySpecException
                ("Inappropriate key specification");
        }
    } catch (InvalidKeyException e) {
        throw new InvalidKeySpecException
            ("Inappropriate key specification: " + e.getMessage());
    }
}
 
Example #9
Source File: JKS.java    From fdroidclient with GNU General Public License v3.0 6 votes vote down vote up
public Key engineGetKey(String alias, char[] password)
        throws NoSuchAlgorithmException, UnrecoverableKeyException {
    alias = alias.toLowerCase(Locale.ENGLISH);

    if (!privateKeys.containsKey(alias))
        return null;
    byte[] key = decryptKey((byte[]) privateKeys.get(alias),
            charsToBytes(password));
    Certificate[] chain = engineGetCertificateChain(alias);
    if (chain.length > 0) {
        try {
            // Private and public keys MUST have the same algorithm.
            KeyFactory fact = KeyFactory.getInstance(
                    chain[0].getPublicKey().getAlgorithm());
            return fact.generatePrivate(new PKCS8EncodedKeySpec(key));
        } catch (InvalidKeySpecException x) {
            throw new UnrecoverableKeyException(x.getMessage());
        }
    } else
        return new SecretKeySpec(key, alias);
}
 
Example #10
Source File: CryptUtils.java    From http4e with Apache License 2.0 6 votes vote down vote up
/**
 * Method convertes the bytes arrays back to private and public key objects
 */
public static Key[] bytesToPrivatePublicKeys( String algorithm, byte[] privKeyBytes, byte[] pubKeyBytes) throws Exception{
   PrivateKey privKey = null;
   PublicKey pubKey = null;
   KeyFactory keyFactory = KeyFactory.getInstance(algorithm);

   if (privKeyBytes != null) {
      EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privKeyBytes);
      privKey = keyFactory.generatePrivate(privateKeySpec);
   }

   if (pubKeyBytes != null) {
      EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pubKeyBytes);
      pubKey = keyFactory.generatePublic(publicKeySpec);
   }

   return new Key[] { privKey, pubKey };
}
 
Example #11
Source File: AsymmetricKeyEncryptionClientDemo.java    From markdown-image-kit with MIT License 6 votes vote down vote up
private static KeyPair loadAsymKeyPair()
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    // load public
    File filePublicKey = new File(pubKeyPath);
    FileInputStream fis = new FileInputStream(filePublicKey);
    byte[] encodedPublicKey = new byte[(int) filePublicKey.length()];
    fis.read(encodedPublicKey);
    fis.close();

    // load private
    File filePrivateKey = new File(priKeyPath);
    fis = new FileInputStream(filePrivateKey);
    byte[] encodedPrivateKey = new byte[(int) filePrivateKey.length()];
    fis.read(encodedPrivateKey);
    fis.close();

    // build RSA KeyPair
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedPublicKey);
    PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

    PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

    return new KeyPair(publicKey, privateKey);
}
 
Example #12
Source File: RSACoder.java    From mumu with Apache License 2.0 6 votes vote down vote up
/**
 * 签名
 * 
 * @param data
 *            待签名数据
 * @param privateKey
 *            私钥
 * @return byte[] 数字签名
 * @throws Exception
 */
public static byte[] sign(byte[] data, byte[] privateKey) throws Exception {
	// 转换私钥材料
	PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKey);
	// 实例化密钥工厂
	KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
	// 取私钥匙对象
	PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);
	// 实例化Signature
	Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
	// 初始化Signature
	signature.initSign(priKey);
	// 更新
	signature.update(data);
	// 签名
	return signature.sign();
}
 
Example #13
Source File: RSA.java    From shopping with Apache License 2.0 6 votes vote down vote up
/**
* RSA签名
* @param content 待签名数据
* @param privateKey 商户私钥
* @param input_charset 编码格式
* @return 签名值
*/
public static String sign(String content, String privateKey, String input_charset){
       try 
       {
       	PKCS8EncodedKeySpec priPKCS8 	= new PKCS8EncodedKeySpec( Base64.decode(privateKey) ); 
       	KeyFactory keyf 				= KeyFactory.getInstance("RSA");
       	PrivateKey priKey 				= keyf.generatePrivate(priPKCS8);

           java.security.Signature signature = java.security.Signature
               .getInstance(SIGN_ALGORITHMS);

           signature.initSign(priKey);
           signature.update( content.getBytes(input_charset) );

           byte[] signed = signature.sign();
           
           return Base64.encode(signed);
       }
       catch (Exception e) 
       {
       	e.printStackTrace();
       }
       
       return null;
   }
 
Example #14
Source File: DSAKeyFactory.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Generates a private key object from the provided key specification
 * (key material).
 *
 * @param keySpec the specification (key material) of the private key
 *
 * @return the private key
 *
 * @exception InvalidKeySpecException if the given key specification
 * is inappropriate for this key factory to produce a private key.
 */
protected PrivateKey engineGeneratePrivate(KeySpec keySpec)
throws InvalidKeySpecException {
    try {
        if (keySpec instanceof DSAPrivateKeySpec) {
            DSAPrivateKeySpec dsaPrivKeySpec = (DSAPrivateKeySpec)keySpec;
            return new DSAPrivateKey(dsaPrivKeySpec.getX(),
                                     dsaPrivKeySpec.getP(),
                                     dsaPrivKeySpec.getQ(),
                                     dsaPrivKeySpec.getG());

        } else if (keySpec instanceof PKCS8EncodedKeySpec) {
            return new DSAPrivateKey
                (((PKCS8EncodedKeySpec)keySpec).getEncoded());

        } else {
            throw new InvalidKeySpecException
                ("Inappropriate key specification");
        }
    } catch (InvalidKeyException e) {
        throw new InvalidKeySpecException
            ("Inappropriate key specification: " + e.getMessage());
    }
}
 
Example #15
Source File: RsaAesCryptoManager.java    From pandroid with Apache License 2.0 6 votes vote down vote up
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 #16
Source File: SslKeyStore.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Nullable
public static PrivateKey readHubPrivateKey() {
   try {
      PemContent pem = readPemContent(IrisHal.getHubKeyFile());
      switch (pem.format) {
      case PKCS1:
         return fromPkcs1(pem.content);

      case PKCS8:
      default:
         return KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(pem.content));
      }
   } catch (Exception ex) {
      log.debug("could not read hub private key: {}", ex.getMessage(), ex);
      return null;
   }
}
 
Example #17
Source File: SslContext.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 * Generates a key specification for an (encrypted) private key.为(加密的)私钥生成密钥规范。
 *
 * @param password characters, if {@code null} an unencrypted key is assumed
 * @param key bytes of the DER encoded private key
 *
 * @return a key specification
 *
 * @throws IOException if parsing {@code key} fails
 * @throws NoSuchAlgorithmException if the algorithm used to encrypt {@code key} is unknown
 * @throws NoSuchPaddingException if the padding scheme specified in the decryption algorithm is unknown
 * @throws InvalidKeySpecException if the decryption key based on {@code password} cannot be generated
 * @throws InvalidKeyException if the decryption key based on {@code password} cannot be used to decrypt
 *                             {@code key}
 * @throws InvalidAlgorithmParameterException if decryption algorithm parameters are somehow faulty
 */
protected static PKCS8EncodedKeySpec generateKeySpec(char[] password, byte[] key)
        throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException,
        InvalidKeyException, InvalidAlgorithmParameterException {

    if (password == null) {
        return new PKCS8EncodedKeySpec(key);
    }

    EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(key);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(encryptedPrivateKeyInfo.getAlgName());
    PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
    SecretKey pbeKey = keyFactory.generateSecret(pbeKeySpec);

    Cipher cipher = Cipher.getInstance(encryptedPrivateKeyInfo.getAlgName());
    cipher.init(Cipher.DECRYPT_MODE, pbeKey, encryptedPrivateKeyInfo.getAlgParameters());

    return encryptedPrivateKeyInfo.getKeySpec(cipher);
}
 
Example #18
Source File: SslContext.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
private static PrivateKey getPrivateKeyFromByteBuffer(ByteBuf encodedKeyBuf, String keyPassword)
        throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException,
        InvalidAlgorithmParameterException, KeyException, IOException {

    byte[] encodedKey = new byte[encodedKeyBuf.readableBytes()];
    encodedKeyBuf.readBytes(encodedKey).release();

    PKCS8EncodedKeySpec encodedKeySpec = generateKeySpec(
            keyPassword == null ? null : keyPassword.toCharArray(), encodedKey);
    try {
        return KeyFactory.getInstance("RSA").generatePrivate(encodedKeySpec);
    } catch (InvalidKeySpecException ignore) {
        try {
            return KeyFactory.getInstance("DSA").generatePrivate(encodedKeySpec);
        } catch (InvalidKeySpecException ignore2) {
            try {
                return KeyFactory.getInstance("EC").generatePrivate(encodedKeySpec);
            } catch (InvalidKeySpecException e) {
                throw new InvalidKeySpecException("Neither RSA, DSA nor EC worked", e);
            }
        }
    }
}
 
Example #19
Source File: PKCS8EncodedKeySpecTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that internal state of the object
 * can not be modified using returned value
 * of <code>getEncoded()</code> method
 */
public final void testIsStatePreserved2() {
    // Reference array
    byte[] encodedKey = new byte[] {(byte)1,(byte)2,(byte)3,(byte)4};
    // Reference array's copy will be used for test
    byte[] encodedKeyCopy = encodedKey.clone();

    PKCS8EncodedKeySpec meks = new PKCS8EncodedKeySpec(encodedKeyCopy);

    byte[] ek = meks.getEncoded();

    // Modify returned array
    ek[3] = (byte)5;

    // Get encoded key again
    byte[] ek1 = meks.getEncoded();

    // Check using reference array that
    // byte value has not been changed
    assertTrue(Arrays.equals(encodedKey, ek1));
}
 
Example #20
Source File: DSAKeyFactory.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Generates a private key object from the provided key specification
 * (key material).
 *
 * @param keySpec the specification (key material) of the private key
 *
 * @return the private key
 *
 * @exception InvalidKeySpecException if the given key specification
 * is inappropriate for this key factory to produce a private key.
 */
protected PrivateKey engineGeneratePrivate(KeySpec keySpec)
throws InvalidKeySpecException {
    try {
        if (keySpec instanceof DSAPrivateKeySpec) {
            DSAPrivateKeySpec dsaPrivKeySpec = (DSAPrivateKeySpec)keySpec;
            return new DSAPrivateKey(dsaPrivKeySpec.getX(),
                                     dsaPrivKeySpec.getP(),
                                     dsaPrivKeySpec.getQ(),
                                     dsaPrivKeySpec.getG());

        } else if (keySpec instanceof PKCS8EncodedKeySpec) {
            return new DSAPrivateKey
                (((PKCS8EncodedKeySpec)keySpec).getEncoded());

        } else {
            throw new InvalidKeySpecException
                ("Inappropriate key specification");
        }
    } catch (InvalidKeyException e) {
        throw new InvalidKeySpecException
            ("Inappropriate key specification: " + e.getMessage());
    }
}
 
Example #21
Source File: DSAKeyFactory.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Generates a private key object from the provided key specification
 * (key material).
 *
 * @param keySpec the specification (key material) of the private key
 *
 * @return the private key
 *
 * @exception InvalidKeySpecException if the given key specification
 * is inappropriate for this key factory to produce a private key.
 */
protected PrivateKey engineGeneratePrivate(KeySpec keySpec)
throws InvalidKeySpecException {
    try {
        if (keySpec instanceof DSAPrivateKeySpec) {
            DSAPrivateKeySpec dsaPrivKeySpec = (DSAPrivateKeySpec)keySpec;
            return new DSAPrivateKey(dsaPrivKeySpec.getX(),
                                     dsaPrivKeySpec.getP(),
                                     dsaPrivKeySpec.getQ(),
                                     dsaPrivKeySpec.getG());

        } else if (keySpec instanceof PKCS8EncodedKeySpec) {
            return new DSAPrivateKey
                (((PKCS8EncodedKeySpec)keySpec).getEncoded());

        } else {
            throw new InvalidKeySpecException
                ("Inappropriate key specification");
        }
    } catch (InvalidKeyException e) {
        throw new InvalidKeySpecException
            ("Inappropriate key specification: " + e.getMessage());
    }
}
 
Example #22
Source File: SecurityTestUtils.java    From incubator-tuweni with Apache License 2.0 6 votes vote down vote up
static void configureJDKTrustStore(Path workDir, SelfSignedCertificate clientCert) throws Exception {
  KeyStore ks = KeyStore.getInstance("JKS");
  ks.load(null, null);

  KeyFactory kf = KeyFactory.getInstance("RSA");
  PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(readPemFile(new File(clientCert.privateKeyPath()).toPath()));
  PrivateKey clientPrivateKey = kf.generatePrivate(keysp);
  CertificateFactory cf = CertificateFactory.getInstance("X.509");
  Certificate certificate = cf
      .generateCertificate(
          new ByteArrayInputStream(Files.readAllBytes(new File(clientCert.certificatePath()).toPath())));
  ks.setCertificateEntry("clientCert", certificate);
  ks.setKeyEntry("client", clientPrivateKey, "changeit".toCharArray(), new Certificate[] {certificate});
  Path tempKeystore = Files.createTempFile(workDir, "keystore", ".jks");
  try (FileOutputStream output = new FileOutputStream(tempKeystore.toFile());) {
    ks.store(output, "changeit".toCharArray());
  }
  System.setProperty("javax.net.ssl.trustStore", tempKeystore.toString());
  System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
}
 
Example #23
Source File: DHKeyFactory.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Generates a private key object from the provided key specification
 * (key material).
 *
 * @param keySpec the specification (key material) of the private key
 *
 * @return the private key
 *
 * @exception InvalidKeySpecException if the given key specification
 * is inappropriate for this key factory to produce a private key.
 */
protected PrivateKey engineGeneratePrivate(KeySpec keySpec)
    throws InvalidKeySpecException
{
    try {
        if (keySpec instanceof DHPrivateKeySpec) {
            DHPrivateKeySpec dhPrivKeySpec = (DHPrivateKeySpec)keySpec;
            return new DHPrivateKey(dhPrivKeySpec.getX(),
                                    dhPrivKeySpec.getP(),
                                    dhPrivKeySpec.getG());

        } else if (keySpec instanceof PKCS8EncodedKeySpec) {
            return new DHPrivateKey
                (((PKCS8EncodedKeySpec)keySpec).getEncoded());

        } else {
            throw new InvalidKeySpecException
                ("Inappropriate key specification");
        }
    } catch (InvalidKeyException e) {
        throw new InvalidKeySpecException
            ("Inappropriate key specification", e);
    }
}
 
Example #24
Source File: KeyFactory.java    From RipplePower with Apache License 2.0 6 votes vote down vote up
protected PrivateKey engineGeneratePrivate(
    KeySpec keySpec)
    throws InvalidKeySpecException
{
    if (keySpec instanceof PKCS8EncodedKeySpec)
    {
        try
        {
            PrivateKeyInfo info = PrivateKeyInfo.getInstance(((PKCS8EncodedKeySpec)keySpec).getEncoded());
            PrivateKey     key = BouncyCastleProvider.getPrivateKey(info);

            if (key != null)
            {
                return key;
            }

            throw new InvalidKeySpecException("no factory found for OID: " + info.getPrivateKeyAlgorithm().getAlgorithm());
        }
        catch (Exception e)
        {
            throw new InvalidKeySpecException(e.toString());
        }
    }

    throw new InvalidKeySpecException("Unknown KeySpec type: " + keySpec.getClass().getName());
}
 
Example #25
Source File: RSAUtils.java    From jeesupport with MIT License 5 votes vote down vote up
/**
 * 私钥加密
 * 
 * @param _key 私钥
 * @param _data 待加密数据
 * @return
 * @throws Exception
 */
public static byte[] s_encrypt_private( byte[] _key , byte[] _data ) throws Exception {

	// 取得私钥
	PKCS8EncodedKeySpec pkcs8 = new PKCS8EncodedKeySpec( _key );

	KeyFactory key_factory = KeyFactory.getInstance( KEY_ALGORITHM_RSA );

	// 生成私钥
	PrivateKey private_key = key_factory.generatePrivate( pkcs8 );

	// 对数据加密
	Cipher cipher = Cipher.getInstance( key_factory.getAlgorithm() );

	cipher.init( Cipher.ENCRYPT_MODE , private_key );

	int blockSize = cipher.getBlockSize();
	if ( blockSize > 0 ) {
		int outputSize = cipher.getOutputSize( _data.length );
		int leavedSize = _data.length % blockSize;
		int blocksSize = leavedSize != 0 ? _data.length / blockSize + 1 : _data.length / blockSize;
		byte[] raw = new byte[ outputSize * blocksSize ];
		int i = 0 , remainSize = 0;
		while ( ( remainSize = _data.length - i * blockSize ) > 0 ) {
			int inputLen = remainSize > blockSize ? blockSize : remainSize;
			cipher.doFinal( _data , i * blockSize , inputLen , raw , i * outputSize );
			i++;
		}
		return raw;
	}
	return cipher.doFinal( _data );
}
 
Example #26
Source File: CipherTestUtils.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private static KeyStore createServerKeyStore(String publicKeyStr,
        String keySpecStr) throws KeyStoreException, IOException,
        NoSuchAlgorithmException, CertificateException,
        InvalidKeySpecException {

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);
    if (publicKeyStr == null || keySpecStr == null) {
        throw new IllegalArgumentException("publicKeyStr or "
                + "keySpecStr cannot be null");
    }
    String strippedPrivateKey = keySpecStr.substring(
            keySpecStr.indexOf("\n"), keySpecStr.lastIndexOf("\n"));

    // generate the private key.
    PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(
            Base64.getMimeDecoder().decode(strippedPrivateKey));
    KeyFactory kf = KeyFactory.getInstance("RSA");
    RSAPrivateKey priKey
            = (RSAPrivateKey) kf.generatePrivate(priKeySpec);

    // generate certificate chain
    try (InputStream is =
            new ByteArrayInputStream(publicKeyStr.getBytes())) {
        // generate certificate from cert string
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        Certificate keyCert = cf.generateCertificate(is);
        Certificate[] chain = {keyCert};
        ks.setKeyEntry("TestEntry", priKey, PASSWORD, chain);
    }

    return ks;
}
 
Example #27
Source File: RSAUtils.java    From RSA-Android with Apache License 2.0 5 votes vote down vote up
/**
 * 通过私钥byte[]将公钥还原,适用于RSA算法
 *
 * @param keyBytes
 * @return
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public static PrivateKey getPrivateKey(byte[] keyBytes) throws NoSuchAlgorithmException,
        InvalidKeySpecException
{
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(RSA);
    PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
    return privateKey;
}
 
Example #28
Source File: CipherTestUtils.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static KeyStore createServerKeyStore(String publicKeyStr,
        String keySpecStr) throws KeyStoreException, IOException,
        NoSuchAlgorithmException, CertificateException,
        InvalidKeySpecException {

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);
    if (publicKeyStr == null || keySpecStr == null) {
        throw new IllegalArgumentException("publicKeyStr or "
                + "keySpecStr cannot be null");
    }
    String strippedPrivateKey = keySpecStr.substring(
            keySpecStr.indexOf("\n"), keySpecStr.lastIndexOf("\n"));

    // generate the private key.
    PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(
            Base64.getMimeDecoder().decode(strippedPrivateKey));
    KeyFactory kf = KeyFactory.getInstance("RSA");
    RSAPrivateKey priKey
            = (RSAPrivateKey) kf.generatePrivate(priKeySpec);

    // generate certificate chain
    try (InputStream is =
            new ByteArrayInputStream(publicKeyStr.getBytes())) {
        // generate certificate from cert string
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        Certificate keyCert = cf.generateCertificate(is);
        Certificate[] chain = {keyCert};
        ks.setKeyEntry("TestEntry", priKey, PASSWORD, chain);
    }

    return ks;
}
 
Example #29
Source File: TokenCreator.java    From cf-java-logging-support with Apache License 2.0 5 votes vote down vote up
private static RSAPrivateKey privateKeyConverter(String pemKey) throws NoSuchAlgorithmException,
                                                                InvalidKeySpecException {
    byte[] keyBytes = DatatypeConverter.parseBase64Binary(pemKey);
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    return (RSAPrivateKey) keyFactory.generatePrivate(spec);
}
 
Example #30
Source File: RsaEncrypt.java    From charging_pile_cloud with MIT License 5 votes vote down vote up
/**
 * RSA私钥解密
 *
 * @param str
 *            加密字符串
 * @param privateKey
 *            私钥
 * @return 铭文
 * @throws Exception
 *             解密过程中的异常信息
 */
public static String decrypt(String str, String privateKey) throws Exception{
    //64位解码加密后的字符串
    byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
    //base64编码的私钥
    byte[] decoded = Base64.decodeBase64(privateKey);
    RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
    //RSA解密
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.DECRYPT_MODE, priKey);
    String outStr = new String(cipher.doFinal(inputByte));
    return outStr;
}