Java Code Examples for java.security.spec.PKCS8EncodedKeySpec

The following examples show how to use java.security.spec.PKCS8EncodedKeySpec. These examples are extracted from open source projects. 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 Project: tomee   Source File: TokenUtils.java    License: Apache License 2.0 8 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 Project: incubator-tuweni   Source File: SecurityTestUtils.java    License: 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 3
/**
 * 解密
 * 
 * @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 4
Source Project: bootshiro   Source File: RsaUtil.java    License: 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 5
Source Project: lion   Source File: RSAUtil.java    License: 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 6
Source Project: QuickSDK   Source File: RSAUtils.java    License: 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 Project: aaden-pay   Source File: LianlianTraderRSAUtil.java    License: 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 Project: hottub   Source File: DSAKeyFactory.java    License: 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 Project: fdroidclient   Source File: JKS.java    License: 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 Project: http4e   Source File: CryptUtils.java    License: 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
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 Project: mumu   Source File: RSACoder.java    License: 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
/**
 * 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 14
Source Project: shopping   Source File: RSA.java    License: 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 15
Source Project: openjdk-jdk8u   Source File: DSAKeyFactory.java    License: 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 16
Source Project: pandroid   Source File: RsaAesCryptoManager.java    License: 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 17
Source Project: arcusplatform   Source File: SslKeyStore.java    License: 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 18
Source Project: netty-4.1.22   Source File: SslContext.java    License: 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 19
Source Project: netty-4.1.22   Source File: SslContext.java    License: 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 20
Source Project: j2objc   Source File: PKCS8EncodedKeySpecTest.java    License: 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 21
/**
 * 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 Project: RipplePower   Source File: KeyFactory.java    License: 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 23
Source Project: jdk8u-jdk   Source File: DHKeyFactory.java    License: 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 Project: Bytecoder   Source File: DSAKeyFactory.java    License: 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 25
Source Project: che   Source File: SignatureKeyManager.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/** Returns key spec by key format and encoded data. */
private EncodedKeySpec getKeySpec(SignatureKey key) {
  switch (key.getFormat()) {
    case PKCS_8:
      return new PKCS8EncodedKeySpec(key.getEncoded());
    case X_509:
      return new X509EncodedKeySpec(key.getEncoded());
    default:
      throw new IllegalArgumentException(
          String.format("Unsupported key spec '%s' for signature keys", key.getFormat()));
  }
}
 
Example 26
Source Project: snowblossom   Source File: KeyUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static PrivateKey decodePrivateKey(ByteString encoded, String algo)
  throws ValidationException
{
  try
  {
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(encoded.toByteArray());
    KeyFactory fact = KeyFactory.getInstance(algo, Globals.getCryptoProviderName());
    return fact.generatePrivate(spec);
  }
  catch(java.security.GeneralSecurityException e)
  {
    throw new ValidationException("Error decoding key", e);
  }

}
 
Example 27
Source Project: bistoury   Source File: EncryptionUtils.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static PrivateKey loadRSAPrivateKey(String path) throws IOException, InvalidKeySpecException {
    ClassPathResource pathResource = new ClassPathResource(path);
    byte[] bb = FileUtil.readBytes(pathResource.getInputStream());
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(Base64.decode(bb));
    try {
        return KeyFactory.getInstance("RSA").generatePrivate(spec);
    } catch (NoSuchAlgorithmException e) {
        // ignore;
        return null;
    }
}
 
Example 28
public static void main(String[] argv) throws Exception {
    KeyFactory factory = KeyFactory.getInstance("DSA", "SUN");

    for (String encodings : PKCS8_ENCODINGS) {
        byte[] encodingBytes = hexToBytes(encodings);
        PKCS8EncodedKeySpec encodedKeySpec =
            new PKCS8EncodedKeySpec(encodingBytes);
        DSAPrivateKey privKey2 = (DSAPrivateKey)
            factory.generatePrivate(encodedKeySpec);
        System.out.println("key: " + privKey2);
    }
    System.out.println("Test Passed");
}
 
Example 29
Source Project: cf-java-logging-support   Source File: TokenCreator.java    License: 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
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;
}