List of usage examples for java.security PublicKey getEncoded
public byte[] getEncoded();
From source file:net.sourceforge.msscodefactory.cflib.v2_1.CFLib.Tip.CFTipEnvelopeHandler.java
public byte[] getEncodedServerPublicKey() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException { final String S_ProcName = "getEncodedServerPublicKey"; if (serverKeyPair == null) { throw CFLib.getDefaultExceptionFactory().newUsageException(getClass(), S_ProcName, "Server key must be initialized by initServerKeys()"); }/*from w w w . j a v a 2 s . c om*/ PublicKey pk = serverKeyPair.getPublic(); if (pk == null) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "serverKeyPair.getPublic()"); } byte encoded[] = pk.getEncoded(); return (encoded); }
From source file:org.apache.hc.client5.http.impl.auth.CredSspScheme.java
private byte[] getSubjectPublicKeyDer(final PublicKey publicKey) throws AuthenticationException { // The publicKey.getEncoded() returns encoded SubjectPublicKeyInfo structure. But the CredSSP expects // SubjectPublicKey subfield. I have found no easy way how to get just the SubjectPublicKey from // java.security libraries. So let's use a primitive way and parse it out from the DER. try {/*from w w w .j a v a 2 s .c o m*/ final byte[] encodedPubKeyInfo = publicKey.getEncoded(); final ByteBuffer buf = ByteBuffer.wrap(encodedPubKeyInfo); getByteAndAssert(buf, 0x30, "initial sequence"); parseLength(buf); getByteAndAssert(buf, 0x30, "AlgorithmIdentifier sequence"); final int algIdSeqLength = parseLength(buf); buf.position(buf.position() + algIdSeqLength); getByteAndAssert(buf, 0x03, "subjectPublicKey type"); int subjectPublicKeyLegth = parseLength(buf); // There may be leading padding byte ... or whatever that is. Skip that. final byte b = buf.get(); if (b == 0) { subjectPublicKeyLegth--; } else { buf.position(buf.position() - 1); } final byte[] subjectPublicKey = new byte[subjectPublicKeyLegth]; buf.get(subjectPublicKey); return subjectPublicKey; } catch (final MalformedChallengeException e) { throw new AuthenticationException(e.getMessage(), e); } }
From source file:com.netscape.cmsutil.crypto.CryptoUtil.java
public static List<byte[]> exportSharedSecret(String nickname, java.security.cert.X509Certificate wrappingCert, SymmetricKey wrappingKey) throws Exception { CryptoManager cm = CryptoManager.getInstance(); CryptoToken token = cm.getInternalKeyStorageToken(); List<byte[]> listWrappedKeys = new ArrayList<byte[]>(); KeyManager km = new KeyManager(token); if (!km.uniqueNamedKeyExists(nickname)) { throw new IOException("Shared secret " + nickname + " does not exist"); }// w w w. j a v a2s . com SymmetricKey sharedSecretKey = null; try { sharedSecretKey = getSymKeyByName(token, nickname); } catch (Exception e) { sharedSecretKey = null; } if (sharedSecretKey == null) { throw new IOException("Shared secret " + nickname + " does not exist"); } PublicKey pub = wrappingCert.getPublicKey(); PK11PubKey pubK = PK11PubKey.fromSPKI(pub.getEncoded()); //Wrap the temp DES3 key with the cert byte[] wrappedKey = wrapUsingPublicKey(token, pubK, wrappingKey, KeyWrapAlgorithm.RSA); listWrappedKeys.add(wrappedKey); //Use the DES3 key to wrap the shared secret byte[] wrappedSharedSecret = wrapUsingSymmetricKey(token, wrappingKey, sharedSecretKey, null, KeyWrapAlgorithm.DES3_ECB); listWrappedKeys.add(wrappedSharedSecret); if (listWrappedKeys.size() != 2) { throw new IOException("Can't write out shared secret data to export for nickname: " + nickname); } return listWrappedKeys; }
From source file:edu.stanford.mobisocial.dungbeetle.DBHelper.java
private void generateAndStorePersonalInfo(SQLiteDatabase db) { String email = getUserEmail(); String name = email; // How to get this? KeyPair keypair = DBIdentityProvider.generateKeyPair(); PrivateKey privateKey = keypair.getPrivate(); PublicKey publicKey = keypair.getPublic(); String pubKeyStr = FastBase64.encodeToString(publicKey.getEncoded()); String privKeyStr = FastBase64.encodeToString(privateKey.getEncoded()); ContentValues cv = new ContentValues(); cv.put(MyInfo.PUBLIC_KEY, pubKeyStr); cv.put(MyInfo.PRIVATE_KEY, privKeyStr); cv.put(MyInfo.NAME, name);//from ww w .j av a 2 s.c o m cv.put(MyInfo.EMAIL, email); db.insertOrThrow(MyInfo.TABLE, null, cv); Log.d(TAG, "Generated public key: " + pubKeyStr); Log.d(TAG, "Generated priv key: **************"); }
From source file:edu.stanford.mobisocial.dungbeetle.DBHelper.java
long insertContact(SQLiteDatabase db, ContentValues cv) { try {/*from w ww .j av a2 s . c om*/ Log.i(TAG, "Inserting contact: " + cv); String pubKeyStr = cv.getAsString(Contact.PUBLIC_KEY); assert (pubKeyStr != null) && pubKeyStr.length() > 0; PublicKey key = RSACrypto.publicKeyFromString(pubKeyStr); cv.put(Contact.PUBLIC_KEY_HASH_64, hashPublicKey(key.getEncoded())); String tag = edu.stanford.mobisocial.bumblebee.util.Util.makePersonIdForPublicKey(key); cv.put(Contact.PERSON_ID, tag); String name = cv.getAsString(Contact.NAME); assert (name != null) && name.length() > 0; return getWritableDatabase().insertOrThrow(Contact.TABLE, null, cv); } catch (Exception e) { Log.e(TAG, e.getMessage(), e); return -1; } }
From source file:com.netscape.cmsutil.crypto.CryptoUtil.java
public static X509Key convertPublicKeyToX509Key(PublicKey pubk) throws InvalidKeyException { X509Key xKey;/*w w w. ja va 2 s .co m*/ if (pubk instanceof RSAPublicKey) { RSAPublicKey rsaKey = (RSAPublicKey) pubk; xKey = new netscape.security.provider.RSAPublicKey(new BigInt(rsaKey.getModulus()), new BigInt(rsaKey.getPublicExponent())); } else if (pubk instanceof PK11ECPublicKey) { byte encoded[] = pubk.getEncoded(); xKey = CryptoUtil.getPublicX509ECCKey(encoded); } else { // Assert.assert(pubk instanceof DSAPublicKey); DSAPublicKey dsaKey = (DSAPublicKey) pubk; DSAParams params = dsaKey.getParams(); xKey = new netscape.security.provider.DSAPublicKey(dsaKey.getY(), params.getP(), params.getQ(), params.getG()); } return xKey; }
From source file:eu.dety.burp.joseph.attacks.key_confusion.KeyConfusionInfo.java
@Override public KeyConfusion prepareAttack(IBurpExtenderCallbacks callbacks, IHttpRequestResponse requestResponse, IRequestInfo requestInfo, JoseParameter parameter) throws AttackPreparationFailedException { this.requestResponse = requestResponse; this.parameter = parameter; this.publicKeyVariations.clear(); this.requests.clear(); String publicKeyValue = publicKey.getText(); // Throw error if public key value is empty if (publicKeyValue.isEmpty()) { throw new AttackPreparationFailedException(bundle.getString("PROVIDE_PUBKEY")); }/* w w w .j av a2 s . c o m*/ // Parse public key according to selected format int publicKeyFormat = publicKeySelection.getSelectedIndex(); switch (publicKeyFormat) { // JWK (JSON) case 1: // TODO: Refactor to test every key at once? Requires change of HashMap key loggerInstance.log(getClass(), "Key format is JWK: " + publicKeyValue, Logger.LogLevel.DEBUG); HashMap<String, PublicKey> publicKeys; PublicKey selectedPublicKey; try { Object publickKeyValueJson = new JSONParser().parse(publicKeyValue); publicKeys = Converter.getRsaPublicKeysByJwkWithId(publickKeyValueJson); } catch (Exception e) { loggerInstance.log(getClass(), "Error in prepareAttack (JWK): " + e.getMessage(), Logger.LogLevel.ERROR); throw new AttackPreparationFailedException(bundle.getString("NOT_VALID_JWK")); } switch (publicKeys.size()) { // No suitable JWK in JWK Set found case 0: loggerInstance.log(getClass(), "Error in prepareAttack (JWK): No suitable JWK", Logger.LogLevel.ERROR); throw new AttackPreparationFailedException(bundle.getString("NO_SUITABLE_JWK")); // Exactly one suitable JWK found case 1: selectedPublicKey = publicKeys.entrySet().iterator().next().getValue(); break; // More than one suitable JWK found. Provide dialog to select one. default: selectedPublicKey = Converter.getRsaPublicKeyByJwkSelectionPanel(publicKeys); } try { loggerInstance.log(getClass(), "Encoded PubKey: " + Base64.encodeBase64String(selectedPublicKey.getEncoded()) + "\nFormat: " + selectedPublicKey.getFormat(), Logger.LogLevel.DEBUG); // PKCS#8 / X.509 publicKeyVariations.put(PayloadType.PKCS8, transformKeyByPayload(PayloadType.PKCS8, selectedPublicKey)); // With header/footer publicKeyVariations.put(PayloadType.PKCS8_WITH_HEADER_FOOTER, transformKeyByPayload(PayloadType.PKCS8_WITH_HEADER_FOOTER, selectedPublicKey)); // With line feeds publicKeyVariations.put(PayloadType.PKCS8_WITH_LF, transformKeyByPayload(PayloadType.PKCS8_WITH_LF, selectedPublicKey)); // With line feeds and header/footer publicKeyVariations.put(PayloadType.PKCS8_WITH_HEADER_FOOTER_LF, transformKeyByPayload(PayloadType.PKCS8_WITH_HEADER_FOOTER_LF, selectedPublicKey)); // With line feeds and header/footer and additional line feed at end publicKeyVariations.put(PayloadType.PKCS8_WITH_HEADER_FOOTER_LF_ENDING_LF, transformKeyByPayload( PayloadType.PKCS8_WITH_HEADER_FOOTER_LF_ENDING_LF, selectedPublicKey)); } catch (Exception e) { throw new AttackPreparationFailedException(bundle.getString("NOT_VALID_JWK")); } break; // PEM (String) default: loggerInstance.log(getClass(), "Key format is PEM: " + publicKeyValue, Logger.LogLevel.DEBUG); // Simple check if String has valid format if (!publicKeyValue.trim().startsWith("-----BEGIN") && !publicKeyValue.trim().startsWith("MI")) { throw new AttackPreparationFailedException(bundle.getString("NOT_VALID_PEM")); } try { // No modification publicKeyVariations.put(PayloadType.ORIGINAL, publicKeyValue); // Without header/footer publicKeyVariations.put(PayloadType.ORIGINAL_NO_HEADER_FOOTER, transformKeyByPayload(PayloadType.ORIGINAL_NO_HEADER_FOOTER, publicKeyValue)); // Without line feeds/carriage returns publicKeyVariations.put(PayloadType.ORIGINAL_NO_LF, transformKeyByPayload(PayloadType.ORIGINAL_NO_LF, publicKeyValue)); // Without header/footer and line feeds/carriage returns publicKeyVariations.put(PayloadType.ORIGINAL_NO_HEADER_FOOTER_LF, transformKeyByPayload(PayloadType.ORIGINAL_NO_HEADER_FOOTER_LF, publicKeyValue)); publicKeyVariations.put(PayloadType.ORIGINAL_ADDITIONAL_LF, transformKeyByPayload(PayloadType.ORIGINAL_ADDITIONAL_LF, publicKeyValue)); // PKCS#1, easy but hacky transformation publicKeyVariations.put(PayloadType.PKCS1, transformKeyByPayload(PayloadType.PKCS1, publicKeyValue)); // PKCS#1 without header/footer publicKeyVariations.put(PayloadType.PKCS1_NO_HEADER_FOOTER, transformKeyByPayload(PayloadType.PKCS1_NO_HEADER_FOOTER, publicKeyValue)); // PKCS#1 without line feeds/carriage returns publicKeyVariations.put(PayloadType.PKCS1_NO_LF, transformKeyByPayload(PayloadType.PKCS1_NO_LF, publicKeyValue)); // PKCS#1 without header/footer and line feeds/carriage // returns publicKeyVariations.put(PayloadType.PKCS1_NO_HEADER_FOOTER_LF, transformKeyByPayload(PayloadType.PKCS1_NO_HEADER_FOOTER_LF, publicKeyValue)); } catch (Exception e) { throw new AttackPreparationFailedException(bundle.getString("NOT_VALID_PEM")); } break; } for (Map.Entry<PayloadType, String> publicKey : publicKeyVariations.entrySet()) { for (String algorithm : algorithms) { try { // Change the "alg" header value for each of the algorithms // entries String[] components = Decoder.getComponents(this.parameter.getJoseValue()); String decodedHeader = Decoder.getDecoded(components[0]); String decodedHeaderReplacedAlgorithm = decodedHeader.replaceFirst("\"alg\":\"(.+?)\"", "\"alg\":\"" + algorithm + "\""); String encodedHeaderReplacedAlgorithm = Decoder.getEncoded(decodedHeaderReplacedAlgorithm); String macAlg = Crypto.getMacAlgorithmByJoseAlgorithm(algorithm, "HmacSHA256"); // Generate signature String newSignature = Decoder .getEncoded(Crypto.generateMac(macAlg, helpers.stringToBytes(publicKey.getValue()), helpers.stringToBytes(Decoder.concatComponents( new String[] { encodedHeaderReplacedAlgorithm, components[1] })))); // Build new JWS String and update parameter String[] newComponents = { encodedHeaderReplacedAlgorithm, components[1], newSignature }; String newComponentsConcatenated = Decoder.concatComponents(newComponents); byte[] tmpRequest = JoseParameter.updateRequest(this.requestResponse.getRequest(), this.parameter, helpers, newComponentsConcatenated); requests.add(new KeyConfusionAttackRequest(tmpRequest, publicKey.getKey().ordinal(), algorithm, publicKey.getValue(), publicKey.getValue().length())); } catch (Exception e) { throw new AttackPreparationFailedException( "Attack preparation failed. Message: " + e.getMessage()); } } } this.amountRequests = requests.size(); return new KeyConfusion(callbacks, this); }
From source file:org.texai.x509.X509Utils.java
/** Generates an intermediate CA certificate, that is to be used to sign end-use certificates. * * @param myPublicKey the public key for this certificate * @param issuerPrivateKey the issuer's private key * @param issuerCertificate the issuer's certificate, which is either the root CA certificate or another intermediate * CA certificate/*from ww w . j a va 2 s .c om*/ * @param pathLengthConstraint the maximum number of CA certificates that may follow this certificate in a certification * path. (Note: One end-entity certificate will follow the final CA certificate in the path. The last certificate in a path * is considered an end-entity certificate, whether the subject of the certificate is a CA or not.) * @return an intermediate CA certificate * * @throws CertificateParsingException when the certificate cannot be parsed * @throws CertificateEncodingException when the certificate cannot be encoded * @throws NoSuchProviderException when an invalid provider is given * @throws NoSuchAlgorithmException when an invalid algorithm is given * @throws SignatureException when the an invalid signature is present * @throws InvalidKeyException when the given key is invalid * @throws IOException if an input/output error occurs while processing the serial number file */ public static X509Certificate generateIntermediateX509Certificate(final PublicKey myPublicKey, final PrivateKey issuerPrivateKey, final X509Certificate issuerCertificate, int pathLengthConstraint) throws CertificateParsingException, CertificateEncodingException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException, IOException { //Preconditions assert myPublicKey != null : "myPublicKey must not be null"; assert issuerPrivateKey != null : "issuerPrivateKey must not be null"; assert issuerCertificate != null : "issuerCertificate must not be null"; //final X500Name issuer = new X500Name(issuerCertificate.getSubjectX500Principal().getName()); final X500Name issuer = new X500Name( StringUtils.reverseCommaDelimitedString(issuerCertificate.getSubjectX500Principal().getName())); final UUID intermediateUUID = UUID.randomUUID(); // provide items to X500Principal in reverse order final X500Principal x500Principal = new X500Principal( "UID=" + intermediateUUID + ", DC=IntermediateCertificate, CN=texai.org"); final X500Name subject = new X500Name(x500Principal.getName()); SubjectPublicKeyInfo publicKeyInfo = new SubjectPublicKeyInfo( ASN1Sequence.getInstance(myPublicKey.getEncoded())); final X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(issuer, getNextSerialNumber(), // serial new Date(System.currentTimeMillis() - 10000L), // notBefore, new Date(System.currentTimeMillis() + VALIDITY_PERIOD), // notAfter, subject, publicKeyInfo); // see http://www.ietf.org/rfc/rfc3280.txt // see http://stackoverflow.com/questions/20175447/creating-certificates-for-ssl-communication final JcaX509ExtensionUtils jcaX509ExtensionUtils = new JcaX509ExtensionUtils(); // Add authority key identifier x509v3CertificateBuilder.addExtension(Extension.authorityKeyIdentifier, false, // isCritical jcaX509ExtensionUtils.createAuthorityKeyIdentifier(issuerCertificate)); // Add subject key identifier x509v3CertificateBuilder.addExtension(Extension.subjectKeyIdentifier, false, // isCritical jcaX509ExtensionUtils.createSubjectKeyIdentifier(myPublicKey)); // add basic constraints x509v3CertificateBuilder.addExtension(Extension.basicConstraints, true, // isCritical new BasicConstraints(pathLengthConstraint)); // is a CA certificate with specified certification path length // add key usage final KeyUsage keyUsage = new KeyUsage( // the keyCertSign bit indicates that the subject public key may be used for verifying a signature on // certificates KeyUsage.keyCertSign | // the cRLSign indicates that the subject public key may be used for verifying a signature on revocation // information KeyUsage.cRLSign); x509v3CertificateBuilder.addExtension(Extension.keyUsage, true, // isCritical keyUsage); X509Certificate x509Certificate; try { final ContentSigner contentSigner = new JcaContentSignerBuilder(DIGITAL_SIGNATURE_ALGORITHM) .setProvider(BOUNCY_CASTLE_PROVIDER).build(issuerPrivateKey); final X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(contentSigner); final JcaX509CertificateConverter jcaX509CertificateConverter = new JcaX509CertificateConverter(); x509Certificate = makeCanonicalX509Certificate( jcaX509CertificateConverter.getCertificate(x509CertificateHolder)); } catch (CertificateException | OperatorCreationException ex) { throw new TexaiException(ex); } //Postconditions try { x509Certificate.checkValidity(); x509Certificate.verify(issuerCertificate.getPublicKey()); } catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException | SignatureException ex) { throw new TexaiException(ex); } return x509Certificate; }
From source file:org.texai.x509.X509Utils.java
/** Generates a signed end-use certificate that cannot be used to sign other certificates, but can be used for authentication * and for message signing.//from w w w .j ava 2 s.c om * * @param myPublicKey the public key for this certificate * @param issuerPrivateKey the issuer's private key * @param issuerCertificate the issuer's certificate * @param uid the subject UID * @param domainComponent the domain component, e.g. TexaiLauncher or NodeRuntime * @return a signed end-use certificate * * @throws CertificateParsingException when the certificate cannot be parsed * @throws CertificateEncodingException when the certificate cannot be encoded * @throws NoSuchProviderException when an invalid provider is given * @throws NoSuchAlgorithmException when an invalid algorithm is given * @throws SignatureException when the an invalid signature is present * @throws InvalidKeyException when the given key is invalid * @throws IOException if an input/output error occurs while processing the serial number file */ public static X509Certificate generateX509Certificate(final PublicKey myPublicKey, final PrivateKey issuerPrivateKey, final X509Certificate issuerCertificate, final UUID uid, final String domainComponent) throws CertificateParsingException, CertificateEncodingException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException, IOException { //Preconditions assert myPublicKey != null : "myPublicKey must not be null"; assert issuerPrivateKey != null : "issuerPrivateKey must not be null"; assert issuerCertificate != null : "issuerCertificate must not be null"; assert uid != null : "uid must not be null"; final String x500PrincipalString; // provide items to X500Principal in reverse order if (domainComponent == null || domainComponent.isEmpty()) { x500PrincipalString = "UID=" + uid + ", CN=texai.org"; } else { x500PrincipalString = "UID=" + uid + ", DC=" + domainComponent + " ,CN=texai.org"; } final X500Principal x500Principal = new X500Principal(x500PrincipalString); LOGGER.info("issuer: " + issuerCertificate.getIssuerX500Principal().getName()); final X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder( new X500Name(StringUtils .reverseCommaDelimitedString(issuerCertificate.getSubjectX500Principal().getName())), // issuer, getNextSerialNumber(), // serial new Date(System.currentTimeMillis() - 10000L), // notBefore, new Date(System.currentTimeMillis() + VALIDITY_PERIOD), // notAfter, new X500Name(x500Principal.getName()), // subject, new SubjectPublicKeyInfo(ASN1Sequence.getInstance(myPublicKey.getEncoded()))); // publicKeyInfo // see http://www.ietf.org/rfc/rfc3280.txt // see http://stackoverflow.com/questions/20175447/creating-certificates-for-ssl-communication final JcaX509ExtensionUtils jcaX509ExtensionUtils = new JcaX509ExtensionUtils(); // Add authority key identifier x509v3CertificateBuilder.addExtension(Extension.authorityKeyIdentifier, false, // isCritical jcaX509ExtensionUtils.createAuthorityKeyIdentifier(issuerCertificate)); // Add subject key identifier x509v3CertificateBuilder.addExtension(Extension.subjectKeyIdentifier, false, // isCritical jcaX509ExtensionUtils.createSubjectKeyIdentifier(myPublicKey)); // add basic constraints x509v3CertificateBuilder.addExtension(Extension.basicConstraints, true, // isCritical new BasicConstraints(false)); // is not a CA certificate // add key usage final KeyUsage keyUsage = new KeyUsage( // the digitalSignature usage indicates that the subject public key may be used with a digital signature // mechanism to support security services other than non-repudiation, certificate signing, or revocation // information signing KeyUsage.digitalSignature | // the nonRepudiation usage indicates that the subject public key may be used to verify digital signatures // used to provide a non-repudiation service which protects against the signing entity falsely denying some // action, excluding certificate or CRL signing KeyUsage.nonRepudiation | // the keyEncipherment usage indicates that the subject public key may be used for key transport, e.g. the // exchange of efficient symmetric keys in SSL KeyUsage.keyEncipherment | // the dataEncipherment usage indicates that the subject public key may be used for enciphering user data, // other than cryptographic keys KeyUsage.dataEncipherment | // the keyAgreement usage indicates that the subject public key may be used for key agreement, e.g. when a // Diffie-Hellman key is to be used for key management KeyUsage.keyAgreement | // the keyCertSign bit indicates that the subject public key may be used for verifying a signature on // certificates KeyUsage.keyCertSign | // the cRLSign indicates that the subject public key may be used for verifying a signature on revocation // information KeyUsage.cRLSign | // see http://www.docjar.com/html/api/sun/security/validator/EndEntityChecker.java.html - bit 0 needs to set for SSL // client authorization KeyUsage.encipherOnly); x509v3CertificateBuilder.addExtension(Extension.keyUsage, true, // isCritical keyUsage); X509Certificate x509Certificate; try { final ContentSigner contentSigner = new JcaContentSignerBuilder(DIGITAL_SIGNATURE_ALGORITHM) .setProvider(BOUNCY_CASTLE_PROVIDER).build(issuerPrivateKey); final X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(contentSigner); final JcaX509CertificateConverter jcaX509CertificateConverter = new JcaX509CertificateConverter(); x509Certificate = makeCanonicalX509Certificate( jcaX509CertificateConverter.getCertificate(x509CertificateHolder)); } catch (CertificateException | OperatorCreationException ex) { throw new TexaiException(ex); } //Postconditions try { x509Certificate.checkValidity(); x509Certificate.verify(issuerCertificate.getPublicKey()); } catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException | SignatureException ex) { throw new TexaiException(ex); } assert x509Certificate.getKeyUsage()[0] : "must have digital signature key usage"; return x509Certificate; }
From source file:org.cesecore.util.CertTools.java
/** * Generates a PKCS10CertificationRequest * /*from w w w .ja v a 2 s.co m*/ * Code Example: * ------------- * An example of putting AltName and a password challenge in an 'attributes' set (taken from RequestMessageTest.test01Pkcs10RequestMessage() ): * * {@code * // Create a P10 with extensions, in this case altNames with a DNS name * ASN1EncodableVector altnameattr = new ASN1EncodableVector(); * altnameattr.add(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest); * // AltNames * GeneralNames san = CertTools.getGeneralNamesFromAltName("dNSName=foo1.bar.com"); * ExtensionsGenerator extgen = new ExtensionsGenerator(); * extgen.addExtension(Extension.subjectAlternativeName, false, san ); * Extensions exts = extgen.generate(); * altnameattr.add(new DERSet(exts)); * * // Add a challenge password as well * ASN1EncodableVector pwdattr = new ASN1EncodableVector(); * pwdattr.add(PKCSObjectIdentifiers.pkcs_9_at_challengePassword); * ASN1EncodableVector pwdvalues = new ASN1EncodableVector(); * pwdvalues.add(new DERUTF8String("foo123")); * pwdattr.add(new DERSet(pwdvalues)); * * // Complete the Attribute section of the request, the set (Attributes) * // contains one sequence (Attribute) * ASN1EncodableVector v = new ASN1EncodableVector(); * v.add(new DERSequence(altnameattr)); * v.add(new DERSequence(pwdattr)); * DERSet attributes = new DERSet(v); * } * * @param signatureAlgorithm * @param subject The request's subjectDN * @param publickey the public key for the certificate requesting signing * @param attributes A set of attributes, for example, extensions, challenge password, etc. * @param privateKey the private key used to generate the certificate * @param provider * @return a PKCS10CertificateRequest based on the input parameters. * * @throws OperatorCreationException if an error occurred while creating the signing key */ public static PKCS10CertificationRequest genPKCS10CertificationRequest(String signatureAlgorithm, X500Name subject, PublicKey publickey, ASN1Set attributes, PrivateKey privateKey, String provider) throws OperatorCreationException { ContentSigner signer; CertificationRequestInfo reqInfo; try { ASN1Sequence seq = (ASN1Sequence) ASN1Primitive.fromByteArray(publickey.getEncoded()); SubjectPublicKeyInfo pkinfo = new SubjectPublicKeyInfo(seq); reqInfo = new CertificationRequestInfo(subject, pkinfo, attributes); if (provider == null) { provider = BouncyCastleProvider.PROVIDER_NAME; } signer = new BufferingContentSigner( new JcaContentSignerBuilder(signatureAlgorithm).setProvider(provider).build(privateKey), 20480); signer.getOutputStream().write(reqInfo.getEncoded(ASN1Encoding.DER)); signer.getOutputStream().flush(); } catch (IOException e) { throw new IllegalStateException("Unexpected IOException was caught.", e); } byte[] sig = signer.getSignature(); DERBitString sigBits = new DERBitString(sig); CertificationRequest req = new CertificationRequest(reqInfo, signer.getAlgorithmIdentifier(), sigBits); return new PKCS10CertificationRequest(req); }