Java Code Examples for org.bouncycastle.util.io.pem.PemObject

The following examples show how to use org.bouncycastle.util.io.pem.PemObject. 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: hadoop-ozone   Source File: KeyCodec.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Writes a given private key using the default config options.
 *
 * @param key - Key to write to file.
 * @throws IOException - On I/O failure.
 */
public void writePrivateKey(PrivateKey key) throws IOException {
  File privateKeyFile =
      Paths.get(location.toString(),
          securityConfig.getPrivateKeyFileName()).toFile();

  if (Files.exists(privateKeyFile.toPath())) {
    throw new IOException("Private key already exist.");
  }

  try (PemWriter privateKeyWriter = new PemWriter(new
      FileWriterWithEncoding(privateKeyFile, DEFAULT_CHARSET))) {
    privateKeyWriter.writeObject(
        new PemObject(PRIVATE_KEY, key.getEncoded()));
  }
  Files.setPosixFilePermissions(privateKeyFile.toPath(), permissionSet);
}
 
Example 2
Source Project: hadoop-ozone   Source File: KeyCodec.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Writes a given public key using the default config options.
 *
 * @param key - Key to write to file.
 * @throws IOException - On I/O failure.
 */
public void writePublicKey(PublicKey key) throws IOException {
  File publicKeyFile = Paths.get(location.toString(),
      securityConfig.getPublicKeyFileName()).toFile();

  if (Files.exists(publicKeyFile.toPath())) {
    throw new IOException("Private key already exist.");
  }

  try (PemWriter keyWriter = new PemWriter(new
      FileWriterWithEncoding(publicKeyFile, DEFAULT_CHARSET))) {
    keyWriter.writeObject(
        new PemObject(PUBLIC_KEY, key.getEncoded()));
  }
  Files.setPosixFilePermissions(publicKeyFile.toPath(), permissionSet);
}
 
Example 3
Source Project: hadoop-ozone   Source File: KeyCodec.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Helper function that actually writes data to the files.
 *
 * @param basePath - base path to write key
 * @param keyPair - Key pair to write to file.
 * @param privateKeyFileName - private key file name.
 * @param publicKeyFileName - public key file name.
 * @param force - forces overwriting the keys.
 * @throws IOException - On I/O failure.
 */
private synchronized void writeKey(Path basePath, KeyPair keyPair,
    String privateKeyFileName, String publicKeyFileName, boolean force)
    throws IOException {
  checkPreconditions(basePath);

  File privateKeyFile =
      Paths.get(location.toString(), privateKeyFileName).toFile();
  File publicKeyFile =
      Paths.get(location.toString(), publicKeyFileName).toFile();
  checkKeyFile(privateKeyFile, force, publicKeyFile);

  try (PemWriter privateKeyWriter = new PemWriter(new
      FileWriterWithEncoding(privateKeyFile, DEFAULT_CHARSET))) {
    privateKeyWriter.writeObject(
        new PemObject(PRIVATE_KEY, keyPair.getPrivate().getEncoded()));
  }

  try (PemWriter publicKeyWriter = new PemWriter(new
      FileWriterWithEncoding(publicKeyFile, DEFAULT_CHARSET))) {
    publicKeyWriter.writeObject(
        new PemObject(PUBLIC_KEY, keyPair.getPublic().getEncoded()));
  }
  Files.setPosixFilePermissions(privateKeyFile.toPath(), permissionSet);
  Files.setPosixFilePermissions(publicKeyFile.toPath(), permissionSet);
}
 
Example 4
Source Project: hedera-sdk-java   Source File: PemUtils.java    License: 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 5
Source Project: julongchain   Source File: CryptoUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 公钥文件生成
 * @param path
 * @param content
 */
