List of usage examples for org.bouncycastle.asn1.x509 SubjectPublicKeyInfo getAlgorithm
public AlgorithmIdentifier getAlgorithm()
From source file:com.vvote.thirdparty.ximix.util.BLSPublicKeyFactory.java
License:Apache License
/** * Create BLS01PublicKeyParameters from an ASN.1 encoding of a SubjectPublicKeyInfo object. * * @param publicKeyInfo the info structure containing the BLS public key. * @return a BLS public key./* w ww. jav a 2 s . c o m*/ */ public static BLS01PublicKeyParameters createKey(SubjectPublicKeyInfo publicKeyInfo) { AlgorithmIdentifier algId = publicKeyInfo.getAlgorithm(); CurveParameters curveParameters; Element G; Pairing pairing; try { ASN1Sequence parameters = ASN1Sequence.getInstance(algId.getParameters()); curveParameters = new DefaultCurveParameters().load(new ByteArrayInputStream( DERUTF8String.getInstance(parameters.getObjectAt(0)).getString().getBytes("UTF8"))); pairing = PairingFactory.getPairing(curveParameters); G = pairing.getG2().newElement(); G.setFromBytes(DEROctetString.getInstance(parameters.getObjectAt(1)).getOctets()); } catch (IOException e) { throw new IllegalStateException("Unable to support encoding: " + e.getMessage(), e); } BLS01Parameters blsParameters = new BLS01Parameters(curveParameters, G.getImmutable()); Element pK = pairing.getG2().newElement(); pK.setFromBytes(publicKeyInfo.getPublicKeyData().getBytes()); return new BLS01PublicKeyParameters(blsParameters, pK.getImmutable()); }
From source file:de.thiemann.ssl.report.model.CertificateV3.java
License:Open Source License
private PubKeyInfo transferPublicKeyInfo(byte[] encodedPublicKey) { PubKeyInfo info = new PubKeyInfo(); try {/* ww w .j a v a2s. com*/ SubjectPublicKeyInfo subPubKeyInfo = new SubjectPublicKeyInfo( (ASN1Sequence) ASN1Object.fromByteArray(encodedPublicKey)); String asn1PubKeyId = subPubKeyInfo.getAlgorithmId().getAlgorithm().getId(); if (asn1PubKeyId.equals(ASN1PublicKeyIds.RSA.getOid())) { DERSequence seq = (DERSequence) subPubKeyInfo.getPublicKey(); ASN1Integer iModulus = (ASN1Integer) seq.getObjectAt(0); BigInteger modulus = iModulus.getPositiveValue(); info.pubKeyAlgorithm = ASN1PublicKeyIds.RSA.name(); info.pubKeySize = modulus.bitLength(); } else if (asn1PubKeyId.equals(ASN1PublicKeyIds.DSA.getOid())) { info.pubKeyAlgorithm = ASN1PublicKeyIds.DSA.name(); } else if (asn1PubKeyId.equals(ASN1PublicKeyIds.Diffie_Hellman.getOid())) { info.pubKeyAlgorithm = ASN1PublicKeyIds.Diffie_Hellman.name(); } else if (asn1PubKeyId.equals(ASN1PublicKeyIds.KEA.getOid())) { info.pubKeyAlgorithm = ASN1PublicKeyIds.KEA.name(); } else if (asn1PubKeyId.equals(ASN1PublicKeyIds.ECDH.getOid())) { info.pubKeyAlgorithm = ASN1PublicKeyIds.ECDH.name(); } else info.pubKeyAlgorithm = "Unknown public key! OID: " + asn1PubKeyId; } catch (IOException e) { e.printStackTrace(); } return info; }
From source file:es.gob.afirma.envelopers.cades.CAdESUtils.java
License:Open Source License
/** Obtiene un <code>Info</code> que contiene los RecipientInfos y el EncryptedContentInfo. * @param data Datos a incluir en el sobre * @param config Configuración de cifrado a aplicar * @param certDest Certificados de los destinatarios * @param cipherKey Clave de cifrado/*from w w w . j a v a2 s. c om*/ * @return <code>Info</code> que contiene los RecipientInfos y el EncryptedContentInfo * @throws IOException en caso de error de entrada / salida * @throws CertificateEncodingException en caso de errores de codificación en los certificados */ static Info getEnvelopeInfo(final byte[] data, final AOCipherConfig config, final X509Certificate[] certDest, final SecretKey cipherKey) throws IOException, CertificateEncodingException { // Reiniciamos las dos variables final Info infos = new Info(); final ASN1EncodableVector recipientInfos = new ASN1EncodableVector(); X509Certificate cert; TBSCertificateStructure tbs; IssuerAndSerialNumber isse; RecipientIdentifier rid; PublicKey pubKey; AlgorithmIdentifier keyEncAlg; SubjectPublicKeyInfo info; // Cifrado de la clave byte[] encryptedKey = null; // generamos el contenedor de cifrado RecipientInfo recipient = null; for (final X509Certificate element : certDest) { cert = element; tbs = TBSCertificateStructure.getInstance(ASN1Primitive.fromByteArray(cert.getTBSCertificate())); // Obtenemos el Isuer & serial number isse = new IssuerAndSerialNumber(X500Name.getInstance(tbs.getIssuer()), tbs.getSerialNumber().getValue()); // Creamos el recipientInfo rid = new RecipientIdentifier(isse); // Obtenemos la clave publica pubKey = cert.getPublicKey(); // obtenemos la informacion de la clave publica info = tbs.getSubjectPublicKeyInfo(); // obtenemos el algoritmo de cifrado. keyEncAlg = info.getAlgorithm(); try { // ciframos la clave encryptedKey = cipherKey(pubKey, cipherKey); } catch (final Exception e) { LOGGER.severe("Error durante el proceso cifrado de la clave: " + e); //$NON-NLS-1$ } // creamos el recipiente con los datos del destinatario. final KeyTransRecipientInfo keyTransRecipientInfo = new KeyTransRecipientInfo(rid, keyEncAlg, new DEROctetString(encryptedKey)); recipient = new RecipientInfo(keyTransRecipientInfo); // Lo añadimos al recipiente de destinatarios. recipientInfos.add(recipient); } // 3. ENCRIPTEDCONTENTINFO try { infos.setEncInfo(getEncryptedContentInfo(data, config, cipherKey)); } catch (final Exception e) { LOGGER.severe("Error durante el proceso cifrado de la clave: " + e); //$NON-NLS-1$ } infos.setRecipientInfos(recipientInfos); return infos; }
From source file:eu.betaas.taas.securitymanager.common.ec.ECKeyPairGen.java
License:Apache License
/** * A method to reconstruct an ECPublicKey from a SubjectPublicKeyInfo of a * certificate /*from w ww . java2s . co m*/ * @param info: SubjectPublicKeyInfo in a X509Certificate * @return: ECPublicKeyParameters */ public static ECPublicKeyParameters generateECPublicKey(SubjectPublicKeyInfo info) { X962Parameters as = (X962Parameters) info.getAlgorithm().getParameters(); DERSequence aa = (DERSequence) as.getParameters(); Enumeration en = aa.getObjects(); ECCurve curve = null; org.bouncycastle.math.ec.ECPoint g = null; byte[] seed = null; BigInteger h = null; BigInteger n = null; while (en.hasMoreElements()) { Object oen = en.nextElement(); if (oen instanceof X9Curve) { curve = ((X9Curve) oen).getCurve(); seed = ((X9Curve) oen).getSeed(); } else if (oen instanceof X9ECPoint) { g = ((X9ECPoint) oen).getPoint(); } else if (oen instanceof ASN1Integer) { BigInteger xoen = ((ASN1Integer) oen).getValue(); if (xoen.equals(BigInteger.ONE)) h = xoen; else n = xoen; } } ASN1OctetString key = new DEROctetString(info.getPublicKeyData().getBytes()); X9ECPoint derQ = new X9ECPoint(curve, key); ECDomainParameters dParams = new ECDomainParameters(curve, g, n, h, seed); return new ECPublicKeyParameters(derQ.getPoint(), dParams); }
From source file:io.apigee.trireme.crypto.algorithms.DsaKeyPairProvider.java
License:Open Source License
/** * DSA public key format -- the PEM file contains a "SubjectPublicKeyInfo" object, which contains * an "Algorithm Identifier" that consists of three integers (p, q, and g) and a single * integer representing y. We use those four parts to assemble a Java public key. *///from w ww . ja va 2s. co m @Override public PublicKey readPublicKey(String algorithm, Reader rdr) throws CryptoException, IOException { PEMParser pp = new PEMParser(rdr); try { Object po = pp.readObject(); if (log.isDebugEnabled()) { log.debug("Trying to read an {} public key and got {}", algorithm, po); } if (po instanceof SubjectPublicKeyInfo) { SubjectPublicKeyInfo pk = (SubjectPublicKeyInfo) po; AlgorithmIdentifier alg = pk.getAlgorithm(); if (!(alg.getParameters() instanceof ASN1Sequence)) { throw new CryptoException("Invalid DSA public key format: Algorithm ID not a Sequence"); } ASN1Sequence identifiers = (ASN1Sequence) (alg.getParameters()); if (identifiers.size() != 3) { throw new CryptoException("Invalid DSA public key format: Identifier does not have 3 items"); } DERInteger p = (DERInteger) identifiers.getObjectAt(0); DERInteger q = (DERInteger) identifiers.getObjectAt(1); DERInteger g = (DERInteger) identifiers.getObjectAt(2); ASN1Primitive pkPrim = pk.parsePublicKey(); if (!(pkPrim instanceof ASN1Integer)) { throw new CryptoException("Invalid DSA public key format: Public key is not an integer"); } DERInteger y = (DERInteger) pkPrim; try { KeyFactory factory = KeyFactory.getInstance("DSA"); DSAPublicKeySpec pubSpec = new DSAPublicKeySpec(y.getValue(), p.getValue(), q.getValue(), g.getValue()); return factory.generatePublic(pubSpec); } catch (GeneralSecurityException gse) { throw new CryptoException(gse); } } throw new CryptoException("Input data does not contain a public key"); } finally { pp.close(); } }
From source file:net.sf.portecle.DViewCSR.java
License:Open Source License
/** * Populate the dialog with the currently selected certificate request's details. * /*from w w w . j ava 2 s .c o m*/ * @throws CryptoException A problem was encountered getting the certificate request's details */ private void populateDialog() throws CryptoException { // Version m_jtfVersion .setText(m_req.toASN1Structure().getCertificationRequestInfo().getVersion().getValue().toString()); m_jtfVersion.setCaretPosition(0); // Subject X500Name subject = m_req.getSubject(); m_jtfSubject.setText(subject.toString()); m_jtfSubject.setCaretPosition(0); m_basename = NameUtil.getCommonName(subject); // Public Key (algorithm and keysize) SubjectPublicKeyInfo keyInfo = m_req.getSubjectPublicKeyInfo(); AsymmetricKeyParameter keyParams = null; try { keyParams = PublicKeyFactory.createKey(keyInfo); } catch (IOException e) { throw new CryptoException(RB.getString("DViewCSR.NoGetKeyInfo.exception.message"), e); } m_jtfPublicKey.setText(AlgorithmType.toString(keyInfo.getAlgorithm().getAlgorithm().toString())); int iKeySize = KeyPairUtil.getKeyLength(keyParams); if (iKeySize != KeyPairUtil.UNKNOWN_KEY_SIZE) { m_jtfPublicKey.setText(MessageFormat.format(RB.getString("DViewCSR.m_jtfPublicKey.text"), m_jtfPublicKey.getText(), iKeySize)); } m_jtfPublicKey.setCaretPosition(0); // Signature Algorithm String sigAlgName = SignatureType.toString(m_req.getSignatureAlgorithm().getAlgorithm().toString()); m_jtfSignatureAlgorithm.setText(sigAlgName); m_jtfSignatureAlgorithm.setCaretPosition(0); // TODO: attributes, requested extensions }
From source file:org.cesecore.keys.util.KeyTools.java
License:Open Source License
/** * Get the ASN.1 encoded PublicKey as a Java PublicKey Object. * @param the ASN.1 encoded PublicKey//from w w w.j ava2 s.c o m * @return the ASN.1 encoded PublicKey as a Java Object */ public static PublicKey getPublicKeyFromBytes(byte[] asn1EncodedPublicKey) { PublicKey pubKey = null; final ASN1InputStream in = new ASN1InputStream(asn1EncodedPublicKey); try { final SubjectPublicKeyInfo keyInfo = SubjectPublicKeyInfo.getInstance(in.readObject()); final AlgorithmIdentifier keyAlg = keyInfo.getAlgorithm(); final X509EncodedKeySpec xKeySpec = new X509EncodedKeySpec(new DERBitString(keyInfo).getBytes()); final KeyFactory keyFact = KeyFactory.getInstance(keyAlg.getAlgorithm().getId(), "BC"); pubKey = keyFact.generatePublic(xKeySpec); } catch (IOException e) { log.debug("Unable to decode PublicKey.", e); } catch (NoSuchAlgorithmException e) { log.debug("Unable to decode PublicKey.", e); } catch (NoSuchProviderException e) { log.debug("Unable to decode PublicKey.", e); } catch (InvalidKeySpecException e) { log.debug("Unable to decode PublicKey.", e); } finally { try { in.close(); } catch (IOException e) { log.debug("Unable to close input stream."); } } return pubKey; }
From source file:org.cesecore.keys.util.KeyToolsTest.java
License:Open Source License
@Test public void testGenKeysECDSAx9() throws Exception { KeyPair keys = KeyTools.genKeys("prime192v1", AlgorithmConstants.KEYALGORITHM_ECDSA); // Verify that the keys are using maned curves, and not explicit parameters PrivateKeyInfo priv2 = PrivateKeyInfo.getInstance(keys.getPrivate().getEncoded()); assertTrue("Private key is not encoded with named curves, but using explicit parameters", X962Parameters.getInstance(priv2.getPrivateKeyAlgorithm().getParameters()).isNamedCurve()); SubjectPublicKeyInfo pub2 = SubjectPublicKeyInfo.getInstance(keys.getPublic().getEncoded()); assertTrue("Public key is not encoded with named curves, but using explicit parameters", X962Parameters.getInstance(pub2.getAlgorithm().getParameters()).isNamedCurve()); assertNotNull("keys must not be null", keys); String b64private = new String(Base64.encode(keys.getPrivate().getEncoded())); assertNotNull("b64private must not be null", b64private); // log.debug(b64private); X509Certificate cert = CertTools.genSelfCert("C=SE,O=Test,CN=Test", 365, null, keys.getPrivate(), keys.getPublic(), AlgorithmConstants.SIGALG_SHA256_WITH_ECDSA, true); // log.debug(cert); assertNotNull("cert must not be null", cert); String b64cert = new String(Base64.encode(cert.getEncoded())); assertNotNull("b64cert cannot be null", b64cert); // log.debug(b64cert); KeyTools.testKey(keys.getPrivate(), keys.getPublic(), "BC"); // Test that fails KeyPair keys1 = KeyTools.genKeys("prime192v1", AlgorithmConstants.KEYALGORITHM_ECDSA); try {//from ww w . j av a 2 s. c o m KeyTools.testKey(keys1.getPrivate(), keys.getPublic(), "BC"); assertTrue(false); } catch (InvalidKeyException e) { assertEquals("Not possible to sign and then verify with key pair.", e.getMessage()); } // This will not do anything for a key which is not an org.ejbca.cvc.PublicKeyEC PublicKey pk = KeyTools.getECPublicKeyWithParams(keys.getPublic(), "prime192v1"); assertTrue(pk.equals(keys.getPublic())); pk = KeyTools.getECPublicKeyWithParams(keys.getPublic(), pk); assertTrue(pk.equals(keys.getPublic())); AlgorithmParameterSpec spec = KeyTools.getKeyGenSpec(keys.getPublic()); assertNotNull(spec); assertTrue((spec instanceof ECParameterSpec)); assertTrue(KeyTools.isPrivateKeyExtractable(keys.getPrivate())); ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(out); KeyTools.printPublicKeyInfo(keys.getPublic(), ps); ps.close(); String str = out.toString(); assertTrue(str.contains("Elliptic curve key")); }
From source file:org.ejbca.core.protocol.cmp.CrmfRequestMessage.java
License:Open Source License
private PublicKey getPublicKey(final SubjectPublicKeyInfo subjectPKInfo, final String provider) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException { try {/* www. j a v a 2 s .c om*/ final X509EncodedKeySpec xspec = new X509EncodedKeySpec(new DERBitString(subjectPKInfo).getBytes()); final AlgorithmIdentifier keyAlg = subjectPKInfo.getAlgorithm(); return KeyFactory.getInstance(keyAlg.getAlgorithm().getId(), provider).generatePublic(xspec); } catch (java.security.spec.InvalidKeySpecException e) { final InvalidKeyException newe = new InvalidKeyException("Error decoding public key."); newe.initCause(e); throw newe; } catch (IOException e) { final InvalidKeyException newe = new InvalidKeyException("Error decoding public key."); newe.initCause(e); throw newe; } }
From source file:org.jmrtd.Util.java
License:Open Source License
public static SubjectPublicKeyInfo toSubjectPublicKeyInfo(PublicKey publicKey) { try {/*from www. ja v a 2s. c om*/ String algorithm = publicKey.getAlgorithm(); if ("EC".equals(algorithm) || "ECDH".equals(algorithm) || (publicKey instanceof ECPublicKey)) { ASN1InputStream asn1In = new ASN1InputStream(publicKey.getEncoded()); SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo( (ASN1Sequence) asn1In.readObject()); asn1In.close(); AlgorithmIdentifier algorithmIdentifier = subjectPublicKeyInfo.getAlgorithm(); String algOID = algorithmIdentifier.getAlgorithm().getId(); if (!SecurityInfo.ID_EC_PUBLIC_KEY.equals(algOID)) { throw new IllegalStateException("Was expecting id-ecPublicKey (" + SecurityInfo.ID_EC_PUBLIC_KEY_TYPE + "), found " + algOID); } ASN1Primitive derEncodedParams = algorithmIdentifier.getParameters().toASN1Primitive(); X9ECParameters params = null; if (derEncodedParams instanceof ASN1ObjectIdentifier) { ASN1ObjectIdentifier paramsOID = (ASN1ObjectIdentifier) derEncodedParams; /* It's a named curve from X9.62. */ params = X962NamedCurves.getByOID(paramsOID); if (params == null) { throw new IllegalStateException( "Could not find X9.62 named curve for OID " + paramsOID.getId()); } /* Reconstruct the parameters. */ org.bouncycastle.math.ec.ECPoint generator = params.getG(); org.bouncycastle.math.ec.ECCurve curve = generator.getCurve(); generator = curve.createPoint(generator.getX().toBigInteger(), generator.getY().toBigInteger(), false); params = new X9ECParameters(params.getCurve(), generator, params.getN(), params.getH(), params.getSeed()); } else { /* It's not a named curve, we can just return the decoded public key info. */ return subjectPublicKeyInfo; } if (publicKey instanceof org.bouncycastle.jce.interfaces.ECPublicKey) { org.bouncycastle.jce.interfaces.ECPublicKey ecPublicKey = (org.bouncycastle.jce.interfaces.ECPublicKey) publicKey; AlgorithmIdentifier id = new AlgorithmIdentifier( subjectPublicKeyInfo.getAlgorithm().getAlgorithm(), params.toASN1Primitive()); org.bouncycastle.math.ec.ECPoint q = ecPublicKey.getQ(); /* FIXME: investigate the compressed versus uncompressed point issue. What is allowed in TR03110? -- MO */ // In case we would like to compress the point: // p = p.getCurve().createPoint(p.getX().toBigInteger(), p.getY().toBigInteger(), true); subjectPublicKeyInfo = new SubjectPublicKeyInfo(id, q.getEncoded()); return subjectPublicKeyInfo; } else { return subjectPublicKeyInfo; } } else if ("DH".equals(algorithm) || (publicKey instanceof DHPublicKey)) { DHPublicKey dhPublicKey = (DHPublicKey) publicKey; DHParameterSpec dhSpec = dhPublicKey.getParams(); return new SubjectPublicKeyInfo( new AlgorithmIdentifier(EACObjectIdentifiers.id_PK_DH, new DHParameter(dhSpec.getP(), dhSpec.getG(), dhSpec.getL()).toASN1Primitive()), new ASN1Integer(dhPublicKey.getY())); } else { throw new IllegalArgumentException( "Unrecognized key type, found " + publicKey.getAlgorithm() + ", should be DH or ECDH"); } } catch (Exception e) { LOGGER.severe("Exception: " + e.getMessage()); return null; } }