use of javax.crypto.EncryptedPrivateKeyInfo in project robovm by robovm.
the class EncryptedPrivateKeyInfoTest method test_ROUNDTRIP_GetKeySpecCipher02.
/**
* Encrypted data contains invalid PKCS8 key info encoding
*/
public final void test_ROUNDTRIP_GetKeySpecCipher02() {
boolean performed = false;
for (int i = 0; i < algName.length; i++) {
try {
// generate test data
TestDataGenerator g = new TestDataGenerator(algName[i][0], algName[i][1], privateKeyInfoDamaged, null);
// create test object
EncryptedPrivateKeyInfo epki;
if (g.ap() == null) {
epki = new EncryptedPrivateKeyInfo(algName[i][0], g.ct());
} else {
epki = new EncryptedPrivateKeyInfo(g.ap(), g.ct());
}
// call methods under test
try {
epki.getKeySpec(g.c());
// must not get here because decrypted data does
// not represent valid PKCS8 encoding
fail(algName[i][0] + ", " + algName[i][1]);
} catch (InvalidKeySpecException ok) {
}
performed = true;
} catch (TestDataGenerator.AllowedFailure allowedFailure) {
} catch (NoSuchAlgorithmException allowedFailure) {
}
}
assertTrue("Test not performed", performed);
}
use of javax.crypto.EncryptedPrivateKeyInfo in project robovm by robovm.
the class EncryptedPrivateKeyInfoTest method testGetAlgParameters04.
/**
* Test #4 for <code>getAlgParameters()</code> method <br>
* Assertion: returns the algorithm parameters <br>
* Test preconditions: test object created using ctor which takes
* AlgorithmParameters and encrypted data as a parameters; <br>
* Expected: the same algorithm parameters as ones passed to the ctor must be
* returned
*
* @throws IOException
*/
public final void testGetAlgParameters04() throws IOException {
boolean performed = false;
for (int i = 0; i < EncryptedPrivateKeyInfoData.algName0.length; i++) {
try {
AlgorithmParameters ap = AlgorithmParameters.getInstance(EncryptedPrivateKeyInfoData.algName0[i][0]);
// use pregenerated AlgorithmParameters encodings
ap.init(EncryptedPrivateKeyInfoData.getParametersEncoding(EncryptedPrivateKeyInfoData.algName0[i][0]));
EncryptedPrivateKeyInfo epki = new EncryptedPrivateKeyInfo(ap, EncryptedPrivateKeyInfoData.encryptedData);
// check that method under test returns
// the same parameters instance
assertSame(ap, epki.getAlgParameters());
performed = true;
} catch (NoSuchAlgorithmException allowedFailure) {
}
}
assertTrue("Test not performed", performed);
}
use of javax.crypto.EncryptedPrivateKeyInfo in project robovm by robovm.
the class EncryptedPrivateKeyInfoTest method test_getAlgName.
public void test_getAlgName() {
boolean performed = false;
for (int i = 0; i < algName.length; i++) {
try {
// generate test data
TestDataGenerator g = new TestDataGenerator(algName[i][0], algName[i][1], privateKeyInfoDamaged, null);
// create test object
EncryptedPrivateKeyInfo epki;
if (g.ap() == null) {
epki = new EncryptedPrivateKeyInfo(algName[i][0], g.ct());
} else {
epki = new EncryptedPrivateKeyInfo(g.ap(), g.ct());
}
// call methods under test
if (algName[i].length == 3) {
assertEquals(algName[i][2], epki.getAlgName());
}
performed = true;
} catch (TestDataGenerator.AllowedFailure allowedFailure) {
} catch (NoSuchAlgorithmException allowedFailure) {
}
}
assertTrue("Test not performed", performed);
}
use of javax.crypto.EncryptedPrivateKeyInfo in project graylog2-server by Graylog2.
the class PemKeyStore method generateKeySpec.
/**
* Generates a key specification for an (encrypted) private key.
*
* @param password characters, if {@code null} or empty an unencrypted key is assumed
* @param key bytes of the DER encoded private key
* @return a key specification
* @throws IOException if parsing {@code key} fails
* @throws NoSuchAlgorithmException if the algorithm used to encrypt {@code key} is unkown
* @throws NoSuchPaddingException if the padding scheme specified in the decryption algorithm is unkown
* @throws InvalidKeySpecException if the decryption key based on {@code password} cannot be generated
* @throws InvalidKeyException if the decryption key based on {@code password} cannot be used to decrypt
* {@code key}
* @throws InvalidAlgorithmParameterException if decryption algorithm parameters are somehow faulty
*/
protected static PKCS8EncodedKeySpec generateKeySpec(char[] password, byte[] key) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidKeyException, InvalidAlgorithmParameterException {
if (password == null || password.length == 0) {
return new PKCS8EncodedKeySpec(key);
}
final EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(key);
final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(encryptedPrivateKeyInfo.getAlgName());
final PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
final SecretKey pbeKey = keyFactory.generateSecret(pbeKeySpec);
@SuppressWarnings("InsecureCryptoUsage") final Cipher cipher = Cipher.getInstance(encryptedPrivateKeyInfo.getAlgName());
cipher.init(Cipher.DECRYPT_MODE, pbeKey, encryptedPrivateKeyInfo.getAlgParameters());
return encryptedPrivateKeyInfo.getKeySpec(cipher);
}
use of javax.crypto.EncryptedPrivateKeyInfo in project nhin-d by DirectProject.
the class CertificatesController method addCertificate.
@PreAuthorize("hasRole('ROLE_ADMIN')")
@RequestMapping(value = "/addcertificate", method = RequestMethod.POST)
public ModelAndView addCertificate(@RequestHeader(value = "X-Requested-With", required = false) String requestedWith, HttpSession session, @ModelAttribute CertificateForm certificateForm, Model model, @RequestParam(value = "submitType") String actionPath) {
final ModelAndView mav = new ModelAndView();
String strid = "";
//if (log.isDebugEnabled())
log.error("Enter domain/addcertificate");
if (actionPath.equalsIgnoreCase("cancel")) {
if (log.isDebugEnabled())
log.debug("trying to cancel from saveupdate");
final SearchDomainForm form2 = (SearchDomainForm) session.getAttribute("searchDomainForm");
model.addAttribute(form2 != null ? form2 : new SearchDomainForm());
model.addAttribute("ajaxRequest", AjaxUtils.isAjaxRequest(requestedWith));
mav.setViewName("main");
mav.addObject("privKeyTypeList", PrivateKeyType.getPrivKeyTypeList());
mav.addObject("statusList", EntityStatus.getEntityStatusList());
return mav;
}
if (actionPath.equalsIgnoreCase("newcertificate") || actionPath.equalsIgnoreCase("add certificate")) {
log.debug("Attempting to add certificate");
if (this.keyManager == null)
log.debug("Key manager is null");
else
log.debug("Key manager is non-null");
strid = "" + certificateForm.getId();
// insert the new address into the Domain list of Addresses
final EntityStatus estatus = certificateForm.getStatus();
if (log.isDebugEnabled())
log.debug("beginning to evaluate filedata");
try {
model.addAttribute("certerror", false);
model.addAttribute("passphraseError", false);
if (!certificateForm.getFileData().isEmpty()) {
final String passphrase = (certificateForm.getKeyPassphrase() == null) ? "" : certificateForm.getKeyPassphrase();
PrivateKeyType privKeyType = PrivateKeyType.fromString(certificateForm.getPrivKeyType());
if ((privKeyType == PrivateKeyType.PKCS8_PASSPHRASE || privKeyType == PrivateKeyType.PKCS_12_PASSPHRASE) && StringUtils.isEmpty(passphrase)) {
// can't move on if a passphrase is required and one is not supplied
model.addAttribute("passphraseError", true);
} else {
byte[] certOrP12Bytes = certificateForm.getFileData().getBytes();
byte[] privateKeyBytes = null;
if (privKeyType == PrivateKeyType.PKCS_12_PASSPHRASE || privKeyType == PrivateKeyType.PKCS_12_UNPROTECTED) {
log.debug("Converting byte stream to cert container");
// there is a private key present.. normalized it to an unproted format
//if (cont.getKey() != null)
//{
log.debug("Private key exists; normalizing to non-protected p12 format.");
certOrP12Bytes = CertUtils.changePkcs12Protection(certOrP12Bytes, passphrase.toCharArray(), passphrase.toCharArray(), "".toCharArray(), "".toCharArray());
//}
} else if (privKeyType != PrivateKeyType.NONE) {
// there is a private key file associated with this request
privateKeyBytes = certificateForm.getPrivKeyData().getBytes();
// get the private key... it may be different formats, so be on the watch
if (privKeyType == PrivateKeyType.PKCS8_PASSPHRASE) {
// key
try {
final EncryptedPrivateKeyInfo encryptPKInfo = new EncryptedPrivateKeyInfo(privateKeyBytes);
final Cipher cipher = Cipher.getInstance(encryptPKInfo.getAlgName());
final PBEKeySpec pbeKeySpec = new PBEKeySpec(passphrase.toCharArray());
final SecretKeyFactory secFac = SecretKeyFactory.getInstance(encryptPKInfo.getAlgName());
final Key pbeKey = secFac.generateSecret(pbeKeySpec);
final AlgorithmParameters algParams = encryptPKInfo.getAlgParameters();
cipher.init(Cipher.DECRYPT_MODE, pbeKey, algParams);
final KeySpec pkcs8KeySpec = encryptPKInfo.getKeySpec(cipher);
final KeyFactory kf = KeyFactory.getInstance("RSA");
privateKeyBytes = kf.generatePrivate(pkcs8KeySpec).getEncoded();
} catch (Exception e) {
return mav;
}
}
}
String owner = "";
final String fileType = certificateForm.getFileData().getContentType();
if (!fileType.matches("application/x-x509-ca-cert") && !fileType.matches("application/octet-stream") && !fileType.matches("application/x-pkcs12")) {
model.addAttribute("certerror", true);
} else {
final Certificate cert = new Certificate();
// convert the cert and key to the proper storage format
cert.setData(toCertDataFormat(certOrP12Bytes, privateKeyBytes, privKeyType));
cert.setOwner(owner);
cert.setStatus(org.nhindirect.config.model.EntityStatus.valueOf(estatus.toString()));
final ArrayList<Certificate> certlist = new ArrayList<Certificate>();
certlist.add(cert);
log.debug("Adding certificate to config store.");
certService.addCertificate(cert);
log.debug("Certificate add SUCCESSFUL");
}
}
} else {
if (log.isDebugEnabled())
log.debug("DO NOT store the certificate into database BECAUSE THERE IS NO FILE");
}
} catch (ServiceException ed) {
log.error(ed);
} catch (Exception e) {
log.error(e);
e.printStackTrace();
}
// certificate form and result
try {
final Collection<Certificate> certs = certService.getAllCertificates();
if (this.keyManager != null && this.keyManager instanceof MutableKeyStoreProtectionManager) {
final KeyStore keyStore = ((MutableKeyStoreProtectionManager) keyManager).getKS();
// the key store manager to see if they have private keys
for (Certificate cert : certs) {
if (!cert.isPrivateKey()) {
try {
final X509Certificate checkCert = CertUtils.toX509Certificate(cert.getData());
final String alias = keyStore.getCertificateAlias(checkCert);
if (!StringUtils.isEmpty(alias)) {
// check if this entry has a private key associated with
// it
final PrivateKey privKey = (PrivateKey) keyStore.getKey(alias, "".toCharArray());
if (privKey != null)
cert.setPrivateKey(true);
}
} catch (Exception e) {
}
}
}
}
model.addAttribute("certificatesResults", certs);
final CertificateForm cform = new CertificateForm();
cform.setId(0);
model.addAttribute("certificateForm", cform);
} catch (ServiceException e1) {
e1.printStackTrace();
}
model.addAttribute("ajaxRequest", AjaxUtils.isAjaxRequest(requestedWith));
final SimpleForm simple = new SimpleForm();
simple.setId(Long.parseLong(strid));
model.addAttribute("simpleForm", simple);
mav.setViewName("certificates");
// the Form's default button action
final String action = "Update";
model.addAttribute("action", action);
model.addAttribute("ajaxRequest", AjaxUtils.isAjaxRequest(requestedWith));
mav.addObject("privKeyTypeList", PrivateKeyType.getPrivKeyTypeList());
mav.addObject("statusList", EntityStatus.getEntityStatusList());
}
return mav;
}
Aggregations