use of org.mozilla.jss.pkcs7.EncryptedData in project jdk8u_jdk by JetBrains.
the class KerberosClientKeyExchangeImpl method init.
/**
* Creates an instance of KerberosClientKeyExchange from its ASN.1 encoding.
* Used by ServerHandshaker to verify and obtain premaster secret.
*
* @param protocolVersion current protocol version
* @param clientVersion version requested by client in its ClientHello;
* used by premaster secret version check
* @param rand random number generator used for generating random
* premaster secret if ticket and/or premaster verification fails
* @param input inputstream from which to get ASN.1-encoded KerberosWrapper
* @param acc the AccessControlContext of the handshaker
* @param serviceCreds server's creds
*/
@Override
public void init(ProtocolVersion protocolVersion, ProtocolVersion clientVersion, SecureRandom rand, HandshakeInStream input, AccessControlContext acc, Object serviceCreds) throws IOException {
// Read ticket
encodedTicket = input.getBytes16();
if (debug != null && Debug.isOn("verbose")) {
Debug.println(System.out, "encoded Kerberos service ticket", encodedTicket);
}
EncryptionKey sessionKey = null;
try {
Ticket t = new Ticket(encodedTicket);
EncryptedData encPart = t.encPart;
PrincipalName ticketSname = t.sname;
final ServiceCreds creds = (ServiceCreds) serviceCreds;
final KerberosPrincipal princ = new KerberosPrincipal(ticketSname.toString());
// For bound service, permission already checked at setup
if (creds.getName() == null) {
SecurityManager sm = System.getSecurityManager();
try {
if (sm != null) {
// Eliminate dependency on ServicePermission
sm.checkPermission(Krb5Helper.getServicePermission(ticketSname.toString(), "accept"), acc);
}
} catch (SecurityException se) {
serviceCreds = null;
// Do not destroy keys. Will affect Subject
if (debug != null && Debug.isOn("handshake")) {
System.out.println("Permission to access Kerberos" + " secret key denied");
}
throw new IOException("Kerberos service not allowedy");
}
}
KerberosKey[] serverKeys = AccessController.doPrivileged(new PrivilegedAction<KerberosKey[]>() {
@Override
public KerberosKey[] run() {
return creds.getKKeys(princ);
}
});
if (serverKeys.length == 0) {
throw new IOException("Found no key for " + princ + (creds.getName() == null ? "" : (", this keytab is for " + creds.getName() + " only")));
}
/*
* permission to access and use the secret key of the Kerberized
* "host" service is done in ServerHandshaker.getKerberosKeys()
* to ensure server has the permission to use the secret key
* before promising the client
*/
// See if we have the right key to decrypt the ticket to get
// the session key.
int encPartKeyType = encPart.getEType();
Integer encPartKeyVersion = encPart.getKeyVersionNumber();
KerberosKey dkey = null;
try {
dkey = findKey(encPartKeyType, encPartKeyVersion, serverKeys);
} catch (KrbException ke) {
// a kvno mismatch
throw new IOException("Cannot find key matching version number", ke);
}
if (dkey == null) {
// %%% Should print string repr of etype
throw new IOException("Cannot find key of appropriate type" + " to decrypt ticket - need etype " + encPartKeyType);
}
EncryptionKey secretKey = new EncryptionKey(encPartKeyType, dkey.getEncoded());
// Decrypt encPart using server's secret key
byte[] bytes = encPart.decrypt(secretKey, KeyUsage.KU_TICKET);
// Reset data stream after decryption, remove redundant bytes
byte[] temp = encPart.reset(bytes);
EncTicketPart encTicketPart = new EncTicketPart(temp);
// Record the Kerberos Principals
peerPrincipal = new KerberosPrincipal(encTicketPart.cname.getName());
localPrincipal = new KerberosPrincipal(ticketSname.getName());
sessionKey = encTicketPart.key;
if (debug != null && Debug.isOn("handshake")) {
System.out.println("server principal: " + ticketSname);
System.out.println("cname: " + encTicketPart.cname.toString());
}
} catch (IOException e) {
throw e;
} catch (Exception e) {
if (debug != null && Debug.isOn("handshake")) {
System.out.println("KerberosWrapper error getting session key," + " generating random secret (" + e.getMessage() + ")");
}
sessionKey = null;
}
// XXX Read and ignore authenticator
input.getBytes16();
if (sessionKey != null) {
preMaster = new KerberosPreMasterSecret(protocolVersion, clientVersion, rand, input, sessionKey);
} else {
// Generate bogus premaster secret
preMaster = new KerberosPreMasterSecret(clientVersion, rand);
}
}
use of org.mozilla.jss.pkcs7.EncryptedData in project jss by dogtagpki.
the class AuthenticatedSafes method getSafeContentsAt.
/**
* Returns the SafeContents at the given index in the AuthenticatedSafes,
* decrypting it if necessary.
*
* <p>The algorithm used to extract encrypted SafeContents does not
* conform to version 1.0 of the spec. Instead, it conforms to the
* draft 1.0 spec, because this is what Communicator and MSIE seem
* to conform to. This looks like an implementation error that has
* become firmly entrenched to preserve interoperability. The draft
* spec dictates that the encrypted content in the EncryptedContentInfo
* is the DER encoding of a SafeContents. This is simple enough. The
* 1.0 final spec says that the SafeContents is wrapped in a ContentInfo,
* then the ContentInfo is BER encoded, then the value octets (not the
* tag or length) are encrypted. No wonder people stayed with the old way.
*
* @param password The password to use to decrypt the SafeContents if
* it is encrypted. If the SafeContents is known to not be encrypted,
* this parameter can be null. If the password is incorrect, the
* decoding will fail somehow, probably with an InvalidBERException,
* BadPaddingException, or IllegalBlockSizeException.
* @param index The index of the SafeContents to extract.
* @return A SafeContents object, which is merely a
* SEQUENCE of SafeBags.
* @exception IllegalArgumentException If no password was provided,
* but the SafeContents is encrypted.
*/
public SEQUENCE getSafeContentsAt(Password password, int index) throws IllegalStateException, NotInitializedException, NoSuchAlgorithmException, InvalidBERException, IOException, InvalidKeyException, InvalidAlgorithmParameterException, TokenException, IllegalBlockSizeException, BadPaddingException {
ContentInfo ci = (ContentInfo) sequence.elementAt(index);
if (ci.getContentType().equals(ContentInfo.ENCRYPTED_DATA)) {
if (password == null) {
// can't decrypt if we don't have a password
throw new IllegalStateException("No password to decode " + "encrypted SafeContents");
}
EncryptedContentInfo encCI = ((EncryptedData) ci.getInterpretedContent()).getEncryptedContentInfo();
// this should be a BER-encoded SafeContents
byte[] decrypted = encCI.decrypt(password, new PasswordConverter());
try {
SEQUENCE.OF_Template seqt = new SEQUENCE.OF_Template(SafeBag.getTemplate());
return (SEQUENCE) ASN1Util.decode(seqt, decrypted);
} catch (InvalidBERException e) {
if (ACCEPT_SECURITY_DYNAMICS) {
// try the security dynamics approach
ContentInfo.Template cit = ContentInfo.getTemplate();
ci = (ContentInfo) ASN1Util.decode(cit, decrypted);
if (!ci.getContentType().equals(ContentInfo.DATA)) {
throw new InvalidBERException("");
}
OCTET_STRING os = (OCTET_STRING) ci.getInterpretedContent();
SEQUENCE.OF_Template seqt = new SEQUENCE.OF_Template(SafeBag.getTemplate());
return (SEQUENCE) ASN1Util.decode(seqt, os.toByteArray());
} else {
throw e;
}
}
} else if (ci.getContentType().equals(ContentInfo.DATA)) {
// This SafeContents is not encrypted
SEQUENCE.OF_Template seqt = new SEQUENCE.OF_Template(SafeBag.getTemplate());
return (SEQUENCE) ASN1Util.decode(seqt, ((OCTET_STRING) ci.getInterpretedContent()).toByteArray());
} else {
throw new InvalidBERException("AuthenticatedSafes element is" + " neither a Data or an EncryptedData");
}
}
use of org.mozilla.jss.pkcs7.EncryptedData in project jss by dogtagpki.
the class AuthenticatedSafes method addEncryptedSafeContents.
/**
* Encrypts a SafeContents and adds it to the AuthenticatedSafes.
*
* @param keyGenAlg The algorithm used to generate a key from the password.
* Must be a PBE algorithm. <code>DEFAULT_KEY_GEN_ALG</code> is
* usually fine here. It only provides 40-bit security, but if the
* private key material is packaged in its own
* <i>EncryptedPrivateKeyInfo</i>, the security of the SafeContents
* is not as important.
* @param password The password to use to generate the encryption key
* and IV.
* @param salt The salt to use to generate the key and IV. If null is
* passed in, the salt will be generated randomly, which is usually
* the right thing to do.
* @param iterationCount The number of hash iterations to perform when
* generating the key and IV. Use DEFAULT_ITERATIONS unless
* you want to be clever.
* @param safeContents A SafeContents, which is a SEQUENCE of SafeBags.
* Each element of the sequence must in fact be an instance of
* <code>SafeBag</code>.
*/
public void addEncryptedSafeContents(PBEAlgorithm keyGenAlg, Password password, byte[] salt, int iterationCount, SEQUENCE safeContents) throws NotInitializedException, InvalidKeyException, InvalidAlgorithmParameterException, TokenException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException {
try {
// generate salt if necessary
if (salt == null) {
// generate random salt
JSSSecureRandom rand = CryptoManager.getInstance().createPseudoRandomNumberGenerator();
salt = new byte[SALT_LENGTH];
rand.nextBytes(salt);
}
EncryptedContentInfo encCI = EncryptedContentInfo.createPBE(keyGenAlg, password, salt, iterationCount, new PasswordConverter(), ASN1Util.encode(safeContents));
EncryptedData encData = new EncryptedData(encCI);
ContentInfo ci = new ContentInfo(encData);
sequence.addElement(ci);
} catch (CharConversionException e) {
throw new RuntimeException("Unable to convert password: " + e.getMessage(), e);
}
}
use of org.mozilla.jss.pkcs7.EncryptedData in project SpringRemote by HaleyWang.
the class PKCS12KeyStore method engineLoad.
public void engineLoad(InputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException {
try {
ASN1DER ber = new ASN1DER();
PFX pfx = new PFX();
ber.decode(stream, pfx);
if (password == null) {
password = new char[0];
}
checkMac(pfx, password);
AuthenticatedSafe authSafe = new AuthenticatedSafe();
ASN1OctetString data = pfx.getDataContent();
ByteArrayInputStream ba = new ByteArrayInputStream(data.getRaw());
ber.decode(ba, authSafe);
for (int i = 0; i < authSafe.getCount(); i++) {
ContentInfo ci = authSafe.getContentInfo(i);
String cit = ci.contentType.getString();
if (cit.equals("1.2.840.113549.1.7.1")) {
data = (ASN1OctetString) ci.content.getValue();
processSafeContents(data.getRaw());
} else if (cit.equals("1.2.840.113549.1.7.6")) {
EncryptedData ed = (EncryptedData) ci.content.getValue();
String alg = ed.encryptedContentInfo.contentEncryptionAlgorithm.algorithmName();
byte[] enc = ed.encryptedContentInfo.encryptedContent.getRaw();
PKCS12PbeParams params = (PKCS12PbeParams) ed.encryptedContentInfo.contentEncryptionAlgorithm.parameters.getValue();
byte[] salt = params.salt.getRaw();
int iterations = params.iterations.getValue().intValue();
byte[] dec = new byte[enc.length];
doCipher(Cipher.DECRYPT_MODE, password, enc, enc.length, dec, salt, iterations, alg);
processSafeContents(dec);
} else {
throw new IOException("ContentInfo type not supported: " + cit);
}
}
} catch (IOException e) {
e.printStackTrace();
throw e;
}
}
Aggregations