Java Code Examples for org.bouncycastle.asn1.pkcs.PrivateKeyInfo#getInstance()

The following examples show how to use org.bouncycastle.asn1.pkcs.PrivateKeyInfo#getInstance() . 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: Ed25519PrivateKey.java    From hedera-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * Construct an Ed25519PrivateKey from a raw byte array.
 *
 * @throws BadKeyException if the key bytes are of an incorrect length for a raw
 *                         private key or private key + public key, or do not represent a DER encoded Ed25519
 *                         private key.
 */
public static Ed25519PrivateKey fromBytes(byte[] keyBytes) {
    if (keyBytes.length == Ed25519.SECRET_KEY_SIZE) {
        // if the decoded bytes matches the length of a private key, try that
        return new Ed25519PrivateKey(new Ed25519PrivateKeyParameters(keyBytes, 0));
    } else if (keyBytes.length == Ed25519.SECRET_KEY_SIZE + Ed25519.PUBLIC_KEY_SIZE) {
        // some legacy code delivers raw private and public key pairs concatted together
        return new Ed25519PrivateKey(
            // this is how we read only the first 32 bytes
            new Ed25519PrivateKeyParameters(keyBytes, 0),
            // read the remaining 32 bytes as the public key
            new Ed25519PublicKeyParameters(keyBytes, Ed25519.SECRET_KEY_SIZE));
    } else {
        // decode a properly DER-encoded private key descriptor
        PrivateKeyInfo privateKeyInfo = PrivateKeyInfo.getInstance(keyBytes);
        return fromPrivateKeyInfo(privateKeyInfo);
    }
}
 
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: ZipUtils.java    From isu with GNU General Public License v3.0 6 votes vote down vote up
/** Read a PKCS#8 format private key. */
private static PrivateKey readPrivateKey(InputStream input)
throws IOException, GeneralSecurityException {
    try {
        byte[] buffer = new byte[4096];
        int size = input.read(buffer);
        byte[] bytes = Arrays.copyOf(buffer, size);
        /* Check to see if this is in an EncryptedPrivateKeyInfo structure. */
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(bytes);
        /*
         * Now it's in a PKCS#8 PrivateKeyInfo structure. Read its Algorithm
         * OID and use that to construct a KeyFactory.
         */
        ASN1InputStream bIn = new ASN1InputStream(new ByteArrayInputStream(spec.getEncoded()));
        PrivateKeyInfo pki = PrivateKeyInfo.getInstance(bIn.readObject());
        String algOid = pki.getPrivateKeyAlgorithm().getAlgorithm().getId();
        return KeyFactory.getInstance(algOid).generatePrivate(spec);
    } finally {
        input.close();
    }
}
 
Example 4
Source File: BCECUtil.java    From littleca with Apache License 2.0 5 votes vote down vote up
/**
 * openssl d2i_ECPrivateKey函数要求的DER编码的私钥也是PKCS1标准的,
 * 这个工具函数的主要目的就是为了能生成一个openssl可以“识别”的ECC私钥
 *
 * @param priKey
 * @param pubKey
 * @return
 * @throws IOException
 */
public static byte[] convertEcPriKeyToPkcs1Der(ECPrivateKeyParameters priKey,
                                               ECPublicKeyParameters pubKey) throws IOException {
    byte[] pkcs8Bytes = convertEcPriKeyToPkcs8Der(priKey, pubKey);
    PrivateKeyInfo pki = PrivateKeyInfo.getInstance(pkcs8Bytes);
    ASN1Encodable encodable = pki.parsePrivateKey();
    ASN1Primitive primitive = encodable.toASN1Primitive();
    byte[] pkcs1Bytes = primitive.getEncoded();
    return pkcs1Bytes;
}
 
Example 5
Source File: KeyUtils.java    From vespa with Apache License 2.0 5 votes vote down vote up
private static byte[] getPkcs1Bytes(PrivateKey privateKey) throws IOException{
    byte[] privBytes = privateKey.getEncoded();
    PrivateKeyInfo pkInfo = PrivateKeyInfo.getInstance(privBytes);
    ASN1Encodable encodable = pkInfo.parsePrivateKey();
    ASN1Primitive primitive = encodable.toASN1Primitive();
    return primitive.getEncoded();
}
 
Example 6
Source File: PrivateKeyCryptor.java    From xipki with Apache License 2.0 5 votes vote down vote up
PKCS8EncryptedPrivateKeyInfo encrypt(PrivateKey privateKey) {
  Args.notNull(privateKey, "privateKey");
  PrivateKeyInfo privateKeyInfo = PrivateKeyInfo.getInstance(privateKey.getEncoded());
  PKCS8EncryptedPrivateKeyInfoBuilder builder = new PKCS8EncryptedPrivateKeyInfoBuilder(
      privateKeyInfo);
  synchronized (encryptor) {
    return builder.build(encryptor);
  }
}
 
