use of java.security.AlgorithmParameters in project jdk8u_jdk by JetBrains.
the class RC2AlgorithmParameters method testParams.
private static byte[] testParams(AlgorithmParameters rc2Params, RC2ParameterSpec rc2Spec) throws Exception {
// test getParameterSpec returns object equal to input
rc2Params.init(rc2Spec);
RC2ParameterSpec rc2OtherSpec = (RC2ParameterSpec) rc2Params.getParameterSpec(RC2ParameterSpec.class);
if (!rc2Spec.equals(rc2OtherSpec)) {
throw new Exception("AlgorithmParameterSpecs should be equal");
}
// test RC2ParameterSpec with RC2 Cipher
Cipher rc2Cipher = Cipher.getInstance("RC2/CBC/PKCS5PADDING", "SunJCE");
rc2Cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec("secret".getBytes("ASCII"), "RC2"), rc2Spec);
// get IV
byte[] iv = rc2Cipher.getIV();
if (!Arrays.equals(iv, rc2Spec.getIV())) {
throw new Exception("ivs should be equal");
}
// test encoding and decoding
byte[] encoded = rc2Params.getEncoded();
AlgorithmParameters params = AlgorithmParameters.getInstance("RC2");
params.init(encoded);
// test RC2 AlgorithmParameters with RC2 Cipher
rc2Cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec("secret".getBytes("ASCII"), "RC2"), params);
// get IV
iv = rc2Cipher.getIV();
if (!Arrays.equals(iv, rc2Spec.getIV())) {
throw new Exception("ivs should be equal");
}
return encoded;
}
use of java.security.AlgorithmParameters in project jdk8u_jdk by JetBrains.
the class PKCS12SameKeyId method main.
public static void main(String[] args) throws Exception {
// Prepare a JKS keystore with many entries
new File(JKSFILE).delete();
for (int i = 0; i < SIZE; i++) {
System.err.print(".");
String cmd = "-keystore " + JKSFILE + " -storepass changeit -keypass changeit -keyalg rsa " + "-genkeypair -alias p" + i + " -dname CN=" + i;
sun.security.tools.keytool.Main.main(cmd.split(" "));
}
// Prepare EncryptedPrivateKeyInfo parameters, copied from various
// places in PKCS12KeyStore.java
AlgorithmParameters algParams = AlgorithmParameters.getInstance("PBEWithSHA1AndDESede");
algParams.init(new PBEParameterSpec("12345678".getBytes(), 1024));
AlgorithmId algid = new AlgorithmId(new ObjectIdentifier("1.2.840.113549.1.12.1.3"), algParams);
PBEKeySpec keySpec = new PBEKeySpec(PASSWORD);
SecretKeyFactory skFac = SecretKeyFactory.getInstance("PBE");
SecretKey skey = skFac.generateSecret(keySpec);
Cipher cipher = Cipher.getInstance("PBEWithSHA1AndDESede");
cipher.init(Cipher.ENCRYPT_MODE, skey, algParams);
// Pre-calculated keys and certs and aliases
byte[][] keys = new byte[SIZE][];
Certificate[][] certChains = new Certificate[SIZE][];
String[] aliases = new String[SIZE];
// Reads from JKS keystore and pre-calculate
KeyStore ks = KeyStore.getInstance("jks");
try (FileInputStream fis = new FileInputStream(JKSFILE)) {
ks.load(fis, PASSWORD);
}
for (int i = 0; i < SIZE; i++) {
aliases[i] = "p" + i;
byte[] enckey = cipher.doFinal(ks.getKey(aliases[i], PASSWORD).getEncoded());
keys[i] = new EncryptedPrivateKeyInfo(algid, enckey).getEncoded();
certChains[i] = ks.getCertificateChain(aliases[i]);
}
// Write into PKCS12 keystore. Use this overloaded version of
// setKeyEntry() to be as fast as possible, so that they would
// have same localKeyId.
KeyStore p12 = KeyStore.getInstance("pkcs12");
p12.load(null, PASSWORD);
for (int i = 0; i < SIZE; i++) {
p12.setKeyEntry(aliases[i], keys[i], certChains[i]);
}
try (FileOutputStream fos = new FileOutputStream(P12FILE)) {
p12.store(fos, PASSWORD);
}
// Check private keys still match certs
p12 = KeyStore.getInstance("pkcs12");
try (FileInputStream fis = new FileInputStream(P12FILE)) {
p12.load(fis, PASSWORD);
}
for (int i = 0; i < SIZE; i++) {
String a = "p" + i;
X509Certificate x = (X509Certificate) p12.getCertificate(a);
X500Name name = (X500Name) x.getSubjectDN();
if (!name.getCommonName().equals("" + i)) {
throw new Exception(a + "'s cert is " + name);
}
}
}
use of java.security.AlgorithmParameters in project jdk8u_jdk by JetBrains.
the class CipherInputStreamExceptions method cbc_shortStream.
/* Check that close() does not throw an exception with full message in
* CipherInputStream's ibuffer.
* This test:
* 1) Encrypts a 97 byte message with AES/CBC/PKCS5Padding
* 2) Create a stream that sends 96 bytes.
* 3) Read stream once,
* 4) Close and expect no exception
*/
static void cbc_shortStream() throws Exception {
Cipher c;
AlgorithmParameters params;
byte[] read = new byte[200];
System.out.println("Running cbc_shortStream");
// Encrypt 97 byte with AES/CBC/PKCS5Padding
byte[] ct = encryptedText("CBC", 97);
// Create stream with only 96 bytes of encrypted data
CipherInputStream in = getStream("CBC", ct, 96);
try {
int size = in.read(read);
in.close();
if (size != 80) {
throw new RuntimeException("Fail: CipherInputStream.read() " + "returned " + size + ". Should have been 80");
}
System.out.println(" Pass.");
} catch (IOException e) {
System.out.println(" Fail: " + e.getMessage());
throw new RuntimeException(e.getCause());
}
}
use of java.security.AlgorithmParameters in project jdk8u_jdk by JetBrains.
the class TestDSAGenParameterSpec method testDSAGenParameterSpec.
private static void testDSAGenParameterSpec(DataTuple dataTuple) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidParameterSpecException, InvalidAlgorithmParameterException {
System.out.printf("Test case: primePLen=%d, " + "subprimeQLen=%d%n", dataTuple.primePLen, dataTuple.subprimeQLen);
AlgorithmParameterGenerator apg = AlgorithmParameterGenerator.getInstance(ALGORITHM_NAME, PROVIDER_NAME);
DSAGenParameterSpec genParamSpec = createGenParameterSpec(dataTuple);
// genParamSpec will be null if IllegalAE is thrown when expected.
if (genParamSpec == null) {
return;
}
try {
apg.init(genParamSpec, null);
AlgorithmParameters param = apg.generateParameters();
checkParam(param, genParamSpec);
System.out.println("Test case passed");
} catch (InvalidParameterException ipe) {
// implementation in SUN doesn't
if (!dataTuple.isSunProviderSupported) {
System.out.println("Test case passed: expected " + "InvalidParameterException is caught");
} else {
throw new RuntimeException("Test case failed.", ipe);
}
}
}
use of java.security.AlgorithmParameters 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