List of usage examples for org.bouncycastle.asn1.x509 SubjectPublicKeyInfo getEncoded
public byte[] getEncoded() throws IOException
From source file:COSE.ECPublicKey.java
public ECPublicKey(OneKey oneKey) throws CoseException, IOException { X9ECParameters p = oneKey.GetCurve(); byte[] rgbKey; byte[] X = oneKey.get(KeyKeys.EC2_X).GetByteString(); if (oneKey.get(KeyKeys.EC2_Y).getType() == CBORType.Boolean) { rgbKey = new byte[X.length + 1]; System.arraycopy(X, 0, rgbKey, 1, X.length); rgbKey[0] = (byte) (2 + (oneKey.get(KeyKeys.EC2_Y).AsBoolean() ? 1 : 0)); org.bouncycastle.math.ec.ECPoint pubPoint; pubPoint = p.getCurve().decodePoint(rgbKey); point = new ECPoint(point.getAffineX(), point.getAffineY()); } else {/*from w ww .ja v a 2 s .co m*/ rgbKey = new byte[X.length * 2 + 1]; System.arraycopy(X, 0, rgbKey, 1, X.length); byte[] Y = oneKey.get(KeyKeys.EC2_Y).GetByteString(); System.arraycopy(Y, 0, rgbKey, 1 + X.length, X.length); rgbKey[0] = 4; point = new ECPoint(new BigInteger(1, X), new BigInteger(1, oneKey.get(KeyKeys.EC2_Y).GetByteString())); } /* switch (AlgorithmID.FromCBOR(oneKey.get(KeyKeys.Algorithm))) { case ECDH_ES_HKDF_256: case ECDH_ES_HKDF_512: case ECDH_SS_HKDF_256: case ECDH_SS_HKDF_512: case ECDH_ES_HKDF_256_AES_KW_128: case ECDH_ES_HKDF_256_AES_KW_192: case ECDH_ES_HKDF_256_AES_KW_256: case ECDH_SS_HKDF_256_AES_KW_128: case ECDH_SS_HKDF_256_AES_KW_192: case ECDH_SS_HKDF_256_AES_KW_256: algorithm = "ECDH"; break; case ECDSA_256: algorithm = "SHA256withECDSA"; break; case ECDSA_384: algorithm = "SHA384withECDSA"; break; case ECDSA_512: algorithm = "SHA512withECDSA"; break; default: throw new CoseException("No algorithm specified"); } */ algorithm = "EC"; // This seems wrong to me asit returns the KeyFactory name and // there is no distinction between ECDH and ECDSA while there // is for DSA vs DiffieHellman. CBORObject curve = oneKey.get(KeyKeys.EC2_Curve); ASN1ObjectIdentifier curveOID; if (curve.equals(KeyKeys.EC2_P256)) { curveOID = org.bouncycastle.asn1.sec.SECObjectIdentifiers.secp256r1; } else if (curve.equals(KeyKeys.EC2_P384)) { curveOID = org.bouncycastle.asn1.sec.SECObjectIdentifiers.secp384r1; } else if (curve.equals(KeyKeys.EC2_P521)) { curveOID = org.bouncycastle.asn1.sec.SECObjectIdentifiers.secp521r1; } else { throw new CoseException("Unrecognized Curve"); } ECField field = new ECFieldFp(p.getCurve().getField().getCharacteristic()); EllipticCurve crv = new EllipticCurve(field, p.getCurve().getA().toBigInteger(), p.getCurve().getB().toBigInteger()); ECPoint pt = new ECPoint(p.getG().getRawXCoord().toBigInteger(), p.getG().getRawYCoord().toBigInteger()); ecParameterSpec = new ECParameterSpec(crv, pt, p.getN(), p.getH().intValue()); AlgorithmIdentifier alg = new AlgorithmIdentifier(org.bouncycastle.asn1.x9.X9Curve.id_ecPublicKey, curveOID); SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo(alg, rgbKey); spkiEncoded = spki.getEncoded(); }
From source file:edu.wisc.doit.tcrypt.AbstractPublicKeyEncrypter.java
License:Apache License
/** * Create an encrypter using the specified public key * // w w w .j a v a 2 s . co m * @param keyPair The public key to use */ public AbstractPublicKeyEncrypter(SubjectPublicKeyInfo publicKey) throws IOException { this(PublicKeyFactory.createKey(publicKey.getEncoded())); }
From source file:net.ripe.rpki.commons.crypto.x509cert.X509CertificateUtil.java
License:BSD License
/** * Get a base 64-encoded, DER-encoded X.509 subjectPublicKeyInfo as used for the Trust Anchor Locator (TAL) * * @throws X509CertificateOperationException * * @throws IOException/*from w w w .j av a 2s.c o m*/ */ public static String getEncodedSubjectPublicKeyInfo(X509Certificate certificate) { byte[] tbsCertificate; try { tbsCertificate = certificate.getTBSCertificate(); } catch (CertificateEncodingException e) { throw new X509CertificateOperationException("Can't extract TBSCertificate from certificate", e); } ASN1Sequence tbsCertificateSequence = (ASN1Sequence) Asn1Util.decode(tbsCertificate); TBSCertificateStructure tbsCertificateStructure = new TBSCertificateStructure(tbsCertificateSequence); SubjectPublicKeyInfo subjectPublicKeyInfo = tbsCertificateStructure.getSubjectPublicKeyInfo(); try { byte[] data = subjectPublicKeyInfo.getEncoded(); Base64Encoder encoder = new Base64Encoder(); ByteArrayOutputStream out = new ByteArrayOutputStream(); encoder.encode(data, 0, data.length, out); out.flush(); return out.toString(); } catch (IOException e) { throw new X509CertificateOperationException("Can't encode SubjectPublicKeyInfo for certificate", e); } }
From source file:no.digipost.api.client.util.DigipostPublicKey.java
License:Apache License
public DigipostPublicKey(EncryptionKey encryptionKey) { try (Reader sourceReader = new StringReader(encryptionKey.getValue()); PEMParser pemParser = new PEMParser(sourceReader)) { SubjectPublicKeyInfo subjectPublicKeyInfo = (SubjectPublicKeyInfo) pemParser.readObject(); X509EncodedKeySpec spec = new X509EncodedKeySpec(subjectPublicKeyInfo.getEncoded()); PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(spec); this.publicKey = publicKey; this.publicKeyHash = encryptionKey.getKeyId(); } catch (Exception e) { throw new DigipostClientException(ErrorCode.FAILED_TO_PARSE_ENCRYPTION_KEY, "Feil ved parsing av krypteringsnkkel fra Digipost.", e); }/*from w w w . j a v a 2s . c o m*/ }
From source file:org.albertschmitt.crypto.RSAService.java
License:Open Source License
/** * Read the RSA Public Key from the specified input stream. * * @param instream//ww w . j ava 2 s. c om * The input stream that contains the RSA Public Key. * @return The RSAPublicKey. * @throws java.io.IOException */ public RSAPublicKey readPublicKey(InputStream instream) throws IOException { SubjectPublicKeyInfo pki; try (InputStreamReader reader = new InputStreamReader(instream)) { try (PEMParser pem = new PEMParser(reader)) { pki = (SubjectPublicKeyInfo) pem.readObject(); } } byte[] data = pki.getEncoded(); RSAPublicKey key = new RSAPublicKey(); key.setKey(PublicKeyFactory.createKey(data)); return key; }
From source file:org.albertschmitt.crypto.RSAService.java
License:Open Source License
/** * Extract the Public Key from the RSA Private Key from the input stream and return it to the client. * * @param instream//w ww . ja v a 2s . c om * The input stream that contains the RSA Private Key. * @return The RSAPublicKey. * @throws java.io.IOException */ public RSAPublicKey readPublicKeyFromPrivate(InputStream instream) throws IOException { org.bouncycastle.openssl.PEMKeyPair pkp; try (InputStreamReader reader = new InputStreamReader(instream)) { try (PEMParser pem = new PEMParser(reader)) { pkp = (PEMKeyPair) pem.readObject(); } } SubjectPublicKeyInfo pki = pkp.getPublicKeyInfo(); byte[] data = pki.getEncoded(); RSAPublicKey key = new RSAPublicKey(); key.setKey(PublicKeyFactory.createKey(data)); return key; }
From source file:org.albertschmitt.crypto.RSAService.java
License:Open Source License
/** * Write the RSAPublicKey to a stream in DER format. * * @param outstream//from www . ja va2s . c om * the stream the DER key is to be written to. * @param key * the RSAPublicKey. * @throws IOException */ public void writeDERKey(OutputStream outstream, RSAPublicKey key) throws IOException { AsymmetricKeyParameter keyParam = key.getKey(); SubjectPublicKeyInfo pki = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(keyParam); byte[] keybytes = pki.getEncoded(); outstream.write(keybytes); outstream.close(); }
From source file:org.cesecore.certificates.certificate.request.RequestMessageUtils.java
License:Open Source License
public static RequestMessage getSimpleRequestMessageFromType(final String username, final String password, final String req, final int reqType) throws SignRequestSignatureException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, IOException, SignatureException, InvalidKeySpecException, ParseException, ConstructionException, NoSuchFieldException { RequestMessage ret = null;/*from w w w.ja va 2 s . c o m*/ if (reqType == CertificateConstants.CERT_REQ_TYPE_PKCS10) { final RequestMessage pkcs10req = RequestMessageUtils.genPKCS10RequestMessage(req.getBytes()); final PublicKey pubKey = pkcs10req.getRequestPublicKey(); SimpleRequestMessage simplereq = new SimpleRequestMessage(pubKey, username, password); final Extensions ext = pkcs10req.getRequestExtensions(); simplereq.setRequestExtensions(ext); ret = simplereq; } else if (reqType == CertificateConstants.CERT_REQ_TYPE_SPKAC) { byte[] reqBytes = req.getBytes(); if (reqBytes != null) { if (log.isDebugEnabled()) { log.debug("Received NS request: " + new String(reqBytes)); } byte[] buffer = Base64.decode(reqBytes); if (buffer == null) { return null; } ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(buffer)); ASN1Sequence spkacSeq = (ASN1Sequence) in.readObject(); in.close(); NetscapeCertRequest nscr = new NetscapeCertRequest(spkacSeq); // Verify POPO, we don't care about the challenge, it's not important. nscr.setChallenge("challenge"); if (nscr.verify("challenge") == false) { if (log.isDebugEnabled()) { log.debug("SPKAC POPO verification Failed"); } throw new SignRequestSignatureException( "Invalid signature in NetscapeCertRequest, popo-verification failed."); } if (log.isDebugEnabled()) { log.debug("POPO verification successful"); } PublicKey pubKey = nscr.getPublicKey(); ret = new SimpleRequestMessage(pubKey, username, password); } } else if (reqType == CertificateConstants.CERT_REQ_TYPE_CRMF) { byte[] request = Base64.decode(req.getBytes()); ASN1InputStream in = new ASN1InputStream(request); try { ASN1Sequence crmfSeq = (ASN1Sequence) in.readObject(); ASN1Sequence reqSeq = (ASN1Sequence) ((ASN1Sequence) crmfSeq.getObjectAt(0)).getObjectAt(0); CertRequest certReq = CertRequest.getInstance(reqSeq); SubjectPublicKeyInfo pKeyInfo = certReq.getCertTemplate().getPublicKey(); KeyFactory keyFact = KeyFactory.getInstance("RSA", "BC"); KeySpec keySpec = new X509EncodedKeySpec(pKeyInfo.getEncoded()); PublicKey pubKey = keyFact.generatePublic(keySpec); // just check it's ok SimpleRequestMessage simplereq = new SimpleRequestMessage(pubKey, username, password); Extensions ext = certReq.getCertTemplate().getExtensions(); simplereq.setRequestExtensions(ext); ret = simplereq; } finally { in.close(); } // a simple crmf is not a complete PKI message, as desired by the CrmfRequestMessage class //PKIMessage msg = PKIMessage.getInstance(new ASN1InputStream(new ByteArrayInputStream(request)).readObject()); //CrmfRequestMessage reqmsg = new CrmfRequestMessage(msg, null, true, null); //imsg = reqmsg; } else if (reqType == CertificateConstants.CERT_REQ_TYPE_PUBLICKEY) { byte[] request; // Request can be Base64 encoded or in PEM format try { request = FileTools.getBytesFromPEM(req.getBytes(), CertTools.BEGIN_PUBLIC_KEY, CertTools.END_PUBLIC_KEY); } catch (IOException ex) { try { request = Base64.decode(req.getBytes()); if (request == null) { throw new IOException("Base64 decode of buffer returns null"); } } catch (DecoderException de) { throw new IOException("Base64 decode fails, message not base64 encoded: " + de.getMessage()); } } final PublicKey pubKey = KeyTools.getPublicKeyFromBytes(request); ret = new SimpleRequestMessage(pubKey, username, password); } else if (reqType == CertificateConstants.CERT_REQ_TYPE_CVC) { CVCObject parsedObject = CertificateParser.parseCVCObject(Base64.decode(req.getBytes())); // We will handle both the case if the request is an authenticated request, i.e. with an outer signature // and when the request is missing the (optional) outer signature. CVCertificate cvccert = null; if (parsedObject instanceof CVCAuthenticatedRequest) { CVCAuthenticatedRequest cvcreq = (CVCAuthenticatedRequest) parsedObject; cvccert = cvcreq.getRequest(); } else { cvccert = (CVCertificate) parsedObject; } CVCRequestMessage reqmsg = new CVCRequestMessage(cvccert.getDEREncoded()); reqmsg.setUsername(username); reqmsg.setPassword(password); // Popo is really actually verified by the CA (in SignSessionBean) as well if (reqmsg.verify() == false) { if (log.isDebugEnabled()) { log.debug("CVC POPO verification Failed"); } throw new SignRequestSignatureException( "Invalid inner signature in CVCRequest, popo-verification failed."); } else { if (log.isDebugEnabled()) { log.debug("POPO verification successful"); } } ret = reqmsg; } return ret; }
From source file:org.ebayopensource.fido.uaf.crypto.KeyCodec.java
License:Apache License
public static PublicKey getRSAPublicKey(byte[] encodedPubKey) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { RSAPublicKey pubKey8 = RSAPublicKey.getInstance(encodedPubKey); SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo( new RSAKeyParameters(false, pubKey8.getModulus(), pubKey8.getPublicExponent())); X509EncodedKeySpec spec = new X509EncodedKeySpec(info.getEncoded()); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePublic(spec); }
From source file:org.ejbca.core.ejb.ra.CertificateRequestSessionBean.java
License:Open Source License
@Override public byte[] processCertReq(Admin admin, UserDataVO userdata, String req, int reqType, String hardTokenSN, int responseType) throws CADoesntExistsException, AuthorizationDeniedException, NotFoundException, InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException, SignatureException, IOException, ObjectNotFoundException, CertificateException, UserDoesntFullfillEndEntityProfile, ApprovalException, EjbcaException { byte[] retval = null; // Check tokentype if (userdata.getTokenType() != SecConst.TOKEN_SOFT_BROWSERGEN) { throw new WrongTokenTypeException( "Error: Wrong Token Type of user, must be 'USERGENERATED' for PKCS10/SPKAC/CRMF/CVC requests"); }/* w w w . j ava 2 s .com*/ // This is the secret sauce, do the end entity handling automagically here before we get the cert addOrEditUser(admin, userdata, false, true); // Process request try { String password = userdata.getPassword(); String username = userdata.getUsername(); IRequestMessage imsg = null; if (reqType == SecConst.CERT_REQ_TYPE_PKCS10) { IRequestMessage pkcs10req = RequestMessageUtils.genPKCS10RequestMessage(req.getBytes()); PublicKey pubKey = pkcs10req.getRequestPublicKey(); imsg = new SimpleRequestMessage(pubKey, username, password); } else if (reqType == SecConst.CERT_REQ_TYPE_SPKAC) { // parts copied from request helper. byte[] reqBytes = req.getBytes(); if (reqBytes != null) { log.debug("Received NS request: " + new String(reqBytes)); byte[] buffer = Base64.decode(reqBytes); if (buffer == null) { return null; } ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(buffer)); ASN1Sequence spkacSeq = (ASN1Sequence) in.readObject(); in.close(); NetscapeCertRequest nscr = new NetscapeCertRequest(spkacSeq); // Verify POPO, we don't care about the challenge, it's not important. nscr.setChallenge("challenge"); if (nscr.verify("challenge") == false) { log.debug("POPO verification Failed"); throw new SignRequestSignatureException( "Invalid signature in NetscapeCertRequest, popo-verification failed."); } log.debug("POPO verification successful"); PublicKey pubKey = nscr.getPublicKey(); imsg = new SimpleRequestMessage(pubKey, username, password); } } else if (reqType == SecConst.CERT_REQ_TYPE_CRMF) { byte[] request = Base64.decode(req.getBytes()); ASN1InputStream in = new ASN1InputStream(request); ASN1Sequence crmfSeq = (ASN1Sequence) in.readObject(); ASN1Sequence reqSeq = (ASN1Sequence) ((ASN1Sequence) crmfSeq.getObjectAt(0)).getObjectAt(0); CertRequest certReq = new CertRequest(reqSeq); SubjectPublicKeyInfo pKeyInfo = certReq.getCertTemplate().getPublicKey(); KeyFactory keyFact = KeyFactory.getInstance("RSA", "BC"); KeySpec keySpec = new X509EncodedKeySpec(pKeyInfo.getEncoded()); PublicKey pubKey = keyFact.generatePublic(keySpec); // just check it's ok imsg = new SimpleRequestMessage(pubKey, username, password); // a simple crmf is not a complete PKI message, as desired by the CrmfRequestMessage class //PKIMessage msg = PKIMessage.getInstance(new ASN1InputStream(new ByteArrayInputStream(request)).readObject()); //CrmfRequestMessage reqmsg = new CrmfRequestMessage(msg, null, true, null); //imsg = reqmsg; } else if (reqType == SecConst.CERT_REQ_TYPE_PUBLICKEY) { byte[] request; // Request can be Base64 encoded or in PEM format try { request = FileTools.getBytesFromPEM(req.getBytes(), CertTools.BEGIN_PUBLIC_KEY, CertTools.END_PUBLIC_KEY); } catch (IOException ex) { try { request = Base64.decode(req.getBytes()); if (request == null) { throw new IOException("Base64 decode of buffer returns null"); } } catch (ArrayIndexOutOfBoundsException ae) { throw new IOException( "Base64 decode fails, message not base64 encoded: " + ae.getMessage()); } } final ASN1InputStream in = new ASN1InputStream(request); final SubjectPublicKeyInfo keyInfo = SubjectPublicKeyInfo.getInstance(in.readObject()); final AlgorithmIdentifier keyAlg = keyInfo.getAlgorithmId(); final X509EncodedKeySpec xKeySpec = new X509EncodedKeySpec(new DERBitString(keyInfo).getBytes()); final KeyFactory keyFact = KeyFactory.getInstance(keyAlg.getObjectId().getId(), "BC"); final PublicKey pubKey = keyFact.generatePublic(xKeySpec); imsg = new SimpleRequestMessage(pubKey, username, password); } if (imsg != null) { retval = getCertResponseFromPublicKey(admin, imsg, hardTokenSN, responseType, userdata); } } catch (NotFoundException e) { sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically throw e; } catch (InvalidKeyException e) { sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically throw e; } catch (NoSuchAlgorithmException e) { sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically throw e; } catch (InvalidKeySpecException e) { sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically throw e; } catch (NoSuchProviderException e) { sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically throw e; } catch (SignatureException e) { sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically throw e; } catch (IOException e) { sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically throw e; } catch (CertificateException e) { sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically throw e; } catch (EjbcaException e) { sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically throw e; } return retval; }