📄 keystoregui.java
字号:
if (keyFile == null)
return; // nothing to do.
/* Read the file data into a byte array */
FileInputStream in = new FileInputStream(keyFile);
byte [] buffer = new byte[(int) (keyFile.length())];
in.read(buffer);
in.close();
/* check if this is pem base64 encoded data - if it is, translate it */
if (CBSecurity.isPEM(buffer))
{
//TODO: XXX <your code to handle encrypted private keys here> XXX//
byte[] pemData = CBSecurity.convertFromPEM(buffer, new String(CBSecurity.PEM_KEY_HEADER).getBytes());
if (pemData != null)
buffer = pemData;
else
{
CBUtility.error(CBIntText.get("Unable to load key: does not begin with {0} ", new String[] {new String(CBSecurity.PEM_KEY_HEADER)}));
return;
}
}
/* check that the user has entered a valid passphrase */
if (checkPassword() == false)
return; // nothing to do.
/* import key */
String alias = certItem.getAlias();
java.security.cert.Certificate[] certChain = keystore.getCertificateChain(alias);
//XXX <your code to handle unencrypted private keys here> XXX//
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
KeyFactory factory = KeyFactory.getInstance("RSA");
PrivateKey key = factory.generatePrivate(keySpec);
if (certChain == null || certChain.length == 0) // ...which it often does, since cert
{ // chains often aren't stored properly
certChain = new java.security.cert.Certificate[1]; // in the keystore
certChain[0] = certItem.getX509Cert();
}
keystore.setKeyEntry(alias, key, password, certChain);
refreshView();
changed = true;
}
catch (Exception e)
{
CBUtility.error("Error importing key file.", e);
e.printStackTrace();
}
}
/**
* Allows the user to export a private key with a particular certificate.
* (Currently limited to pkcs 8 - other may be possible depending on keystore
* implementation).
* @param certItem the certificate whose private key is to be exported.
*/
protected void exportKey(CertItem certItem)
{
try
{
/* Check that the user has selected a certificate to associate with the new key */
if (certItem == null || certItem.getX509Cert() == null)
{
CBUtility.error(CBIntText.get("Please select a certificate to match with a key."), null);
return;
}
/* Get the user to select a pkcs 8 private key file */
File keyFile = getKeyFile(CBIntText.get("Select a file to save the pkcs8 key to."));
if (keyFile == null)
return; // nothing to do.
/* check that the user has entered a valid passphrase */
if (checkPassword() == false)
return; // nothing to do.
/* read key from keystore */
Key myKey = keystore.getKey(certItem.getAlias(), password);
if (myKey == null)
{
return;
}
byte[] data = myKey.getEncoded();
if (data == null)
{
throw new Exception("Unable to access encoded private key data");
}
if (keyFile.toString().toLowerCase().endsWith(".pem"))
{
data = CBSecurity.convertToPEMPrivateKey(data);
}
FileOutputStream out = new FileOutputStream(keyFile);
out.write(data);
out.close();
}
catch (Exception e)
{
CBUtility.error("Error exporting key file.", e);
e.printStackTrace();
}
}
/**
* This prompts the user to select a pkcs8 file to import, and
* attach to an existing certificate.
* @return the File name of the selected pkcs8 file.
*/
protected File getKeyFile(String title)
{
JFileChooser chooser = new JFileChooser(properties.getProperty("cert.homeDir"));
chooser.addChoosableFileFilter(new CBFileFilter(new String[] {"der", "pem"},"Certificate Files (*.der, *.pem)"));
chooser.setDialogTitle(title);
int option = chooser.showOpenDialog(owner);
while (true)
{
if (option == JFileChooser.APPROVE_OPTION) // only do something if user chose 'ok'
{
File keyFile = chooser.getSelectedFile();
if (keyFile == null)
CBUtility.error(CBIntText.get("Please select a file"));
else
{
properties.setProperty("cert.homeDir", keyFile.getParent());
chooser = null;
return keyFile;
}
}
else
{
chooser = null;
return null; // user selected cancel, or closed the window.
}
}
}
/**
* Uses the CertViewer to display the contents of the selected
* certificate.
* @param cert the certificate to display.
*/
protected void viewCurrentCert(CertItem cert)
{
if (cert == null || cert.getX509Cert() == null) // nothing to do.
{
CBUtility.error(CBIntText.get("Please select a certificate to view."), null);
return;
}
CertViewer viewer = new CertViewer(owner, cert.getX509Cert());
viewer.setVisible(true);
}
/**
* Checks the list to see which the currently selected certificate is,
* and then prompts the user to confirm the deletion.
* @param certItem the certificate to delete.
*/
protected void deleteCurrentCert(CertItem certItem)
{
if (certItem == null)
return; // nothing to do.
int delete = JOptionPane.showConfirmDialog(this, CBIntText.get("delete certificate: {0} ?", new String[] {certItem.getAlias()}),
CBIntText.get("Confirm Certificate Deletion"), JOptionPane.OK_CANCEL_OPTION);
if (delete != JOptionPane.OK_OPTION)
return; // nothing to do
if (keystore == null) // ? Can't see how this would happen
{
CBUtility.error(CBIntText.get("Internal Error: unable to find Certificate Keystore"), null);
return;
}
if (checkPassword() == false)
return; // nothing to do.
try
{
keystore.deleteEntry(certItem.getAlias());
refreshView();
changed = true;
return;
/* DEFER
if (writeKeyStore(password, keystore, keystoreFile) == true)
{
refreshView();
return; // SUCCESS!!!
}
*/
}
catch (KeyStoreException e)
{
CBUtility.error(CBIntText.get("Error - unable to delete key: {0} from key store", new String[] {certItem.getAlias()}), e);
}
// FAILURE!!!
try // try to reset entry in local keystore
{
keystore.setCertificateEntry(certItem.getAlias(), certItem.getX509Cert());
}
catch (Exception e)
{
log.log(Level.WARNING, "unable to recover key store.",e);
}
}
/**
* checks that the user has entered a valid password. If they haven't,
* it prompts for one.
* @return whether a valid password has been entered and checked against
* the keystore.
*/
protected boolean checkPassword()
{
if (password != null)
return true; // we already have a password.
return setupPasswordAndKeystore(keystoreType, keystoreFile, this); // we don't, so try to get one...
}
/**
* <p>This allows the user to enter their password, which remains valid
* for the life of this component. </p>
*
* <p>This also sets up the keystore</p>
* @return whether the password successfully opened the keystore.
*/
public boolean setupPasswordAndKeystore(String keystoreType, String keystoreFile, Component owner)
{
if ((password != null) && (keystore != null)) // no thanks, we already have one...
return true;
String message = CBIntText.get("Enter Key Store Password");
while ((password = getPassword(owner, message)) != null)
{
keystore = readKeyStore(password, keystoreType, keystoreFile);
if (keystore != null)
{
return true; // we have a valid keystore!
}
// this message is only displayed if we go around the loop again.
message = CBIntText.get("Password incorrect. Please try again.");
}
return false; // user hasn't entered a password and has cancelled out.
}
public static char[] getPassword(Component owner, String message)
{
char[] password;
JPasswordField passwordInput = new JPasswordField();
int response = JOptionPane.showConfirmDialog(owner, passwordInput,
message, JOptionPane.OK_CANCEL_OPTION);
if (response != JOptionPane.OK_OPTION)
password = null; // give up, go home
else
password = passwordInput.getPassword();
return password;
}
/**
* Sets up the keystore variable, using the
* current password (may be null) and keystore file.
*/
/*
public static boolean setupKeyStore(char[] password, KeyStore keyStore, String keyStoreType, String keyStoreFile)
{
KeyStore newKeystore = readKeyStore(password, keyStoreType, keyStoreFile);
if (newKeystore == null)
{
return false;
}
else
{
keyStore = newKeystore;
return true;
}
}
*/
/**
* Checks if the given alias name already exists in the
* Keystore.
*/
private boolean listContains(String aliasName)
{
if (aliasName == null) return false;
for (int i=0; i<certListModel.size(); i++)
if (aliasName.equals(((CertItem)certListModel.get(i)).alias))
return true;
return false;
}
/**
* Allows the User to browse to a new Cert (on disk) and
* import it.
*/
protected void addNewCert()
{
CertViewer.CertAndFileName info = CertViewer.loadCertificate(owner);
if (info == null || info.cert == null)
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -