Java Code Examples for org.bouncycastle.util.io.pem.PemReader#readPemObject()

The following examples show how to use org.bouncycastle.util.io.pem.PemReader#readPemObject() . 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: TLSCertificateKeyPair.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
/***
 * Creates a TLSCertificateKeyPair out of the given {@link X509Certificate} and {@link KeyPair}
 * encoded in PEM and also in DER for the certificate
 * @param x509Cert the certificate to process
 * @param keyPair  the key pair to process
 * @return a TLSCertificateKeyPair
 * @throws IOException upon failure
 */
static TLSCertificateKeyPair fromX509CertKeyPair(X509Certificate x509Cert, KeyPair keyPair) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintWriter writer = new PrintWriter(baos);
    JcaPEMWriter w = new JcaPEMWriter(writer);
    w.writeObject(x509Cert);
    w.flush();
    w.close();
    byte[] pemBytes = baos.toByteArray();

    InputStreamReader isr = new InputStreamReader(new ByteArrayInputStream(pemBytes));
    PemReader pr = new PemReader(isr);
    PemObject pem = pr.readPemObject();
    byte[] derBytes = pem.getContent();

    baos = new ByteArrayOutputStream();
    PrintWriter wr = new PrintWriter(baos);
    wr.println("-----BEGIN PRIVATE KEY-----");
    wr.println(new String(Base64.encodeBase64(keyPair.getPrivate().getEncoded())));
    wr.println("-----END PRIVATE KEY-----");
    wr.flush();
    wr.close();
    byte[] keyBytes = baos.toByteArray();
    return new TLSCertificateKeyPair(pemBytes, derBytes, keyBytes);
}
 
Example 2
Source File: PemUtils.java    From hedera-sdk-java with Apache License 2.0 6 votes vote down vote up
public static PrivateKeyInfo readPrivateKey(Reader input, @Nullable String passphrase) throws IOException {
    final PemReader pemReader = new PemReader(input);

    PemObject readObject = null;

    for (;;) {
        PemObject nextObject = pemReader.readPemObject();

        if (nextObject == null) break;
        readObject = nextObject;

        String objType = readObject.getType();

        if (passphrase != null && !passphrase.isEmpty() && objType.equals(TYPE_ENCRYPTED_PRIVATE_KEY)) {
            return decryptPrivateKey(readObject.getContent(), passphrase);
        } else if (objType.equals(TYPE_PRIVATE_KEY)) {
            return PrivateKeyInfo.getInstance(readObject.getContent());
        }
    }

    if (readObject != null && readObject.getType().equals(TYPE_ENCRYPTED_PRIVATE_KEY)) {
        throw new BadKeyException("PEM file contained an encrypted private key but no passphrase was given");
    }

    throw new BadKeyException("PEM file did not contain a private key");
}
 
Example 3
Source File: CryptoUtil.java    From julongchain with Apache License 2.0 6 votes vote down vote up
/**
 * 加载密钥文件
 * @param filePath
 * @return
 */
public static byte[] loadKeyFile(String filePath) {

    File inFile = new File(filePath);
    long fileLen = inFile.length();
    Reader reader = null;
    PemObject pemObject = null;
    try {
        reader = new FileReader(inFile);

        char[] content = new char[(int) fileLen];
        reader.read(content);
        String str = new String(content);

        StringReader stringreader = new StringReader(str);
        PemReader pem = new PemReader(stringreader);
        pemObject = pem.readPemObject();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return pemObject.getContent();
}
 
Example 4
Source File: CryptoUtil.java    From julongchain with Apache License 2.0 6 votes vote down vote up
/**
 * 读取私钥文件
 * @param skPath
 * @return
 * @throws CspException
 * @throws IOException
 */
public static byte[] readSkFile(String skPath) throws CspException, IOException {
    InputStreamReader reader = new InputStreamReader(new FileInputStream(skPath));
    PemReader pemReader = new PemReader(reader);
    PemObject pemObject = pemReader.readPemObject();
    reader.close();
    byte[] encodedData = pemObject.getContent();
    DerValue derValue = new DerValue(new ByteArrayInputStream(encodedData));
    byte[] rawPrivateKey = null;
    if (derValue.tag != 48) {
        throw new CspException("invalid key format");
    } else {
        BigInteger version = derValue.data.getBigInteger();
        if (!version.equals(BigInteger.ZERO)) {
            throw new CspException("version mismatch: (supported: " + Debug.toHexString(BigInteger.ZERO) + ", parsed: " + Debug.toHexString(version));
        } else {
            AlgorithmId algId = AlgorithmId.parse(derValue.data.getDerValue());
            rawPrivateKey = derValue.data.getOctetString();
        }
        return rawPrivateKey;
    }
}
 
Example 5
Source File: CaHelper.java    From julongchain with Apache License 2.0 6 votes vote down vote up
public static Certificate loadCertificateSM2(String certPath) throws JulongChainException {
    File certDir = new File(certPath);
    File[] files = certDir.listFiles();
    if (!certDir.isDirectory() || files == null) {
        log.error("invalid directory for certPath " + certPath);
        return null;
    }
    for (File file : files) {
        if (!file.getName().endsWith(".pem")) {
            continue;
        }
        try {
            InputStreamReader reader = new InputStreamReader(new FileInputStream(file));
            PemReader pemReader = new PemReader(reader);
            PemObject pemObject = pemReader.readPemObject();
            reader.close();
            byte[] certBytes = pemObject.getContent();
            return Certificate.getInstance(certBytes);
        } catch (Exception e) {
            throw new JulongChainException("An error occurred :" + e.getMessage());
        }
    }
    throw new JulongChainException("no pem file found");
}
 
Example 6
Source File: CryptoPrimitives.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Return PrivateKey  from pem bytes.
 *
 * @param pemKey pem-encoded private key
 * @return
 */
public PrivateKey bytesToPrivateKey(byte[] pemKey) throws CryptoException {
    PrivateKey pk = null;
    CryptoException ce = null;

    try {
        PemReader pr = new PemReader(new StringReader(new String(pemKey)));
        PemObject po = pr.readPemObject();
        PEMParser pem = new PEMParser(new StringReader(new String(pemKey)));

        if (po.getType().equals("PRIVATE KEY")) {
            pk = new JcaPEMKeyConverter().getPrivateKey((PrivateKeyInfo) pem.readObject());
        } else {
            logger.trace("Found private key with type " + po.getType());
            PEMKeyPair kp = (PEMKeyPair) pem.readObject();
            pk = new JcaPEMKeyConverter().getPrivateKey(kp.getPrivateKeyInfo());
        }
    } catch (Exception e) {
        throw new CryptoException("Failed to convert private key bytes", e);
    }
    return pk;
}
 
Example 7
Source File: PemFile.java    From azure-keyvault-java with MIT License 5 votes vote down vote up
public PemFile(String filename) throws FileNotFoundException, IOException {
    PemReader pemReader = new PemReader(new InputStreamReader(new FileInputStream(filename)));
    try {
        this.pemObject = pemReader.readPemObject();
    } finally {
        pemReader.close();
    }
}
 
Example 8
Source File: SecurityHelper.java    From MQTT-Essentials-A-Lightweight-IoT-Protocol with MIT License 5 votes vote down vote up
private static PrivateKey createPrivateKeyFromPemFile(final String keyFileName) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException 
{
	// Loads a privte key from the specified key file name
    final PemReader pemReader = new PemReader(new FileReader(keyFileName));
    final PemObject pemObject = pemReader.readPemObject();
    final byte[] pemContent = pemObject.getContent();
    pemReader.close();
    final PKCS8EncodedKeySpec encodedKeySpec = new PKCS8EncodedKeySpec(pemContent);
    final KeyFactory keyFactory = getKeyFactoryInstance();
    final PrivateKey privateKey = keyFactory.generatePrivate(encodedKeySpec);
    return privateKey;
}
 
Example 9
Source File: SecurityHelper.java    From MQTT-Essentials-A-Lightweight-IoT-Protocol with MIT License 5 votes vote down vote up
private static PrivateKey createPrivateKeyFromPemFile(final String keyFileName) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException 
{
	// Loads a privte key from the specified key file name
    final PemReader pemReader = new PemReader(new FileReader(keyFileName));
    final PemObject pemObject = pemReader.readPemObject();
    final byte[] pemContent = pemObject.getContent();
    pemReader.close();
    final PKCS8EncodedKeySpec encodedKeySpec = new PKCS8EncodedKeySpec(pemContent);
    final KeyFactory keyFactory = getKeyFactoryInstance();
    final PrivateKey privateKey = keyFactory.generatePrivate(encodedKeySpec);
    return privateKey;
}
 
Example 10
Source File: PEMManager.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
public void load(InputStream in)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
                InvalidKeySpecException, NoSuchProviderException {
    PemReader pemReader = new PemReader(new InputStreamReader(in));

    pem = pemReader.readPemObject();
    if (pem == null) {
        throw new IOException("The file does not represent a pem account.");
    }

    // logger.debug(" load pem, type: {}, header: {}", pem.getType(), pem.getHeaders());

    pemReader.close();
}
 
Example 11
Source File: BCECUtil.java    From jiguang-java-client-common with MIT License 5 votes vote down vote up
private static byte[] convertPEMToEncodedData(String pemString) throws IOException {
    ByteArrayInputStream bIn = new ByteArrayInputStream(pemString.getBytes());
    PemReader pRdr = new PemReader(new InputStreamReader(bIn));
    try {
        PemObject pemObject = pRdr.readPemObject();
        return pemObject.getContent();
    } finally {
        pRdr.close();
    }
}
 
Example 12
Source File: CspHelper.java    From julongchain with Apache License 2.0 5 votes vote down vote up
public static IKey loadPrivateKey(String keystorePath) throws JulongChainException {
    File keyStoreDir = new File(keystorePath);
    File[] files = keyStoreDir.listFiles();
    if (!keyStoreDir.isDirectory() || files == null) {
        log.error("invalid directory for keystorePath " + keystorePath);
        return null;
    }
    for (File file : files) {
        if (!file.getName().endsWith("_sk")) {
            continue;
        }
        try {
            InputStreamReader reader = new InputStreamReader(new FileInputStream(file));
            PemReader pemReader = new PemReader(reader);
            PemObject pemObject = pemReader.readPemObject();
            reader.close();

            byte[] encodedData = pemObject.getContent();
            List<Object> list = decodePrivateKeyPKCS8(encodedData);
            Object rawKey = list.get(1);
            return CSP.keyImport(rawKey, new SM2PrivateKeyImportOpts(true));
        } catch (Exception e) {
            log.error("An error occurred on loadPrivateKey: {}", e.getMessage());
        }
    }
    throw new JulongChainException("no pem file found");
}
 
Example 13
Source File: PemUtils.java    From java-jwt with MIT License 5 votes vote down vote up
private static byte[] parsePEMFile(File pemFile) throws IOException {
    if (!pemFile.isFile() || !pemFile.exists()) {
        throw new FileNotFoundException(String.format("The file '%s' doesn't exist.", pemFile.getAbsolutePath()));
    }
    PemReader reader = new PemReader(new FileReader(pemFile));
    PemObject pemObject = reader.readPemObject();
    byte[] content = pemObject.getContent();
    reader.close();
    return content;
}
 
Example 14
Source File: CertUtil.java    From javasdk with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * read pem and convert to address.
 * @param s pem file context
 * @return address
 * @throws Exception -
 */
public static String pemToAddr(String s) throws Exception {
    PemReader pemReader = new PemReader(new StringReader(s));
    PemObject pemObject = pemReader.readPemObject();
    X509CertificateHolder cert = new X509CertificateHolder(pemObject.getContent());
    SubjectPublicKeyInfo pkInfo = cert.getSubjectPublicKeyInfo();
    DERBitString pk = pkInfo.getPublicKeyData();
    byte[] pk64 = ByteUtils.subArray(pk.getBytes(),1);
    return ByteUtils.toHexString(HashUtil.sha3omit12(pk64));
}
 
Example 15
Source File: BCECUtil.java    From gmhelper with Apache License 2.0 5 votes vote down vote up
private static byte[] convertPEMToEncodedData(String pemString) throws IOException {
    ByteArrayInputStream bIn = new ByteArrayInputStream(pemString.getBytes());
    PemReader pRdr = new PemReader(new InputStreamReader(bIn));
    try {
        PemObject pemObject = pRdr.readPemObject();
        return pemObject.getContent();
    } finally {
        pRdr.close();
    }
}
 
Example 16
Source File: PemFile.java    From arcusipcd with Apache License 2.0 5 votes vote down vote up
public PemFile(String filename) throws FileNotFoundException, IOException {
	PemReader pemReader = new PemReader(new InputStreamReader(new FileInputStream(filename)));
	try {
		this.pemObject = pemReader.readPemObject();
	} finally {
		pemReader.close();
	}
}
 
Example 17
Source File: CertUtils.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
public static PrivateKey pemToPrivateKey(final String pem) throws InvalidKeySpecException, IOException {
    final PemReader pr = new PemReader(new StringReader(pem));
    final PemObject pemObject = pr.readPemObject();
    final KeyFactory keyFactory = getKeyFactory();
    return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(pemObject.getContent()));
}
 
