org.bouncycastle.util.io.pem.PemReader Java Examples

The following examples show how to use org.bouncycastle.util.io.pem.PemReader. 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: CertificateHelper.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
public static List<Certificate> parseChain(final String chain) throws IOException, CertificateException {
    Preconditions.checkNotNull(chain);

    final List<Certificate> certs = new ArrayList<Certificate>();
    try(final PemReader pemReader = new PemReader(new StringReader(chain));)
    {
        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(cert);
            }
        }
        if (certs.isEmpty()) {
            throw new IllegalStateException("Unable to decode certificate chain");
        }
    }
    return certs;
}
 
Example #3
Source File: Actions.java    From xipki with Apache License 2.0 6 votes vote down vote up
protected List<X509Cert> getPeerCertificates()
    throws CertificateException, IOException {
  if (StringUtil.isNotBlank(peerCertsFile)) {
    try (PemReader pemReader = new PemReader(new FileReader(peerCertsFile))) {
      List<X509Cert> certs = new LinkedList<>();
      PemObject pemObj;
      while ((pemObj = pemReader.readPemObject()) != null) {
        if (!"CERTIFICATE".equals(pemObj.getType())) {
          continue;
        }

        certs.add(X509Util.parseCert(pemObj.getContent()));
      }
      return certs.isEmpty() ? null : certs;
    }
  } else if (StringUtil.isNotBlank(peerCertFile)) {
    X509Cert cert = X509Util.parseCert(Paths.get(peerCertFile).toFile());
    return Arrays.asList(cert);
  } else {
    return null;
  }
}
 
Example #4
Source File: RestCaClient.java    From xipki with Apache License 2.0 6 votes vote down vote up
private List<X509Certificate> httpgetCaCertchain() throws Exception {
  List<X509Certificate> certchain = new LinkedList<>();
  // Get CA certificate chain
  byte[] bytes = httpGet(caUrl + "/cacertchain", CT_PEM_FILE);
  try (PemReader pemReader =
      new PemReader(new InputStreamReader(new ByteArrayInputStream(bytes)))) {
    PemObject pemObject;
    while ((pemObject = pemReader.readPemObject()) != null) {
      if ("CERTIFICATE".contentEquals(pemObject.getType())) {
        certchain.add(SdkUtil.parseCert(pemObject.getContent()));
      }
    }
  }

  if (certchain.isEmpty()) {
    throw new Exception("could not retrieve certificates");
  }
  return certchain;
}
 
Example #5
Source File: MspValidateTest.java    From julongchain with Apache License 2.0 6 votes vote down vote up
@Test
public void certTest() throws IOException {
    String privateKey = "MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQgTchUuHEAckzfS16v\n" +
            "8hz4Rt9G+41OifbzAr9jM+JGxiygCgYIKoEcz1UBgi2hRANCAASDw0oz+lq1H8QM\n" +
            "8YaZSikOsCdbLR+sUd+hpzvDF1wmS3zVNqtKnTRzD3bVgR4AFljtBVmbXNmJdrno\n" +
            "C8r6EmyE";
    byte[] sk = org.bouncycastle.util.encoders.Base64.decode(privateKey);

    System.out.println("私钥长度" + sk.length);
    System.out.println(Hex.toHexString(sk));
    String cert_path = MspValidateTest.class.getResource("/szca/testsm2.pem").getPath();
    byte[] idBytes = FileUtils.readFileBytes(cert_path);
    Certificate certificate = Certificate.getInstance(new PemReader(new InputStreamReader(new ByteArrayInputStream(idBytes))).readPemObject().getContent());
    byte[] publickey = certificate.getSubjectPublicKeyInfo().getPublicKeyData().getBytes();

    System.out.println(certificate.getSubject());
    System.out.println("公钥:" + Hex.toHexString(publickey));
    System.out.println("公钥长度:" + publickey.length);
}
 
Example #6
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 #7
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 #8
Source File: KeyLoader.java    From protect with MIT License 6 votes vote down vote up
public KeyLoader(final File keyPath, final Set<String> keyNames) throws FileNotFoundException, IOException,
		NoSuchAlgorithmException, InvalidKeySpecException, CertificateException {

	this.tlsPublicKeys = new ArrayList<>(keyNames.size());
	this.verificationKeys = new ArrayList<>(keyNames.size());
	this.encryptionKeys = new ArrayList<>(keyNames.size());

	// Load all public keys
	for (String username : keyNames) {
		final File publicKeyFile = new File(keyPath, "public-" + username);

		try (final PemReader reader = new PemReader(new FileReader(publicKeyFile.getAbsolutePath()))) {
			final PublicKey tlsPublicKey = (PublicKey) Pem.readObject(reader.readPemObject());
			this.tlsPublicKeys.add(tlsPublicKey);
			this.userTlsKeyMap.put(Hex.encodeHexString(tlsPublicKey.getEncoded()), username);

			this.verificationKeys.add((PublicKey) Pem.readObject(reader.readPemObject()));
			this.encryptionKeys.add((PublicKey) Pem.readObject(reader.readPemObject()));
		}
	}

	this.tlsKey = null;
	this.signingKey = null;
	this.decryptionKey = null;
}
 
