List of usage examples for org.bouncycastle.asn1.x509 AlgorithmIdentifier getParameters
public ASN1Encodable getParameters()
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 w w .j a v a2 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.tsenger.animamea.asn1.DomainParameter.java
License:Open Source License
/** * Extrahiert aus dem AlogorithmIdentifier die Parameter fr DH oder ECDH. * Es werden standardisierte DomainParameter und explizite DP erkannt. * @param algorithm OID/*w w w. jav a 2 s.com*/ */ public DomainParameter(AlgorithmIdentifier aid) { if (aid.getAlgorithm().toString().equals(BSIObjectIdentifiers.standardizedDomainParameters.toString())) { int dpref = ((ASN1Integer) aid.getParameters()).getPositiveValue().intValue(); getParameters(dpref); } else if (aid.getAlgorithm().toString().equals("1.2.840.10045.2.1")) { X9ECParameters x9ecp = X9ECParameters.getInstance(aid.getParameters()); ecSpec = new ECParameterSpec(x9ecp.getCurve(), x9ecp.getG(), x9ecp.getN()); } //TODO properitre DH Domain Parameter else throw new UnsupportedOperationException( "unsupported Domain Parameters. Algorithm OID: " + aid.getAlgorithm().toString()); }
From source file:de.tsenger.sandbox.PKCS8PrivateKey.java
License:Open Source License
public static void main(String[] args) throws IOException { byte[] pkBytes = readBinaryFile( "/home/tsenger/Dokumente/Programming/animamea/certs/Key_DEATTIDBSIDE003.pkcs8"); DERSequence pkSeq = (DERSequence) DERSequence.fromByteArray(pkBytes); PrivateKeyInfo pkInfo = new PrivateKeyInfo(pkSeq); AlgorithmIdentifier ecPublicKey = pkInfo.getPrivateKeyAlgorithm(); System.out.println(ecPublicKey.getAlgorithm().toString()); System.out.println(HexString.bufferToHex(ecPublicKey.getEncoded(null))); X9ECParameters ecp = X9ECParameters.getInstance(ecPublicKey.getParameters()); System.out.println("N: \n" + HexString.bufferToHex(Converter.bigIntToByteArray(ecp.getN()))); ECPrivateKey ecpk2 = ECPrivateKey.getInstance(ecPublicKey); //ECPrivateKey.getInstance(pkInfo.getPrivateKey()); System.out.println("private Key: \n" + HexString.bufferToHex(Converter.bigIntToByteArray(ecpk2.getKey()))); }
From source file:edu.vt.middleware.crypt.io.PrivateKeyCredentialReader.java
License:Open Source License
/** * Decrypts a DER-encoded private key in PKCS#8 format. * * @param encrypted Bytes of DER-encoded encrypted private key. * @param password Password to decrypt private key. * * @return ASN.1 encoded bytes of decrypted key. * * @throws CryptException On key decryption errors. *//* w w w .jav a 2 s . c om*/ private byte[] decryptPKCS8Key(final byte[] encrypted, final char[] password) throws CryptException { final EncryptionScheme scheme; try { final EncryptedPrivateKeyInfo ki = EncryptedPrivateKeyInfo .getInstance(ASN1Object.fromByteArray(encrypted)); final AlgorithmIdentifier alg = ki.getEncryptionAlgorithm(); if (PKCSObjectIdentifiers.id_PBES2.equals(alg.getObjectId())) { // PBES2 has following parameters: // { // {id-PBKDF2, {salt, iterationCount, keyLength (optional)}} // {encryptionAlgorithmOid, iv} // } final DERSequence pbeSeq = (DERSequence) alg.getParameters(); final PBKDF2Parameters kdfParms = PBKDF2Parameters.decode((DERSequence) pbeSeq.getObjectAt(0)); final PBES2CipherGenerator cipherGen = new PBES2CipherGenerator( (DERSequence) pbeSeq.getObjectAt(1)); if (kdfParms.getLength() == 0) { kdfParms.setLength(cipherGen.getKeySize() / 8); } scheme = new PBES2EncryptionScheme(cipherGen.generate(), kdfParms); } else { // Use PBES1 encryption scheme to decrypt key scheme = new PBES1EncryptionScheme(PBES1Algorithm.fromOid(alg.getObjectId().getId()), PBEParameter.decode((DERSequence) alg.getParameters())); } return scheme.decrypt(password, ki.getEncryptedData()); } catch (Exception e) { throw new CryptException("Failed decrypting PKCS#8 private key", e); } }
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 .j a v a 2 s.c o 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.wstech2.me.httpsclient.CertificateValidatorUtils.java
License:Apache License
public static boolean isAlgIdEqual(AlgorithmIdentifier id1, AlgorithmIdentifier id2) { if (!id1.getAlgorithm().equals(id2.getAlgorithm())) { return false; }// w w w .j a v a 2 s . c om if (id1.getParameters() == null) { if (id2.getParameters() != null && !id2.getParameters().equals(DERNull.INSTANCE)) { return false; } return true; } if (id2.getParameters() == null) { if (id1.getParameters() != null && !id1.getParameters().equals(DERNull.INSTANCE)) { return false; } return true; } return id1.getParameters().equals(id2.getParameters()); }
From source file:org.cryptacular.asn.PKCS8PrivateKeyDecoder.java
License:Open Source License
@Override protected byte[] decryptKey(final byte[] encrypted, final char[] password) { final EncryptionScheme scheme; final EncryptedPrivateKeyInfo ki = EncryptedPrivateKeyInfo.getInstance(tryConvertPem(encrypted)); final AlgorithmIdentifier alg = ki.getEncryptionAlgorithm(); if (PKCSObjectIdentifiers.id_PBES2.equals(alg.getAlgorithm())) { scheme = new PBES2EncryptionScheme(PBES2Parameters.getInstance(alg.getParameters()), password); } else {/*from w w w . j a v a2s. c om*/ scheme = new PBES1EncryptionScheme(PBES1Algorithm.fromOid(alg.getAlgorithm().getId()), PBEParameter.getInstance(alg.getParameters()), password); } return scheme.decrypt(ki.getEncryptedData()); }
From source file:org.ejbca.core.protocol.cmp.CmpTestCase.java
License:Open Source License
protected static void checkCmpResponseGeneral(byte[] retMsg, String issuerDN, X500Name userDN, Certificate cacert, byte[] senderNonce, byte[] transId, boolean signed, String pbeSecret, String expectedSignAlg)/*w w w.j a v a 2 s . co m*/ throws IOException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException { assertNotNull("No response from server.", retMsg); assertTrue("Response was of 0 length.", retMsg.length > 0); boolean pbe = (pbeSecret != null); // // Parse response message // ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(retMsg)); PKIMessage respObject = null; try { respObject = PKIMessage.getInstance(asn1InputStream.readObject()); } finally { asn1InputStream.close(); } assertNotNull(respObject); // The signer, i.e. the CA, check it's the right CA PKIHeader header = respObject.getHeader(); // Check that the message is signed with the correct digest alg if (StringUtils.isEmpty(expectedSignAlg)) { expectedSignAlg = PKCSObjectIdentifiers.sha1WithRSAEncryption.getId(); } // if cacert is ECDSA we should expect an ECDSA signature alg //if (AlgorithmTools.getSignatureAlgorithm(cacert).contains("ECDSA")) { // expectedSignAlg = X9ObjectIdentifiers.ecdsa_with_SHA1.getId(); //} else if(AlgorithmTools.getSignatureAlgorithm(cacert).contains("ECGOST3410")) { // expectedSignAlg = CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001.getId(); //} else if(AlgorithmTools.getSignatureAlgorithm(cacert).contains("DSTU4145")) { // expectedSignAlg = (new ASN1ObjectIdentifier(CesecoreConfiguration.getOidDstu4145())).getId(); //} if (signed) { AlgorithmIdentifier algId = header.getProtectionAlg(); assertNotNull( "Protection algorithm was null when expecting a signed response, this was propably an unprotected error message: " + header.getFreeText(), algId); assertEquals(expectedSignAlg, algId.getAlgorithm().getId()); } if (pbe) { AlgorithmIdentifier algId = header.getProtectionAlg(); assertNotNull( "Protection algorithm was null when expecting a pbe protected response, this was propably an unprotected error message: " + header.getFreeText(), algId); assertEquals("Protection algorithm id: " + algId.getAlgorithm().getId(), CMPObjectIdentifiers.passwordBasedMac.getId(), algId.getAlgorithm().getId()); // 1.2.840.113549.1.1.5 - SHA-1 with RSA Encryption } // Check that the signer is the expected CA assertEquals(header.getSender().getTagNo(), 4); X500Name expissuer = new X500Name(issuerDN); X500Name actissuer = new X500Name(header.getSender().getName().toString()); assertEquals(expissuer, actissuer); if (signed) { // Verify the signature byte[] protBytes = CmpMessageHelper.getProtectedBytes(respObject); DERBitString bs = respObject.getProtection(); Signature sig; try { sig = Signature.getInstance(expectedSignAlg, "BC"); sig.initVerify(cacert); sig.update(protBytes); boolean ret = sig.verify(bs.getBytes()); assertTrue(ret); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); assertTrue(false); } catch (NoSuchProviderException e) { e.printStackTrace(); assertTrue(false); } catch (InvalidKeyException e) { e.printStackTrace(); assertTrue(false); } catch (SignatureException e) { e.printStackTrace(); assertTrue(false); } } if (pbe) { ASN1OctetString os = header.getSenderKID(); assertNotNull(os); String keyId = CmpMessageHelper.getStringFromOctets(os); log.debug("Found a sender keyId: " + keyId); // Verify the PasswordBased protection of the message byte[] protectedBytes = CmpMessageHelper.getProtectedBytes(respObject); DERBitString protection = respObject.getProtection(); AlgorithmIdentifier pAlg = header.getProtectionAlg(); log.debug("Protection type is: " + pAlg.getAlgorithm().getId()); PBMParameter pp = PBMParameter.getInstance(pAlg.getParameters()); int iterationCount = pp.getIterationCount().getPositiveValue().intValue(); log.debug("Iteration count is: " + iterationCount); AlgorithmIdentifier owfAlg = pp.getOwf(); // Normal OWF alg is 1.3.14.3.2.26 - SHA1 log.debug("Owf type is: " + owfAlg.getAlgorithm().getId()); AlgorithmIdentifier macAlg = pp.getMac(); // Normal mac alg is 1.3.6.1.5.5.8.1.2 - HMAC/SHA1 log.debug("Mac type is: " + macAlg.getAlgorithm().getId()); byte[] salt = pp.getSalt().getOctets(); // log.info("Salt is: "+new String(salt)); byte[] raSecret = pbeSecret != null ? pbeSecret.getBytes() : new byte[0]; byte[] basekey = new byte[raSecret.length + salt.length]; System.arraycopy(raSecret, 0, basekey, 0, raSecret.length); for (int i = 0; i < salt.length; i++) { basekey[raSecret.length + i] = salt[i]; } // Construct the base key according to rfc4210, section 5.1.3.1 MessageDigest dig = MessageDigest.getInstance(owfAlg.getAlgorithm().getId(), BouncyCastleProvider.PROVIDER_NAME); for (int i = 0; i < iterationCount; i++) { basekey = dig.digest(basekey); dig.reset(); } // HMAC/SHA1 os normal 1.3.6.1.5.5.8.1.2 or 1.2.840.113549.2.7 String macOid = macAlg.getAlgorithm().getId(); Mac mac = Mac.getInstance(macOid, BouncyCastleProvider.PROVIDER_NAME); SecretKey key = new SecretKeySpec(basekey, macOid); mac.init(key); mac.reset(); mac.update(protectedBytes, 0, protectedBytes.length); byte[] out = mac.doFinal(); // My out should now be the same as the protection bits byte[] pb = protection.getBytes(); boolean ret = Arrays.equals(out, pb); assertTrue(ret); } // --SenderNonce // SenderNonce is something the server came up with, but it should be 16 // chars byte[] nonce = header.getSenderNonce().getOctets(); assertEquals(nonce.length, 16); // --Recipient Nonce // recipient nonce should be the same as we sent away as sender nonce nonce = header.getRecipNonce().getOctets(); assertEquals(new String(nonce), new String(senderNonce)); // --Transaction ID // transid should be the same as the one we sent nonce = header.getTransactionID().getOctets(); assertEquals(new String(nonce), new String(transId)); }
From source file:org.ejbca.core.protocol.cmp.CrmfRequestMessageTest.java
License:Open Source License
private void doNovosecClientRequest(final String sigAlg, final String digestAlg, final String expectedAlgOid) throws IOException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException, SignatureException, IllegalStateException, OperatorCreationException, CertificateException { // Check that we can parse a request from Novosec (patched by EJBCA). // Read an initialization request with a signature POP and signature protection to see that we can process it {/*from w w w. j av a 2s . c om*/ ASN1InputStream in = new ASN1InputStream(novosecsigpopir); try { ASN1Primitive derObject = in.readObject(); PKIMessage req = PKIMessage.getInstance(derObject); //log.info(req.toString()); // Verify should be ok if we do not allow RA verify POP here CrmfRequestMessage msg = new CrmfRequestMessage(req, "CN=AdminCA1", false, "CN"); assertTrue(msg.verify()); // Since we don't have RA POP we can't test for that... assertEquals("CN=AdminCA1,O=EJBCA Sample,C=SE", msg.getIssuerDN()); assertEquals("CN=abc123rry2942812801980668853,O=PrimeKey Solutions AB,C=SE", msg.getRequestDN()); assertEquals("abc123rry2942812801980668853", msg.getUsername()); assertEquals("foo123", msg.getPassword()); // Verify signature protection AlgorithmIdentifier algId = msg.getMessage().getHeader().getProtectionAlg(); String oid = algId.getAlgorithm().getId(); assertEquals(PKCSObjectIdentifiers.sha1WithRSAEncryption.getId(), oid); // Check that this is an old message, created before ECA-2104, using null instead of DERNull as algorithm parameters. ASN1Encodable pp = algId.getParameters(); assertNull(pp); // Try to verify, it should work good even though the small bug in ECA-2104, since we don't use algorithm parameters for RSA-PKCS signatures PublicKey pubKey = msg.getRequestPublicKey(); assertTrue(CmpMessageHelper.verifyCertBasedPKIProtection(msg.getMessage(), pubKey)); // Verify that our verification routine does not give positive result for any other keys KeyPair keys = KeyTools.genKeys("512", "RSA"); assertFalse(CmpMessageHelper.verifyCertBasedPKIProtection(msg.getMessage(), keys.getPublic())); } finally { in.close(); } } // Re-protect the message, now fixed by ECA-2104 { ASN1InputStream in = new ASN1InputStream(novosecsigpopir); try { ASN1Primitive derObject = in.readObject(); PKIMessage myPKIMessage = PKIMessage.getInstance(derObject); KeyPair keys = KeyTools.genKeys("512", "RSA"); X509Certificate signCert = CertTools.genSelfCert("CN=CMP Sign Test", 3650, null, keys.getPrivate(), keys.getPublic(), sigAlg, false); // Re-sign the message Collection<Certificate> signCertChain = new ArrayList<Certificate>(); signCertChain.add(signCert); byte[] newmsg = CmpMessageHelper.signPKIMessage(myPKIMessage, signCertChain, keys.getPrivate(), digestAlg, "BC"); in.close(); in = new ASN1InputStream(newmsg); derObject = in.readObject(); PKIMessage pkimsg = PKIMessage.getInstance(derObject); // We have to do this twice, because Novosec caches ProtectedBytes in the PKIMessage object, so we need to // encode it and re-decode it again to get the changes from ECA-2104 encoded correctly. // Not needed when simply signing a new message that you create, only when re-signing newmsg = CmpMessageHelper.signPKIMessage(pkimsg, signCertChain, keys.getPrivate(), digestAlg, "BC"); in.close(); in = new ASN1InputStream(newmsg); derObject = in.readObject(); pkimsg = PKIMessage.getInstance(derObject); AlgorithmIdentifier algId = pkimsg.getHeader().getProtectionAlg(); String oid = algId.getAlgorithm().getId(); assertEquals(expectedAlgOid, oid); // Check that we have DERNull and not plain java null as algorithm parameters. ASN1Encodable pp = algId.getParameters(); assertNotNull(pp); assertEquals(DERNull.class.getName(), pp.getClass().getName()); // Try to verify, also verify at the same time that encoding decoding of the signature works assertTrue(CmpMessageHelper.verifyCertBasedPKIProtection(pkimsg, keys.getPublic())); // Verify that our verification routine does not give positive result for any other keys CrmfRequestMessage msg = new CrmfRequestMessage(pkimsg, "CN=AdminCA1", false, "CN"); assertTrue(msg.verify()); PublicKey pubKey = msg.getRequestPublicKey(); assertFalse(CmpMessageHelper.verifyCertBasedPKIProtection(pkimsg, pubKey)); } finally { in.close(); } } }
From source file:org.ejbca.core.protocol.cmp.CrmfRequestMessageTest.java
License:Open Source License
private void internalBcClientRequestTest(byte[] message) throws IOException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException { // Check that we can parse request from BouncyCastle version 1.46. // Read an initialization request with a signature POP, and signature protection, to see that we can process it ASN1InputStream in = new ASN1InputStream(message); try {/*w w w . j a va 2 s. c om*/ ASN1Primitive derObject = in.readObject(); PKIMessage req = PKIMessage.getInstance(derObject); //log.info(req.toString()); // Verify should be ok if we do not allow RA verify POP here CrmfRequestMessage msg = new CrmfRequestMessage(req, "CN=AdminCA1", false, "CN"); // BC messages in BC1.46 uses POPOSigningKeyInput for POPO, not the 3rd case in RFC4211 section 4.1, like everyone else... // BC messages in BC1.47 should use normal POPO, 3rd case assertTrue(msg.verify()); // Since we don't have RA POP we can't test for that... assertEquals("CN=AdminCA1", msg.getIssuerDN()); assertEquals("CN=user", msg.getRequestDN()); assertEquals("user", msg.getUsername()); assertEquals("foo123", msg.getPassword()); // Check signature protection AlgorithmIdentifier algId = msg.getMessage().getHeader().getProtectionAlg(); String oid = algId.getAlgorithm().getId(); assertEquals(PKCSObjectIdentifiers.sha1WithRSAEncryption.getId(), oid); // Check that we have DERNull and not plain java null as algorithm parameters. ASN1Encodable pp = algId.getParameters(); assertNotNull(pp); assertEquals(DERNull.class.getName(), pp.getClass().getName()); // Try to verify the protection signature assertTrue(CmpMessageHelper.verifyCertBasedPKIProtection(msg.getMessage(), msg.getRequestPublicKey())); } finally { in.close(); } }