Java Code Examples for org.bouncycastle.util.io.pem.PemObject#getContent()

The following examples show how to use org.bouncycastle.util.io.pem.PemObject#getContent() . 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: 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 2
Source File: PEMImporter.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
private static List<X509Certificate> readCertificateChain(File certificateChainFile)
    throws IOException, GeneralSecurityException
{
    final List<X509Certificate> certs = new ArrayList<>();
    try(final PemReader pemReader = new PemReader(Files.newBufferedReader(certificateChainFile.toPath())))
    {
        final PemObject pemObject = pemReader.readPemObject();
        final CertificateFactory certificateFactory = CertificateFactory.getInstance("X509");
        final ByteArrayInputStream bais = new ByteArrayInputStream(pemObject.getContent());

        for (final Certificate cert : certificateFactory.generateCertificates(bais)) {
            if (cert instanceof X509Certificate) {
                certs.add((X509Certificate) cert);
            }
        }
        if (certs.isEmpty()) {
            throw new IllegalStateException("Unable to decode certificate chain");
        }
    }
    return certs;
}
 
Example 3
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 4
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 5
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 6
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 7
Source File: BCECUtil.java    From littleca with Apache License 2.0 5 votes vote down vote up
private static byte[] convertPemToDerEcData(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 8
Source File: TLS.java    From cava with Apache License 2.0 5 votes vote down vote up
/**
 * Read a PEM-encoded file.
 *
 * @param certificate The path to a PEM-encoded file.
 * @return The bytes for the PEM content.
 * @throws IOException If an IO error occurs.
 */
public static byte[] readPemFile(Path certificate) throws IOException {
  try (BufferedReader reader = Files.newBufferedReader(certificate, UTF_8);
      PemReader pemReader = new PemReader(reader)) {
    PemObject pemObject = pemReader.readPemObject();
    return pemObject.getContent();
  }
}
 
Example 9
Source File: JWTAuthOptionsFactory.java    From besu with Apache License 2.0 5 votes vote down vote up
private byte[] readPublicKey(final File publicKeyFile) {
  try (final BufferedReader reader = Files.newBufferedReader(publicKeyFile.toPath(), UTF_8);
      final PemReader pemReader = new PemReader(reader)) {
    final PemObject pemObject = pemReader.readPemObject();
    if (pemObject == null) {
      throw new IllegalStateException("Authentication RPC public key file format is invalid");
    }
    return pemObject.getContent();
  } catch (IOException e) {
    throw new IllegalStateException("Authentication RPC public key could not be read", e);
  }
}
 
Example 10
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 11
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 12
Source File: SshKeyUtils.java    From onedev with MIT License 5 votes vote down vote up
public static PublicKey decodePEMPublicKey(String publicKey) throws IOException, GeneralSecurityException {
    try (PemReader pemReaderPublic = new PemReader(new StringReader(publicKey))) {
        KeyFactory kf = SecurityUtils.getKeyFactory(KeyUtils.RSA_ALGORITHM);
        
        PemObject pemObjectPublic = pemReaderPublic.readPemObject();
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(pemObjectPublic.getContent());
        return kf.generatePublic(x509EncodedKeySpec);
    }
}
 
Example 13
Source File: SshKeyUtils.java    From onedev with MIT License 5 votes vote down vote up
public static PrivateKey decodePEMPrivateKey(String privateKey) throws IOException, GeneralSecurityException {
    try (PemReader pemReaderPrivate = new PemReader(new StringReader(privateKey))) {
        KeyFactory kf = SecurityUtils.getKeyFactory(KeyUtils.RSA_ALGORITHM);
        
        PemObject pemObjectPrivate = pemReaderPrivate.readPemObject();
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(pemObjectPrivate.getContent());
        return kf.generatePrivate(spec);
    }
}
 
Example 14
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 15
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 16
Source File: KeyCodec.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
/**
 * Reads a Private Key from the PEM Encoded Store.
 *
 * @param basePath - Base Path, Directory where the Key is stored.
 * @param keyFileName - File Name of the private key
 * @return PrivateKey Object.
 * @throws IOException - on Error.
 */
private PKCS8EncodedKeySpec readKey(Path basePath, String keyFileName)
    throws IOException {
  File fileName = Paths.get(basePath.toString(), keyFileName).toFile();
  String keyData = FileUtils.readFileToString(fileName, DEFAULT_CHARSET);
  final byte[] pemContent;
  try (PemReader pemReader = new PemReader(new StringReader(keyData))) {
    PemObject keyObject = pemReader.readPemObject();
    pemContent = keyObject.getContent();
  }
  return new PKCS8EncodedKeySpec(pemContent);
}
 
Example 17
Source File: CryptoPrimitives.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
public byte[] certificateToDER(String certificatePEM) {

        byte[] content = null;

        try (PemReader pemReader = new PemReader(new StringReader(certificatePEM))) {
            final PemObject pemObject = pemReader.readPemObject();
            content = pemObject.getContent();

        } catch (IOException e) {
            // best attempt
        }

        return content;
    }
 
Example 18
Source File: CertificateSignRequest.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
/**
 * Gets a CertificateRequest Object from PEM encoded CSR.
 *
 * @param csr - PEM Encoded Certificate Request String.
 * @return PKCS10CertificationRequest
 * @throws IOException - On Error.
 */
public static PKCS10CertificationRequest getCertificationRequest(String csr)
    throws IOException {
  try (PemReader reader = new PemReader(new StringReader(csr))) {
    PemObject pemObject = reader.readPemObject();
    if(pemObject.getContent() == null) {
      throw new SCMSecurityException("Invalid Certificate signing request");
    }
    return new PKCS10CertificationRequest(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));
}