Example #9
Source File: PemToDerConverter.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Converts PEM encoded binaries to DER encoded equivalent
 * 
 * @param pemEncoded the PEM encoded byte array
 * @return DER encoded byte array
 */
public static byte[] convert(final byte[] pemEncoded) {
	try (ByteArrayInputStream bais = new ByteArrayInputStream(pemEncoded);
			Reader reader = new InputStreamReader(bais);
			PemReader pemReader = new PemReader(reader)) {
		PemObject pemObject = pemReader.readPemObject();
		if (pemObject == null) {
			throw new DSSException("Unable to read PEM Object");
		}
		byte[] binaries = pemObject.getContent();
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		os.write(binaries, 0, binaries.length);
		return os.toByteArray();
	} catch (IOException e) {
		throw new DSSException("Unable to convert the CRL to DER", e);
	}
}
 
Example #10
Source File: MspValidateTest.java    From julongchain with Apache License 2.0 6 votes vote down vote up
@Test
public void skKeyTest() throws IOException, JulongChainException, NoSuchAlgorithmException, InvalidKeySpecException {

    String sk_path = MspValidateTest.class.getResource("/sk-dxtest_sk").getPath();

    File inFile = new File(sk_path);
    long fileLen = inFile.length();
    Reader reader = null;
    PemObject pemObject = null;
    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();

    System.out.println(Hex.toHexString(pemObject.getContent()));
}
 
Example #11
Source File: CertTest.java    From julongchain with Apache License 2.0 6 votes vote down vote up
@Test
public void szcaCertTest() throws Exception {
    String skPath = "/szca/sk-test";
    String certPath = "/szca/signcert.pem";
    String testData = "this is test data";
    String privateKeyPath = CertTest.class.getResource(skPath).getPath();
    String signCertPath = CertTest.class.getResource(certPath).getPath();
    byte[] sk = CryptoUtil.getPrivateKey(privateKeyPath);
    byte[] certBytes = FileUtils.readFileBytes(signCertPath);
    Certificate signCert = Certificate.getInstance(
            new PemReader(new InputStreamReader(new ByteArrayInputStream(certBytes))).readPemObject().getContent());
    byte[] pk = signCert.getSubjectPublicKeyInfo().getPublicKeyData().getBytes();
    byte[] sign = sm2.sign(sk, testData.getBytes());
    boolean result = sm2.verify(pk, sign, testData.getBytes());
    assertEquals(true, result);
}
 
Example #12
Source File: SSLContextInitializer.java    From trufflesqueak with MIT License 6 votes vote down vote up
private static CertificateInfo readPem(final File file)
                throws IOException, GeneralSecurityException {

    Certificate certificate = null;
    PrivateKey key = null;

    try (PemReader reader = new PemReader(new FileReader(file))) {

        while (true) {
            final PemObject read = reader.readPemObject();
            if (read == null) {
                break;
            } else if (read.getType().equals(CERTIFICATE)) {
                certificate = readCertificate(read.getContent());
            } else if (read.getType().equals(PRIVATE_KEY)) {
                key = readPrivateKey(read.getContent());
            }
        }

        return new CertificateInfo(certificate, key);
    }
}
 
Example #13
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 #14
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 #15
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 #16
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 #17
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 #18
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 #19
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 #20
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 #21
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 #22
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 #23
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 #24
Source File: DefaultOAuthJwtAccessTokenTest.java    From athenz with Apache License 2.0 5 votes vote down vote up
@BeforeMethod
public void initialize() throws Exception {
    PublicKey pub = null;
    try (PemReader reader = new PemReader(new FileReader(this.getClass().getClassLoader().getResource("jwt_public.key").getFile()))) {
        pub = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(reader.readPemObject().getContent()));
    }
    this.parser = Jwts.parserBuilder().setSigningKey(pub).setAllowedClockSkewSeconds(60).build();
}
 
Example #25
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 #26
Source File: DSSUtils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * This method converts a PEM encoded certificate/crl/... to DER encoded
 * 
 * @param pemContent
 *            the String which contains the PEM encoded object
 * @return the binaries of the DER encoded object
 */
public static byte[] convertToDER(String pemContent) {
	try (Reader reader = new StringReader(pemContent); PemReader pemReader = new PemReader(reader)) {
		PemObject readPemObject = pemReader.readPemObject();
		return readPemObject.getContent();
	} catch (IOException e) {
		throw new DSSException("Unable to convert PEM to DER", e);
	}
}
 
Example #27
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 #28
Source File: CertServiceImpl.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
@Override
public Certificate parseCertificate(final String cert) {
    Preconditions.checkArgument(!Strings.isNullOrEmpty(cert));
    final PemReader certPem = new PemReader(new StringReader(cert));
    try {
        return readCertificateFromPemObject(certPem.readPemObject());
    } catch (final CertificateException | IOException e) {
        throw new InvalidParameterValueException("Invalid Certificate format. Expected X509 certificate. Failed due to " + e.getMessage());
    } finally {
        IOUtils.closeQuietly(certPem);
    }
}
 
Example #29
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 #30
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));
}