/** * Helper method for newSelfSignedCACert() and newCert(). Initializes a X509v3CertificateBuilder with * logic that's common to both methods. * @param issuer Issuer field of the new cert. * @param notBefore date before which the new cert is not valid. * @param notAfter date after which the new cert is not valid. * @param subject Subject field of the new cert. * @param subjectPublicKey public key to store in the new cert. * @return a X509v3CertificateBuilder that can be further customized to finish creating the new cert. */ private static X509v3CertificateBuilder initCertBuilder( X500Name issuer, Date notBefore, Date notAfter, X500Name subject, PublicKey subjectPublicKey) { return new X509v3CertificateBuilder( issuer, new BigInteger(SERIAL_NUMBER_MAX_BITS, PRNG), notBefore, notAfter, subject, SubjectPublicKeyInfo.getInstance(subjectPublicKey.getEncoded())); }
/** * Returns a {@link PEMKeyPair} object with direct access to the public and private keys given a PKCS #8 private key. * * @param privateKeyInfo the PKCS #8 private key info * @return the PKCS #1 public and private key pair * @throws IOException if there is an error converting the key pair */ private static PEMKeyPair convertPrivateKeyFromPKCS8ToPKCS1(PrivateKeyInfo privateKeyInfo) throws IOException { // Parse the key wrapping to determine the internal key structure ASN1Encodable asn1PrivateKey = privateKeyInfo.parsePrivateKey(); // Convert the parsed key to an RSA private key RSAPrivateKey keyStruct = RSAPrivateKey.getInstance(asn1PrivateKey); // Create the RSA public key from the modulus and exponent RSAPublicKey pubSpec = new RSAPublicKey( keyStruct.getModulus(), keyStruct.getPublicExponent()); // Create an algorithm identifier for forming the key pair AlgorithmIdentifier algId = new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE); if (isVerbose()) { logger.info("Converted private key from PKCS #8 to PKCS #1 RSA private key"); } // Create the key pair container return new PEMKeyPair(new SubjectPublicKeyInfo(algId, pubSpec), new PrivateKeyInfo(algId, keyStruct)); }
private byte[] getKeyHashFromCertHolder(X509CertificateHolder certHolder) throws IOException { // https://tools.ietf.org/html/rfc2560#section-4.2.1 // KeyHash ::= OCTET STRING -- SHA-1 hash of responder's public key // -- (i.e., the SHA-1 hash of the value of the // -- BIT STRING subjectPublicKey [excluding // -- the tag, length, and number of unused // -- bits] in the responder's certificate) // code below inspired by org.bouncycastle.cert.ocsp.CertificateID.createCertID() // tested with SO52757037-Signed3-OCSP-with-KeyHash.pdf SubjectPublicKeyInfo info = certHolder.getSubjectPublicKeyInfo(); try { return MessageDigest.getInstance("SHA-1").digest(info.getPublicKeyData().getBytes()); } catch (NoSuchAlgorithmException ex) { // should not happen LOG.error("SHA-1 Algorithm not found", ex); return new byte[0]; } }
BCGOST3410PublicKey( SubjectPublicKeyInfo info) { GOST3410PublicKeyAlgParameters params = GOST3410PublicKeyAlgParameters.getInstance(info.getAlgorithm().getParameters()); DEROctetString derY; try { derY = (DEROctetString)info.parsePublicKey(); byte[] keyEnc = derY.getOctets(); byte[] keyBytes = new byte[keyEnc.length]; for (int i = 0; i != keyEnc.length; i++) { keyBytes[i] = keyEnc[keyEnc.length - 1 - i]; // was little endian } this.y = new BigInteger(1, keyBytes); } catch (IOException e) { throw new IllegalArgumentException("invalid info structure in GOST3410 public key"); } this.gost3410Spec = GOST3410ParameterSpec.fromPublicKeyAlg(params); }
public X509Certificate createSelfSignedCertificate(KeyPair keyPair) throws NoSuchAlgorithmException, NoSuchProviderException, CertIOException, OperatorCreationException, CertificateException { long serial = System.currentTimeMillis(); SubjectPublicKeyInfo keyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); X500Name name = new X500Name(createX500NameString()); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(name, BigInteger.valueOf(serial), new Date(System.currentTimeMillis() - 1000000000), new Date(System.currentTimeMillis() + 1000000000), name, keyInfo ); certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); certBuilder.addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth)); JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256withRSA"); ContentSigner signer = csBuilder.build(keyPair.getPrivate()); X509CertificateHolder certHolder = certBuilder.build(signer); X509Certificate cert = new JcaX509CertificateConverter().getCertificate(certHolder); return cert; } }
params = new DSTU4145Params(new ASN1ObjectIdentifier(((ECNamedCurveSpec)ecSpec).getName())); EC5Util.convertPoint(curve, ecSpec.getGenerator(), withCompression), ecSpec.getOrder(), BigInteger.valueOf(ecSpec.getCofactor()), ecSpec.getCurve().getSeed()); info = new SubjectPublicKeyInfo(new AlgorithmIdentifier(UAObjectIdentifiers.dstu4145be, params), new DEROctetString(encKey));
AsymmetricKeyParameter getPublicKeyParameters(SubjectPublicKeyInfo keyInfo, Object defaultParams) throws IOException { DHParameter params = DHParameter.getInstance(keyInfo.getAlgorithm().getParameters()); ASN1Integer derY = (ASN1Integer)keyInfo.parsePublicKey(); BigInteger lVal = params.getL(); int l = lVal == null ? 0 : lVal.intValue(); DHParameters dhParams = new DHParameters(params.getP(), params.getG(), null, l); return new DHPublicKeyParameters(derY.getValue(), dhParams); } }
protected void engineInitVerify( PublicKey publicKey) throws InvalidKeyException { ECKeyParameters param; if (publicKey instanceof ECPublicKey) { param = (ECKeyParameters)generatePublicKeyParameter(publicKey); } else { try { byte[] bytes = publicKey.getEncoded(); publicKey = BouncyCastleProvider.getPublicKey(SubjectPublicKeyInfo.getInstance(bytes)); param = (ECKeyParameters)ECUtil.generatePublicKeyParameter(publicKey); } catch (Exception e) { throw new InvalidKeyException("cannot recognise key type in ECGOST-2012-256 signer"); } } if (param.getParameters().getN().bitLength() > 256) { throw new InvalidKeyException("key out of range for ECGOST-2012-256"); } digest.reset(); signer.init(false, param); }
protected static MyKeypair generateEcKeypair() throws GeneralSecurityException { KeyPairGenerator kpGen = KeyPairGenerator.getInstance("EC"); ECGenParameterSpec spec = new ECGenParameterSpec("secp256r1"); kpGen.initialize(spec); KeyPair kp = kpGen.generateKeyPair(); ECPublicKey pub = (ECPublicKey) kp.getPublic(); byte[] keyData = new byte[65]; keyData[0] = 4; copyArray(pub.getW().getAffineX().toByteArray(), keyData, 1, 32); copyArray(pub.getW().getAffineY().toByteArray(), keyData, 33, 32); AlgorithmIdentifier algId = new AlgorithmIdentifier( X9ObjectIdentifiers.id_ecPublicKey, SECObjectIdentifiers.secp256r1); SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo(algId, keyData); return new MyKeypair(kp.getPrivate(), subjectPublicKeyInfo); }
/** * Create subjectKeyIdentifier * The Subject Key Identifier extension identifies the public key certified by this certificate. * This extension provides a way of distinguishing public keys if more than one is available for * a given subject name. * i.e. * Identifier: Subject Key Identifier - 2.5.29.14 * Critical: no * Key Identifier: * 3B:46:83:85:27:BC:F5:9D:8E:63:E3:BE:79:EF:AF:79: * 9C:37:85:84 * * */ protected SubjectKeyIdentifier createSubjectKeyIdentifier(PublicKey publicKey) throws IOException { try (ByteArrayInputStream bais = new ByteArrayInputStream(publicKey.getEncoded()); ASN1InputStream ais = new ASN1InputStream(bais)) { ASN1Sequence asn1Sequence = (ASN1Sequence) ais.readObject(); SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo(asn1Sequence); return new BcX509ExtensionUtils().createSubjectKeyIdentifier(subjectPublicKeyInfo); } }
public V3X509CertificateGenerator(Date startDate, X500Name issuerDn, X500Name subjectDn, PublicKey publicKey, BigInteger serialNumber) { SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()); this.v3CertGen = new X509v3CertificateBuilder(issuerDn, serialNumber, startDate, new DateTime().plusYears(YEARS).toDate(), subjectDn, publicKeyInfo); }
byte[] encodedPubKey = pubKey.getEncoded(); SubjectPublicKeyInfo spkInfo = SubjectPublicKeyInfo.getInstance(encodedPubKey); ASN1Primitive primitive = spkInfo.parsePublicKey(); PublicKey publicKey = KeyCodec.getRSAPublicKey(primitive.getEncoded()); logger.info("pub=" + Base64.encodeBase64URLSafeString(encodedPubKey)); logger.info("pub format=" + pubKey.getFormat()); logger.info("pub alg=" + pubKey.getAlgorithm());
private KeyPairWithSubjectPublicKeyInfo genECKeypair(String curveNameOrOid, SecureRandom random) throws Exception { ASN1ObjectIdentifier curveOid = AlgorithmUtil.getCurveOidForCurveNameOrOid(curveNameOrOid); if (curveOid == null) { throw new IllegalArgumentException("invalid curveNameOrOid '" + curveNameOrOid + "'"); } KeyPair kp = KeyUtil.generateECKeypair(curveOid, random); AlgorithmIdentifier algId = new AlgorithmIdentifier( X9ObjectIdentifiers.id_ecPublicKey, curveOid); ECPublicKey pub = (ECPublicKey) kp.getPublic(); int orderBitLength = pub.getParams().getOrder().bitLength(); byte[] keyData = KeyUtil.getUncompressedEncodedECPoint(pub.getW(), orderBitLength); SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo(algId, keyData); return new KeyPairWithSubjectPublicKeyInfo(kp, subjectPublicKeyInfo); }
private static SubjectKeyIdentifier publicKeyToSubjectKeyIdentifier(PublicKey publicKey) throws OperatorCreationException { SubjectPublicKeyInfo pubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()); DigestCalculator digCalc = new BcDigestCalculatorProvider().get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1)); X509ExtensionUtils utils = new X509ExtensionUtils(digCalc); return utils.createSubjectKeyIdentifier(pubKeyInfo); }
public PublicKey generatePublic(SubjectPublicKeyInfo keyInfo) throws IOException { ASN1ObjectIdentifier algOid = keyInfo.getAlgorithm().getAlgorithm(); if (algOid.equals(X9ObjectIdentifiers.id_ecPublicKey)) { return new BCECPublicKey(algorithm, keyInfo, configuration); } else { throw new IOException("algorithm identifier " + algOid + " in key not recognised"); } }
private void prepareKeyBlob() throws IOException { SubjectPublicKeyInfo ephemeralKey = null; CustomECPoint ecPoint = msg.getComputations().getClientPublicKey(); if (ecPoint != null) { ephemeralKey = SubjectPublicKeyInfo.getInstance(generatePublicKey(ecPoint).getEncoded()); } Gost2814789EncryptedKey encryptedKey = new Gost2814789EncryptedKey(msg.getComputations().getEncryptedKey() .getValue(), getMaskKey(), msg.getComputations().getMacKey().getValue()); ASN1ObjectIdentifier paramSet = new ASN1ObjectIdentifier(msg.getComputations().getEncryptionParamSet() .getValue()); GostR3410TransportParameters params = new GostR3410TransportParameters(paramSet, ephemeralKey, msg .getComputations().getUkm().getValue()); GostR3410KeyTransport transport = new GostR3410KeyTransport(encryptedKey, params); DERSequence proxyKeyBlobs = (DERSequence) DERSequence.getInstance(getProxyKeyBlobs()); TLSGostKeyTransportBlob blob = new TLSGostKeyTransportBlob(transport, proxyKeyBlobs); msg.setKeyTransportBlob(blob.getEncoded()); LOGGER.debug("GOST key blob: " + ASN1Dump.dumpAsString(blob, true)); }
private KeyTransRecipientInfo computeRecipientInfo(X509Certificate x509certificate, byte[] abyte0) throws IOException, CertificateEncodingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { TBSCertificate certificate; try (ASN1InputStream input = new ASN1InputStream(x509certificate.getTBSCertificate())) { certificate = TBSCertificate.getInstance(input.readObject()); } AlgorithmIdentifier algorithmId = certificate.getSubjectPublicKeyInfo().getAlgorithm(); IssuerAndSerialNumber serial = new IssuerAndSerialNumber( certificate.getIssuer(), certificate.getSerialNumber().getValue()); Cipher cipher; try { cipher = Cipher.getInstance(algorithmId.getAlgorithm().getId(), SecurityProvider.getProvider()); } catch (NoSuchAlgorithmException | NoSuchPaddingException e) { // should never happen, if this happens throw IOException instead throw new RuntimeException("Could not find a suitable javax.crypto provider", e); } cipher.init(1, x509certificate.getPublicKey()); DEROctetString octets = new DEROctetString(cipher.doFinal(abyte0)); RecipientIdentifier recipientId = new RecipientIdentifier(serial); return new KeyTransRecipientInfo(recipientId, algorithmId, octets); }
private void readObject( ObjectInputStream in) throws IOException, ClassNotFoundException { byte[] enc = (byte[])in.readObject(); populateFromPubKeyInfo(SubjectPublicKeyInfo.getInstance(ASN1Primitive.fromByteArray(enc))); this.algorithm = (String)in.readObject(); this.withCompression = in.readBoolean(); }
private DERBitString getPublicKeyDetails(JCEECPublicKey pub) { try { SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(ASN1Primitive.fromByteArray(pub.getEncoded())); return info.getPublicKeyData(); } catch (IOException e) { // should never happen return null; } }
private void populateFromPubKeyInfo(SubjectPublicKeyInfo keyInfo) { if (EdECObjectIdentifiers.id_X448.equals(keyInfo.getAlgorithm().getAlgorithm())) { xdhPublicKey = new X448PublicKeyParameters(keyInfo.getPublicKeyData().getOctets(), 0); } else { xdhPublicKey = new X25519PublicKeyParameters(keyInfo.getPublicKeyData().getOctets(), 0); } }