List of usage examples for org.bouncycastle.asn1.cmp CMPObjectIdentifiers passwordBasedMac
ASN1ObjectIdentifier passwordBasedMac
To view the source code for org.bouncycastle.asn1.cmp CMPObjectIdentifiers passwordBasedMac.
Click Source Link
From source file:org.ejbca.core.protocol.cmp.CmpErrorResponseMessage.java
License:Open Source License
@Override public boolean create() throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException { final PKIHeaderBuilder myPKIHeaderBuilder = CmpMessageHelper.createPKIHeaderBuilder(getSender(), getRecipient(), getSenderNonce(), getRecipientNonce(), getTransactionId()); boolean pbeProtected = (getPbeDigestAlg() != null) && (getPbeMacAlg() != null) && (getPbeKeyId() != null) && (getPbeKey() != null); if (pbeProtected) { myPKIHeaderBuilder.setProtectionAlg(new AlgorithmIdentifier(CMPObjectIdentifiers.passwordBasedMac)); }//from www . j a v a2s . c o m final PKIHeader myPKIHeader = myPKIHeaderBuilder.build(); PKIStatusInfo myPKIStatusInfo = new PKIStatusInfo(PKIStatus.rejection); if (failInfo != null && failText != null) { myPKIStatusInfo = new PKIStatusInfo(PKIStatus.rejection, new PKIFreeText(new DERUTF8String(failText)), CmpMessageHelper.getPKIFailureInfo(failInfo.intValue())); } else if (failText != null) { myPKIStatusInfo = new PKIStatusInfo(PKIStatus.rejection, new PKIFreeText(new DERUTF8String(failText))); } PKIBody myPKIBody = null; log.debug("Create error message from requestType: " + requestType); if (requestType == 0 || requestType == 2) { myPKIBody = CmpMessageHelper.createCertRequestRejectBody(myPKIStatusInfo, requestId, requestType); } else { ErrorMsgContent myErrorContent = new ErrorMsgContent(myPKIStatusInfo); myPKIBody = new PKIBody(23, myErrorContent); // 23 = error } PKIMessage myPKIMessage = new PKIMessage(myPKIHeader, myPKIBody); if (pbeProtected) { responseMessage = CmpMessageHelper.protectPKIMessageWithPBE(myPKIMessage, getPbeKeyId(), getPbeKey(), getPbeDigestAlg(), getPbeMacAlg(), getPbeIterationCount()); } else { responseMessage = CmpMessageHelper.pkiMessageToByteArray(myPKIMessage); } return true; }
From source file:org.ejbca.core.protocol.cmp.CmpMessageHelper.java
License:Open Source License
public static byte[] protectPKIMessageWithPBE(PKIMessage msg, String keyId, String raSecret, String digestAlgId, String macAlgId, int iterationCount) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException { if (LOG.isTraceEnabled()) { LOG.trace(">protectPKIMessageWithPBE()"); }//from w w w. j a v a 2s.c om // Create the PasswordBased protection of the message PKIHeaderBuilder head = getHeaderBuilder(msg.getHeader()); byte[] keyIdBytes; try { keyIdBytes = keyId.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { keyIdBytes = keyId.getBytes(); LOG.info("UTF-8 not available, using platform default encoding for keyIdBytes."); } head.setSenderKID(new DEROctetString(keyIdBytes)); // SHA1 AlgorithmIdentifier owfAlg = new AlgorithmIdentifier(digestAlgId); // iterations, usually something like 1024 ASN1Integer iteration = new ASN1Integer(iterationCount); // HMAC/SHA1 AlgorithmIdentifier macAlg = new AlgorithmIdentifier(macAlgId); // We need some random bytes for the nonce byte[] saltbytes = createSenderNonce(); DEROctetString derSalt = new DEROctetString(saltbytes); // Create the new protected return message //String objectId = "1.2.840.113533.7.66.13" = passwordBasedMac; String objectId = CMPObjectIdentifiers.passwordBasedMac.getId(); PBMParameter pp = new PBMParameter(derSalt, owfAlg, iteration, macAlg); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(new ASN1ObjectIdentifier(objectId), pp); head.setProtectionAlg(pAlg); // Calculate the protection bits byte[] rasecret = raSecret.getBytes(); byte[] basekey = new byte[rasecret.length + saltbytes.length]; System.arraycopy(rasecret, 0, basekey, 0, rasecret.length); System.arraycopy(saltbytes, 0, basekey, rasecret.length, saltbytes.length); // Construct the base key according to rfc4210, section 5.1.3.1 MessageDigest dig = MessageDigest.getInstance(owfAlg.getAlgorithm().getId(), "BC"); for (int i = 0; i < iterationCount; i++) { basekey = dig.digest(basekey); dig.reset(); } PKIHeader pkiHeader = head.build(); // Do the mac String macOid = macAlg.getAlgorithm().getId(); byte[] protectedBytes = CmpMessageHelper.getProtectedBytes(pkiHeader, msg.getBody()); //ret.getProtectedBytes(); Mac mac = Mac.getInstance(macOid, "BC"); SecretKey key = new SecretKeySpec(basekey, macOid); mac.init(key); mac.reset(); mac.update(protectedBytes, 0, protectedBytes.length); byte[] out = mac.doFinal(); DERBitString bs = new DERBitString(out); if (LOG.isTraceEnabled()) { LOG.trace("<protectPKIMessageWithPBE()"); } // Return response as byte array return CmpMessageHelper .pkiMessageToByteArray(new PKIMessage(pkiHeader, msg.getBody(), bs, msg.getExtraCerts())); }
From source file:org.ejbca.core.protocol.cmp.CmpPbeVerifyer.java
License:Open Source License
public CmpPbeVerifyer(final PKIMessage msg) { final PKIHeader head = msg.getHeader(); protectedBytes = CmpMessageHelper.getProtectedBytes(msg); protection = msg.getProtection();//from w ww .jav a2 s .co m pAlg = head.getProtectionAlg(); final ASN1ObjectIdentifier algId = pAlg.getAlgorithm(); if (!StringUtils.equals(algId.getId(), CMPObjectIdentifiers.passwordBasedMac.getId())) { final String errMsg = "Protection algorithm id expected '" + CMPObjectIdentifiers.passwordBasedMac.getId() + "' (passwordBasedMac) but was '" + algId.getId() + "'."; throw new IllegalArgumentException(errMsg); } final PBMParameter pp = PBMParameter.getInstance(pAlg.getParameters()); iterationCount = pp.getIterationCount().getPositiveValue().intValue(); final AlgorithmIdentifier owfAlg = pp.getOwf(); // Normal OWF alg is 1.3.14.3.2.26 - SHA1 owfOid = owfAlg.getAlgorithm().getId(); final AlgorithmIdentifier macAlg = pp.getMac(); // Normal mac alg is 1.3.6.1.5.5.8.1.2 - HMAC/SHA1 macOid = macAlg.getAlgorithm().getId(); if (LOG.isDebugEnabled()) { LOG.debug("Protection type is: " + algId.getId()); LOG.debug("Iteration count is: " + iterationCount); LOG.debug("Owf type is: " + owfOid); LOG.debug("Mac type is: " + macOid); } salt = pp.getSalt().getOctets(); //log.info("Salt: "+new String(salt)); }
From source file:org.ejbca.core.protocol.cmp.CmpPbeVerifyer.java
License:Open Source License
public boolean verify(String raAuthenticationSecret) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException { lastUsedRaSecret = raAuthenticationSecret; boolean ret = false; // Verify the PasswordBased protection of the message if (!pAlg.getAlgorithm().equals(CMPObjectIdentifiers.passwordBasedMac)) { errMsg = INTRES.getLocalizedMessage("cmp.errorunknownprotalg", pAlg.getAlgorithm().getId()); LOG.error(errMsg);/* w ww.jav a 2 s . c om*/ return ret; } else { if (iterationCount > 10000) { LOG.info("Received message with too many iterations in PBE protection: " + iterationCount); throw new InvalidKeyException("Iteration count can not exceed 10000"); } byte[] raSecret = raAuthenticationSecret.getBytes(); byte[] basekey = new byte[raSecret.length + salt.length]; System.arraycopy(raSecret, 0, basekey, 0, raSecret.length); System.arraycopy(salt, 0, basekey, raSecret.length, salt.length); // Construct the base key according to rfc4210, section 5.1.3.1 MessageDigest dig = MessageDigest.getInstance(owfOid, "BC"); for (int i = 0; i < iterationCount; i++) { basekey = dig.digest(basekey); dig.reset(); } // HMAC/SHA1 is normal 1.3.6.1.5.5.8.1.2 or 1.2.840.113549.2.7 Mac mac = Mac.getInstance(macOid, "BC"); 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(); ret = Arrays.equals(out, pb); } return ret; }
From source file:org.ejbca.core.protocol.cmp.CmpResponseMessage.java
License:Open Source License
@Override public boolean create() throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException { boolean ret = false; // Some general stuff, common for all types of messages String issuer = null;/*ww w . j a v a 2 s. c o m*/ String subject = null; if (cert != null) { X509Certificate x509cert = (X509Certificate) cert; issuer = x509cert.getIssuerDN().getName(); subject = x509cert.getSubjectDN().getName(); } else if ((signCertChain != null) && (signCertChain.size() > 0)) { issuer = ((X509Certificate) signCertChain.iterator().next()).getSubjectDN().getName(); subject = "CN=fooSubject"; } else { issuer = "CN=fooIssuer"; subject = "CN=fooSubject"; } final GeneralName issuerName = new GeneralName(new X500Name(issuer)); final GeneralName subjectName = new GeneralName(new X500Name(subject)); final PKIHeaderBuilder myPKIHeader = CmpMessageHelper.createPKIHeaderBuilder(issuerName, subjectName, senderNonce, recipientNonce, transactionId); PKIBody myPKIBody = null; final PKIMessage myPKIMessage; try { if (status.equals(ResponseStatus.SUCCESS)) { if (cert != null) { if (log.isDebugEnabled()) { log.debug("Creating a CertRepMessage 'accepted'"); } PKIStatusInfo myPKIStatusInfo = new PKIStatusInfo(PKIStatus.granted); // 0 = accepted ASN1InputStream certASN1InputStream = new ASN1InputStream( new ByteArrayInputStream(cert.getEncoded())); ASN1InputStream cacertASN1InputStream = new ASN1InputStream( new ByteArrayInputStream(cacert.getEncoded())); try { try { CMPCertificate cmpcert = CMPCertificate.getInstance(certASN1InputStream.readObject()); CertOrEncCert retCert = new CertOrEncCert(cmpcert); CertifiedKeyPair myCertifiedKeyPair = new CertifiedKeyPair(retCert); CertResponse myCertResponse = new CertResponse(new ASN1Integer(requestId), myPKIStatusInfo, myCertifiedKeyPair, null); CertResponse[] certRespos = { myCertResponse }; CMPCertificate[] caPubs = { CMPCertificate.getInstance(cacertASN1InputStream.readObject()) }; CertRepMessage myCertRepMessage = new CertRepMessage(caPubs, certRespos); int respType = requestType + 1; // 1 = intitialization response, 3 = certification response etc if (log.isDebugEnabled()) { log.debug("Creating response body of type " + respType); } myPKIBody = new PKIBody(respType, myCertRepMessage); } finally { certASN1InputStream.close(); cacertASN1InputStream.close(); } } catch (IOException e) { throw new IllegalStateException("Unexpected IOException caught.", e); } } } else if (status.equals(ResponseStatus.FAILURE)) { if (log.isDebugEnabled()) { log.debug("Creating a CertRepMessage 'rejected'"); } // Create a failure message ASN1EncodableVector statusInfoV = new ASN1EncodableVector(); statusInfoV.add(ASN1Integer.getInstance(PKIStatus.rejection.toASN1Primitive())); if (failText != null) { statusInfoV.add(new PKIFreeText(new DERUTF8String(failText))); } statusInfoV.add(CmpMessageHelper.getPKIFailureInfo(failInfo.intValue())); PKIStatusInfo myPKIStatusInfo = PKIStatusInfo .getInstance(ASN1Sequence.getInstance(new DERSequence(statusInfoV))); myPKIBody = CmpMessageHelper.createCertRequestRejectBody(myPKIStatusInfo, requestId, requestType); } else { if (log.isDebugEnabled()) { log.debug("Creating a 'waiting' message?"); } // Not supported, lets create a PKIError failure instead // Create a failure message ASN1EncodableVector statusInfoV = new ASN1EncodableVector(); statusInfoV.add(PKIStatus.rejection); // 2 = rejection if (failText != null) { statusInfoV.add(new PKIFreeText(new DERUTF8String(failText))); } statusInfoV.add(CmpMessageHelper.getPKIFailureInfo(failInfo.intValue())); PKIStatusInfo myPKIStatusInfo = PKIStatusInfo.getInstance(new DERSequence(statusInfoV)); ErrorMsgContent myErrorContent = new ErrorMsgContent(myPKIStatusInfo); myPKIBody = new PKIBody(23, myErrorContent); // 23 = error } if ((pbeKeyId != null) && (pbeKey != null) && (pbeDigestAlg != null) && (pbeMacAlg != null)) { myPKIHeader.setProtectionAlg(new AlgorithmIdentifier(CMPObjectIdentifiers.passwordBasedMac)); PKIHeader header = myPKIHeader.build(); myPKIMessage = new PKIMessage(header, myPKIBody); responseMessage = CmpMessageHelper.protectPKIMessageWithPBE(myPKIMessage, pbeKeyId, pbeKey, pbeDigestAlg, pbeMacAlg, pbeIterationCount); } else { myPKIHeader.setProtectionAlg(new AlgorithmIdentifier(digest)); PKIHeader header = myPKIHeader.build(); myPKIMessage = new PKIMessage(header, myPKIBody); responseMessage = CmpMessageHelper.signPKIMessage(myPKIMessage, signCertChain, signKey, digest, provider); } ret = true; } catch (CertificateEncodingException e) { log.error("Error creating CertRepMessage: ", e); } catch (InvalidKeyException e) { log.error("Error creating CertRepMessage: ", e); } catch (NoSuchProviderException e) { log.error("Error creating CertRepMessage: ", e); } catch (NoSuchAlgorithmException e) { log.error("Error creating CertRepMessage: ", e); } catch (SecurityException e) { log.error("Error creating CertRepMessage: ", e); } catch (SignatureException e) { log.error("Error creating CertRepMessage: ", e); } return ret; }
From source file:org.ejbca.core.protocol.cmp.CmpRevokeResponseMessage.java
License:Open Source License
@Override public boolean create() throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException { final PKIHeaderBuilder myPKIHeader = CmpMessageHelper.createPKIHeaderBuilder(getSender(), getRecipient(), getSenderNonce(), getRecipientNonce(), getTransactionId()); PKIStatusInfo myPKIStatusInfo = new PKIStatusInfo(PKIStatus.granted); // 0 = accepted if (status != ResponseStatus.SUCCESS && status != ResponseStatus.GRANTED_WITH_MODS) { if (log.isDebugEnabled()) { log.debug("Creating a rejection message"); }/*from w w w .j a v a 2 s .c om*/ myPKIStatusInfo = new PKIStatusInfo(PKIStatus.rejection, null, CmpMessageHelper.getPKIFailureInfo(failInfo.intValue())); if (failText != null && failInfo != null) { myPKIStatusInfo = new PKIStatusInfo(PKIStatus.rejection, new PKIFreeText(failText), CmpMessageHelper.getPKIFailureInfo(failInfo.intValue())); } } RevRepContentBuilder revBuilder = new RevRepContentBuilder(); revBuilder.add(myPKIStatusInfo); RevRepContent myRevrepMessage = revBuilder.build(); PKIBody myPKIBody = new PKIBody(CmpPKIBodyConstants.REVOCATIONRESPONSE, myRevrepMessage); PKIMessage myPKIMessage; if ((getPbeDigestAlg() != null) && (getPbeMacAlg() != null) && (getPbeKeyId() != null) && (getPbeKey() != null)) { myPKIHeader.setProtectionAlg(new AlgorithmIdentifier(CMPObjectIdentifiers.passwordBasedMac)); myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody); responseMessage = CmpMessageHelper.protectPKIMessageWithPBE(myPKIMessage, getPbeKeyId(), getPbeKey(), getPbeDigestAlg(), getPbeMacAlg(), getPbeIterationCount()); } else { myPKIHeader.setProtectionAlg(new AlgorithmIdentifier(digestAlg)); myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody); try { responseMessage = CmpMessageHelper.signPKIMessage(myPKIMessage, signCertChain, signKey, digestAlg, provider); } catch (CertificateEncodingException e) { log.error("Failed to sign CMPRevokeResponseMessage"); log.error(e.getLocalizedMessage(), e); responseMessage = getUnprotectedResponseMessage(myPKIMessage); } catch (SecurityException e) { log.error("Failed to sign CMPRevokeResponseMessage"); log.error(e.getLocalizedMessage(), e); responseMessage = getUnprotectedResponseMessage(myPKIMessage); } catch (SignatureException e) { log.error("Failed to sign CMPRevokeResponseMessage"); log.error(e.getLocalizedMessage(), e); responseMessage = getUnprotectedResponseMessage(myPKIMessage); } } return true; }
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)/*from ww w .j a va2 s .c om*/ 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)); }