Example 7
Source File: PemUtils.java    From hedera-sdk-java with Apache License 2.0 4 votes vote down vote up
private static PrivateKeyInfo decryptPrivateKey(byte[] encodedStruct, String passphrase) throws IOException {
    PKCS8EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new PKCS8EncryptedPrivateKeyInfo(encodedStruct);

    AlgorithmIdentifier encryptAlg = encryptedPrivateKeyInfo.getEncryptionAlgorithm();

    if (!encryptAlg.getAlgorithm().equals(PKCSObjectIdentifiers.id_PBES2)) {
        throw new BadKeyException("unsupported PEM key encryption: " + encryptAlg);
    }

    PBES2Parameters params = PBES2Parameters.getInstance(encryptAlg.getParameters());
    KeyDerivationFunc kdf = params.getKeyDerivationFunc();
    EncryptionScheme encScheme = params.getEncryptionScheme();

    if (!kdf.getAlgorithm().equals(PKCSObjectIdentifiers.id_PBKDF2)) {
        throw new BadKeyException("unsupported KDF: " + kdf.getAlgorithm());
    }

    if (!encScheme.getAlgorithm().equals(NISTObjectIdentifiers.id_aes128_CBC)) {
        throw new BadKeyException("unsupported encryption: " + encScheme.getAlgorithm());
    }

    PBKDF2Params kdfParams = PBKDF2Params.getInstance(kdf.getParameters());

    if (!kdfParams.getPrf().getAlgorithm().equals(PKCSObjectIdentifiers.id_hmacWithSHA256)) {
        throw new BadKeyException("unsupported PRF: " + kdfParams.getPrf());
    }

    int keyLength = kdfParams.getKeyLength() != null
        ? kdfParams.getKeyLength().intValueExact()
        : CryptoUtils.CBC_DK_LEN;

    KeyParameter derivedKey = CryptoUtils.deriveKeySha256(
        passphrase,
        kdfParams.getSalt(),
        kdfParams.getIterationCount().intValueExact(),
        keyLength);

    AlgorithmParameters aesParams;
    try {
        aesParams = AlgorithmParameters.getInstance("AES");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    aesParams.init(encScheme.getParameters().toASN1Primitive().getEncoded());

    Cipher cipher = CryptoUtils.initAesCbc128Decrypt(derivedKey, aesParams);
    byte[] decrypted = CryptoUtils.runCipher(cipher, encryptedPrivateKeyInfo.getEncryptedData());

    // we need to parse our input data as the cipher may add padding
    ASN1InputStream inputStream = new ASN1InputStream(new ByteArrayInputStream(decrypted));
    return PrivateKeyInfo.getInstance(inputStream.readObject());
}
 
Example 8
Source File: CmpCaClient.java    From xipki with Apache License 2.0 4 votes vote down vote up
private Map<BigInteger, KeyAndCert> parseEnrollCertResult(PKIMessage response,
    int resonseBodyType, int numCerts) throws Exception {
  PKIBody respBody = response.getBody();
  final int bodyType = respBody.getType();

  if (PKIBody.TYPE_ERROR == bodyType) {
    ErrorMsgContent content = ErrorMsgContent.getInstance(respBody.getContent());
    throw new Exception("Server returned PKIStatus: " + buildText(content.getPKIStatusInfo()));
  } else if (resonseBodyType != bodyType) {
    throw new Exception(String.format("unknown PKI body type %s instead the expected [%s, %s]",
        bodyType, resonseBodyType, PKIBody.TYPE_ERROR));
  }

  CertRepMessage certRep = CertRepMessage.getInstance(respBody.getContent());
  CertResponse[] certResponses = certRep.getResponse();

  if (certResponses.length != numCerts) {
    throw new Exception("expected " + numCerts + " CertResponse, but returned "
        + certResponses.length);
  }

  // We only accept the certificates which are requested.
  Map<BigInteger, KeyAndCert> keycerts = new HashMap<>(numCerts * 2);
  for (int i = 0; i < numCerts; i++) {
    CertResponse certResp = certResponses[i];
    PKIStatusInfo statusInfo = certResp.getStatus();
    int status = statusInfo.getStatus().intValue();
    BigInteger certReqId = certResp.getCertReqId().getValue();

    if (status != PKIStatus.GRANTED && status != PKIStatus.GRANTED_WITH_MODS) {
      throw new Exception("CertReqId " + certReqId
          + ": server returned PKIStatus: " + buildText(statusInfo));
    }

    CertifiedKeyPair cvk = certResp.getCertifiedKeyPair();
    if (cvk != null) {
      CMPCertificate cmpCert = cvk.getCertOrEncCert().getCertificate();
      X509Certificate cert = SdkUtil.parseCert(cmpCert.getX509v3PKCert().getEncoded());
      if (!verify(caCert, cert)) {
        throw new Exception("CertReqId " + certReqId
            + ": the returned certificate is not issued by the given CA");
      }

      EncryptedValue encKey = cvk.getPrivateKey();
      PrivateKeyInfo key = null;
      if (encKey != null) {
        byte[] keyBytes = decrypt(encKey);
        key = PrivateKeyInfo.getInstance(keyBytes);
      }

      keycerts.put(certReqId, new KeyAndCert(key, cert));
    }
  }

  return keycerts;
}
 
Example 9
Source File: BCECUtil.java    From gmhelper with Apache License 2.0 3 votes vote down vote up
/**
 * 将ECC私钥转换为SEC1标准的字节流
 * openssl d2i_ECPrivateKey函数要求的DER编码的私钥也是SEC1标准的,
 * 这个工具函数的主要目的就是为了能生成一个openssl可以直接“识别”的ECC私钥.
 * 相对RSA私钥的PKCS1标准,ECC私钥的标准为SEC1
 *
 * @param priKey
 * @param pubKey
 * @return
 * @throws IOException
 */
public static byte[] convertECPrivateKeyToSEC1(
        ECPrivateKeyParameters priKey, ECPublicKeyParameters pubKey) throws IOException {
    byte[] pkcs8Bytes = convertECPrivateKeyToPKCS8(priKey, pubKey);
    PrivateKeyInfo pki = PrivateKeyInfo.getInstance(pkcs8Bytes);
    ASN1Encodable encodable = pki.parsePrivateKey();
    ASN1Primitive primitive = encodable.toASN1Primitive();
    byte[] sec1Bytes = primitive.getEncoded();
    return sec1Bytes;
}
 
Example 10
Source File: BCECUtil.java    From jiguang-java-client-common with MIT License 3 votes vote down vote up
/**
 * 将ECC私钥转换为SEC1标准的字节流
 * openssl d2i_ECPrivateKey函数要求的DER编码的私钥也是SEC1标准的,
 * 这个工具函数的主要目的就是为了能生成一个openssl可以直接“识别”的ECC私钥.
 * 相对RSA私钥的PKCS1标准,ECC私钥的标准为SEC1
 *
 * @param priKey
 * @param pubKey
 * @return
 * @throws IOException
 */
public static byte[] convertECPrivateKeyToSEC1(ECPrivateKeyParameters priKey,
    ECPublicKeyParameters pubKey) throws IOException {
    byte[] pkcs8Bytes = convertECPrivateKeyToPKCS8(priKey, pubKey);
    PrivateKeyInfo pki = PrivateKeyInfo.getInstance(pkcs8Bytes);
    ASN1Encodable encodable = pki.parsePrivateKey();
    ASN1Primitive primitive = encodable.toASN1Primitive();
    byte[] sec1Bytes = primitive.getEncoded();
    return sec1Bytes;
}
 
Example 11
Source File: EccUtil.java    From keystore-explorer with GNU General Public License v3.0 3 votes vote down vote up
/**
 * Converts PKCS#8 EC private key (RFC 5208 ASN.1 PrivateKeyInfo structure) to "traditional" OpenSSL
 * ASN.1 structure ECPrivateKey from RFC 5915. As ECPrivateKey is already in the PrivateKey field of PrivateKeyInfo,
 * this must only be extracted:
 *
 * SEQUENCE {
 *	  INTEGER 0
 *	  SEQUENCE {
 *	    OBJECT IDENTIFIER ecPublicKey (1 2 840 10045 2 1)
 *	    OBJECT IDENTIFIER prime256v1 (1 2 840 10045 3 1 7)
 *	    }
 *	  OCTET STRING, encapsulates {
 *	    SEQUENCE {
 *	      INTEGER 1
 *	      OCTET STRING
 *	        17 12 CA 42 16 79 1B 45    ...B.y.E
 *	        ...
 *	        C8 B2 66 0A E5 60 50 0B
 *	      [0] {
 *	        OBJECT IDENTIFIER prime256v1 (1 2 840 10045 3 1 7)
 *	        }
 *	      [1] {
 *	        BIT STRING
 *	          04 61 C0 08 B4 89 A0 50    .a.....P
 *            ...
 *	          AE D5 ED C3 4D 0E 47 91    ....M.G.
 *	          89                         .
 *	        }
 *	      }
 *	    }
 *	  }
 *
 * @param ecPrivateKey An EC key
 * @return Object holding ASN1 ECPrivateKey structure
 * @throws IOException When ECPrivateKey structure in PrivateKeyInfo's PrivateKey field cannot be parsed
 */
public static org.bouncycastle.asn1.sec.ECPrivateKey convertToECPrivateKeyStructure(ECPrivateKey ecPrivateKey)
		throws IOException {
	byte[] encoded = ecPrivateKey.getEncoded();
	PrivateKeyInfo privateKeyInfo = PrivateKeyInfo.getInstance(encoded);
	ASN1Encodable privateKey = privateKeyInfo.parsePrivateKey();
	return org.bouncycastle.asn1.sec.ECPrivateKey.getInstance(privateKey);
}