Example 18
Source File: CertUtils.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
public static PublicKey pemToPublicKey(final String pem) throws InvalidKeySpecException, IOException {
    final PemReader pr = new PemReader(new StringReader(pem));
    final PemObject pemObject = pr.readPemObject();
    final KeyFactory keyFactory = getKeyFactory();
    return keyFactory.generatePublic(new X509EncodedKeySpec(pemObject.getContent()));
}
 
Example 19
Source File: KeysStore.java    From julongchain with Apache License 2.0 4 votes vote down vote up
/**
 * 读取密钥数据
 * @param path 存储路径
 * @param pwd 口令
 * @param ski 密钥标识
 * @param keyType 密钥类型
 * @return
 */
public byte[] loadKey(String path, byte[] pwd, byte[] ski, int keyType) {
    if(null == ski || 0 == ski.length) {
        return null;
    }
    String fileName = getFileNameByType(ski, keyType);
    String fullPath = fileName;
    if(null != path && !"".equals(path)) {
        if(path.endsWith("/")) {
            fullPath = path + fullPath;
        } else {
            fullPath = path + File.separator + fullPath;
        }
    }
    //检查文件是否存在
    File inFile = new File(fullPath);
    if(!inFile.exists()) {
        return null;
    }
    long fileLen = inFile.length();
    Reader fileReader = null;
    PemObject pemObject = null;
    try {
        fileReader = new FileReader(inFile);
        char[] content = new char[(int) fileLen];
        fileReader.read(content);
        String str = new String(content);
        StringReader stringreader = new StringReader(str);
        PemReader pem = new PemReader(stringreader);
        pemObject = pem.readPemObject();
        //如果文件未加密则返回文件内容
        if(null == pwd || "".equals(pwd)) {
            return pemObject.getContent();
        }
        //获取IV数据
        byte[] objectContent = pemObject.getContent();
        byte[] iv = new byte[Constants.SM4_IV_LEN];
        System.arraycopy(objectContent, 0, iv, 0, Constants.SM4_IV_LEN);
        byte[] cipherContent = new byte[objectContent.length-Constants.SM4_IV_LEN];
        System.arraycopy(objectContent, Constants.SM4_IV_LEN, cipherContent, 0, objectContent.length-Constants.SM4_IV_LEN);

        //解密文件内容
        byte[] cipherKey = deriveKey(pwd, iv);
        byte[] plainContent = sm4.decryptCBC(cipherContent, cipherKey, iv);
        return  plainContent;

    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 20
Source File: RootCAProvider.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
private Certificate generateCertificateUsingCsr(final String csr, final List<String> names, final List<String> ips, final int validityDays) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, CertificateException, SignatureException, IOException, OperatorCreationException {
    final List<String> dnsNames = new ArrayList<>();
    final List<String> ipAddresses = new ArrayList<>();

    if (names != null) {
        dnsNames.addAll(names);
    }
    if (ips != null) {
        ipAddresses.addAll(ips);
    }

    PemObject pemObject = null;

    try {
        final PemReader pemReader = new PemReader(new StringReader(csr));
        pemObject = pemReader.readPemObject();
    } catch (IOException e) {
        LOG.error("Failed to read provided CSR string as a PEM object", e);
    }

    if (pemObject == null) {
        throw new CloudRuntimeException("Unable to read/process CSR: " + csr);
    }

    final JcaPKCS10CertificationRequest request = new JcaPKCS10CertificationRequest(pemObject.getContent());
    final String subject = request.getSubject().toString();
    for (final Attribute attribute : request.getAttributes()) {
        if (attribute == null) {
            continue;
        }
        if (attribute.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
            final Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0));
            final GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
            if (gns != null && gns.getNames() != null && gns.getNames().length > 0) {
                for (final GeneralName name : gns.getNames()) {
                    if (name.getTagNo() == GeneralName.dNSName) {
                        dnsNames.add(name.getName().toString());
                    }
                    if (name.getTagNo() == GeneralName.iPAddress) {
                        final InetAddress address = InetAddress.getByAddress(DatatypeConverter.parseHexBinary(name.getName().toString().substring(1)));
                        ipAddresses.add(address.toString().replace("/", ""));
                    }
                }
            }
        }
    }

    final X509Certificate clientCertificate = CertUtils.generateV3Certificate(
            caCertificate, caKeyPair, request.getPublicKey(),
            subject, CAManager.CertSignatureAlgorithm.value(),
            validityDays, dnsNames, ipAddresses);
    return new Certificate(clientCertificate, null, Collections.singletonList(caCertificate));
}