public static void publicKeyFileGen(String path, byte[] content) {
    PemObject pemObject = new PemObject("PUBLIC KEY", content);
    StringWriter str = new StringWriter();
    PemWriter pemWriter = new PemWriter(str);
    try {
        pemWriter.writeObject(pemObject);
        pemWriter.close();
        str.close();
        PrintWriter pw = new PrintWriter(new FileOutputStream(path + PK));
        String publiKey = new String(str.toString());
        pw.print(publiKey);
        pw.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 6
Source Project: julongchain   Source File: CryptoUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 私钥文件生成
 * @param path
 * @param content
 */
public static void privateKeyFileGen(String path, byte[] content) {
    PemObject pemObject = new PemObject("PRIVATE KEY", content);
    StringWriter str = new StringWriter();
    PemWriter pemWriter = new PemWriter(str);
    try {
        pemWriter.writeObject(pemObject);
        pemWriter.close();
        str.close();
        PrintWriter pw = new PrintWriter(new FileOutputStream(path + SK));
        String publiKey = new String(str.toString());
        pw.print(publiKey);
        pw.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 7
Source Project: julongchain   Source File: CryptoUtil.java    License: 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 8
Source Project: julongchain   Source File: CryptoUtil.java    License: 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 9
Source Project: julongchain   Source File: CryptoUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 从pem私钥文件中获取sk
 * @return
 */
public static byte[] getPrivateKey(String filePath)throws Exception{
    File inFile = new File(filePath);
    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);
    String privateKeyPEM = str.replace("-----BEGIN PRIVATE KEY-----\n", "")
            .replace("-----END PRIVATE KEY-----", "").replace("\n", "");
    Security.addProvider(new BouncyCastleProvider());
    KeyFactory keyf = KeyFactory.getInstance("EC");
    PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKeyPEM) );
    BCECPrivateKey priKey = (BCECPrivateKey)keyf.generatePrivate(priPKCS8);
    return priKey.getD().toByteArray();
}
 
Example 10
Source Project: julongchain   Source File: CaHelper.java    License: 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 11
Source Project: julongchain   Source File: MspValidateTest.java    License: 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 12
Source Project: protect   Source File: MessageStatusCli.java    License: MIT License 6 votes vote down vote up
private static void writeObject(final Key key, final PemWriter writer) throws IOException {

		final String description;
		if (key instanceof RSAPrivateKey) {
			description = "PAILLIER PRIVATE KEY";
		} else if (key instanceof RSAPublicKey) {
			description = "PAILLIER PUBLIC KEY";
		} else if (key instanceof ECPrivateKey) {
			description = "EC PRIVATE KEY";
		} else if (key instanceof ECPublicKey) {
			description = "EC PUBLIC KEY";
		} else if (key instanceof EdDSAPrivateKey) {
			description = "ED25519 PRIVATE KEY";
		} else if (key instanceof EdDSAPublicKey) {
			description = "ED25519 PUBLIC KEY";
		} else if (key instanceof PrivateKey) {
			description = "PRIVATE KEY";
		} else if (key instanceof PublicKey) {
			description = "PUBLIC KEY";
		} else {
			description = "KEY";
		}

		writer.writeObject(new PemObject(description, key.getEncoded()));
	}
 
Example 13
Source Project: snowblossom   Source File: CertGen.java    License: Apache License 2.0 6 votes vote down vote up
public static ByteString pemCode(byte[] encoded, String type)
{
  try
  {
    PemObject po = new PemObject(type, encoded);

    ByteArrayOutputStream b_out = new ByteArrayOutputStream();

    PemWriter w = new PemWriter( new OutputStreamWriter(b_out));

    w.writeObject(po);
    w.flush();
    w.close();

    return ByteString.copyFrom(b_out.toByteArray());
  }
  catch(java.io.IOException e)
  {
    throw new RuntimeException(e);
  }

}
 
Example 14
Source Project: trufflesqueak   Source File: SSLContextInitializer.java    License: 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 15
Source Project: fabric-sdk-java   Source File: TLSCertificateKeyPair.java    License: 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 16
Source Project: vespa   Source File: KeyUtils.java    License: Apache License 2.0 6 votes vote down vote up
private static String toPkcs1Pem(PrivateKey privateKey) {
    try (StringWriter stringWriter = new StringWriter(); JcaPEMWriter pemWriter = new JcaPEMWriter(stringWriter)) {
        String algorithm = privateKey.getAlgorithm();
        String type;
        if (algorithm.equals(RSA.getAlgorithmName())) {
            type = "RSA PRIVATE KEY";
        } else if (algorithm.equals(EC.getAlgorithmName())) {
            type = "EC PRIVATE KEY";
        } else {
            throw new IllegalArgumentException("Unexpected key algorithm: " + algorithm);
        }
        pemWriter.writeObject(new PemObject(type, getPkcs1Bytes(privateKey)));
        pemWriter.flush();
        return stringWriter.toString();
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 17
Source Project: dss   Source File: PemToDerConverter.java    License: 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 18
Source Project: zeppelin   Source File: PEMImporter.java    License: 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 19
Source Project: xipki   Source File: RestCaClient.java    License: 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 20
Source Project: xipki   Source File: Actions.java    License: 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 21
Source Project: cloudstack   Source File: CertificateHelper.java    License: 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 22
Source Project: incubator-tuweni   Source File: TLS.java    License: 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 23
Source Project: hadoop-ozone   Source File: CertificateSignRequest.java    License: Apache License 2.0 5 votes vote down vote up
public static String getEncodedString(PKCS10CertificationRequest request)
    throws IOException {
  PemObject pemObject =
      new PemObject("CERTIFICATE REQUEST", request.getEncoded());
  StringWriter str = new StringWriter();
  try(JcaPEMWriter pemWriter = new JcaPEMWriter(str)) {
    pemWriter.writeObject(pemObject);
  }
  return str.toString();
}
 
Example 24
Source Project: hadoop-ozone   Source File: CertificateSignRequest.java    License: 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 25
Source Project: hadoop-ozone   Source File: KeyCodec.java    License: 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 26
Source Project: besu   Source File: JWTAuthOptionsFactory.java    License: 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 27
Source Project: dremio-flight-connector   Source File: SslHelper.java    License: Apache License 2.0 5 votes vote down vote up
private static InputStream keyToStream(PrivateKey key) throws IOException {
  final StringWriter writer = new StringWriter();
  final JcaPEMWriter pemWriter = new JcaPEMWriter(writer);
  pemWriter.writeObject(new PemObject("PRIVATE KEY", key.getEncoded()));
  pemWriter.flush();
  pemWriter.close();
  String pemString = writer.toString();
  return new ByteArrayInputStream(pemString.getBytes());
}
 
Example 28
Source Project: javasdk   Source File: CertUtil.java    License: 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 29
Source Project: hedera-sdk-java   Source File: Ed25519PrivateKey.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Write out a PEM encoded version of this private key.
 *
 * @deprecated for removal; exporting unencrypted PEMs is very insecure and has dubious
 * utility.
 */
@Deprecated
public void writePem(Writer out) throws IOException {
    final PemWriter pemWriter = new PemWriter(out);
    pemWriter.writeObject(new PemObject(PemUtils.TYPE_PRIVATE_KEY, encodeDER()));
    pemWriter.flush();
}
 
Example 30
Source Project: hedera-sdk-java   Source File: PemUtils.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unused")
public static void writeEncryptedPrivateKey(PrivateKeyInfo pkInfo, Writer out, String passphrase) throws IOException {
    byte[] salt = CryptoUtils.randomBytes(CryptoUtils.SALT_LEN);

    KeyParameter derivedKey = CryptoUtils.deriveKeySha256(
        passphrase, salt, CryptoUtils.ITERATIONS, CryptoUtils.CBC_DK_LEN);

    byte[] iv = CryptoUtils.randomBytes(CryptoUtils.IV_LEN);

    Cipher cipher = CryptoUtils.initAesCbc128Encrypt(derivedKey, iv);

    byte[] encryptedKey = CryptoUtils.runCipher(cipher, pkInfo.getEncoded());

    // I wanted to just do this with BC's PKCS8Generator and KcePKCSPBEOutputEncryptorBuilder
    // but it tries to init AES instance of `Cipher` with a `PBKDF2Key` and the former complains

    // So this is basically a reimplementation of that minus the excess OO
    PBES2Parameters parameters = new PBES2Parameters(
        new KeyDerivationFunc(
            PKCSObjectIdentifiers.id_PBKDF2,
            new PBKDF2Params(
                salt,
                CryptoUtils.ITERATIONS,
                CryptoUtils.CBC_DK_LEN,
                new AlgorithmIdentifier(PKCSObjectIdentifiers.id_hmacWithSHA256))),
        new EncryptionScheme(NISTObjectIdentifiers.id_aes128_CBC,
            ASN1Primitive.fromByteArray(cipher.getParameters().getEncoded())));

    EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(
        new AlgorithmIdentifier(PKCSObjectIdentifiers.id_PBES2, parameters),
        encryptedKey);

    PemWriter writer = new PemWriter(out);
    writer.writeObject(new PemObject(TYPE_ENCRYPTED_PRIVATE_KEY, encryptedPrivateKeyInfo.getEncoded()));
    writer.flush();
}