类java.security.spec.PKCS8EncodedKeySpec源码实例Demo

下面列出了怎么用java.security.spec.PKCS8EncodedKeySpec的API类实例代码及写法,或者点击链接到github查看源代码。


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");
}
 
源代码2 项目: translationstudio8   文件: EncryptRSA.java

/**
 * 解密
 * 
 * @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();
}
 
源代码3 项目: bootshiro   文件: RsaUtil.java

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;
        }
    }
 
源代码4 项目: lion   文件: RSAUtil.java

/**
 * 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;
}
 
源代码5 项目: tomee   文件: TokenUtils.java

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)));
}
 
源代码6 项目: QuickSDK   文件: RSAUtils.java

/**
 * 使用私钥对数据进行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;
}
 
源代码7 项目: aaden-pay   文件: LianlianTraderRSAUtil.java

/**
 * 签名处理
 * 
 * @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;
}
 
源代码8 项目: hottub   文件: DSAKeyFactory.java

/**
 * 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());
    }
}
 
源代码9 项目: fdroidclient   文件: JKS.java

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);
}
 
源代码10 项目: http4e   文件: CryptUtils.java

/**
 * 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 };
}
 

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);
}
 
源代码12 项目: mumu   文件: RSACoder.java

/**
 * 签名
 * 
 * @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();
}
 
源代码13 项目: dragonwell8_jdk   文件: DSAKeyFactory.java

/**
 * 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());
    }
}
 
源代码14 项目: shopping   文件: RSA.java

/**
* 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;
   }
 
源代码15 项目: openjdk-jdk8u   文件: DSAKeyFactory.java

/**
 * 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());
    }
}
 
源代码16 项目: pandroid   文件: RsaAesCryptoManager.java

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);
    }
}
 
源代码17 项目: arcusplatform   文件: SslKeyStore.java

@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;
   }
}
 
源代码18 项目: netty-4.1.22   文件: SslContext.java

/**
 * 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);
}
 
源代码19 项目: netty-4.1.22   文件: SslContext.java

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);
            }
        }
    }
}
 
源代码20 项目: j2objc   文件: PKCS8EncodedKeySpecTest.java

/**
 * 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));
}
 

/**
 * 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());
    }
}
 
源代码22 项目: RipplePower   文件: KeyFactory.java

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());
}
 
源代码23 项目: jdk8u-jdk   文件: DHKeyFactory.java

/**
 * 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);
    }
}
 
源代码24 项目: Bytecoder   文件: DSAKeyFactory.java

/**
 * 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());
    }
}
 
源代码25 项目: che   文件: SignatureKeyManager.java

/** 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()));
  }
}
 
源代码26 项目: snowblossom   文件: KeyUtil.java

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);
  }

}
 
源代码27 项目: bistoury   文件: EncryptionUtils.java

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;
    }
}
 
源代码28 项目: openjdk-jdk9   文件: TestLeadingZeros.java

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");
}
 

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);
}
 

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;
}