Search in sources :

Example 1 with EncryptedData

use of com.mindbright.security.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);
    }
}
Also used : Ticket(sun.security.krb5.internal.Ticket) KerberosTicket(javax.security.auth.kerberos.KerberosTicket) KerberosPrincipal(javax.security.auth.kerberos.KerberosPrincipal) ServiceCreds(sun.security.jgss.krb5.ServiceCreds) EncryptionKey(sun.security.krb5.EncryptionKey) PrincipalName(sun.security.krb5.PrincipalName) IOException(java.io.IOException) EncTicketPart(sun.security.krb5.internal.EncTicketPart) KrbException(sun.security.krb5.KrbException) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException) KerberosKey(javax.security.auth.kerberos.KerberosKey) KrbException(sun.security.krb5.KrbException) EncryptedData(sun.security.krb5.EncryptedData)

Example 2 with EncryptedData

use of com.mindbright.security.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");
    }
}
Also used : InvalidBERException(org.mozilla.jss.asn1.InvalidBERException) OCTET_STRING(org.mozilla.jss.asn1.OCTET_STRING) ContentInfo(org.mozilla.jss.pkcs7.ContentInfo) EncryptedContentInfo(org.mozilla.jss.pkcs7.EncryptedContentInfo) SEQUENCE(org.mozilla.jss.asn1.SEQUENCE) EncryptedData(org.mozilla.jss.pkcs7.EncryptedData) EncryptedContentInfo(org.mozilla.jss.pkcs7.EncryptedContentInfo) ASN1Template(org.mozilla.jss.asn1.ASN1Template)

Example 3 with EncryptedData

use of com.mindbright.security.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);
    }
}
Also used : ContentInfo(org.mozilla.jss.pkcs7.ContentInfo) EncryptedContentInfo(org.mozilla.jss.pkcs7.EncryptedContentInfo) JSSSecureRandom(org.mozilla.jss.crypto.JSSSecureRandom) EncryptedData(org.mozilla.jss.pkcs7.EncryptedData) CharConversionException(java.io.CharConversionException) EncryptedContentInfo(org.mozilla.jss.pkcs7.EncryptedContentInfo)

Example 4 with EncryptedData

use of com.mindbright.security.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;
    }
}
Also used : ASN1OctetString(com.mindbright.asn1.ASN1OctetString) PFX(com.mindbright.security.pkcs12.PFX) ASN1DER(com.mindbright.asn1.ASN1DER) ByteArrayInputStream(java.io.ByteArrayInputStream) ContentInfo(com.mindbright.security.pkcs7.ContentInfo) PKCS12PbeParams(com.mindbright.security.pkcs12.PKCS12PbeParams) AuthenticatedSafe(com.mindbright.security.pkcs12.AuthenticatedSafe) ASN1OctetString(com.mindbright.asn1.ASN1OctetString) ASN1CharString(com.mindbright.asn1.ASN1CharString) EncryptedData(com.mindbright.security.pkcs7.EncryptedData) IOException(java.io.IOException)

Aggregations

IOException (java.io.IOException)2 ContentInfo (org.mozilla.jss.pkcs7.ContentInfo)2 EncryptedContentInfo (org.mozilla.jss.pkcs7.EncryptedContentInfo)2 EncryptedData (org.mozilla.jss.pkcs7.EncryptedData)2 ASN1CharString (com.mindbright.asn1.ASN1CharString)1 ASN1DER (com.mindbright.asn1.ASN1DER)1 ASN1OctetString (com.mindbright.asn1.ASN1OctetString)1 AuthenticatedSafe (com.mindbright.security.pkcs12.AuthenticatedSafe)1 PFX (com.mindbright.security.pkcs12.PFX)1 PKCS12PbeParams (com.mindbright.security.pkcs12.PKCS12PbeParams)1 ContentInfo (com.mindbright.security.pkcs7.ContentInfo)1 EncryptedData (com.mindbright.security.pkcs7.EncryptedData)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 CharConversionException (java.io.CharConversionException)1 PrivilegedActionException (java.security.PrivilegedActionException)1 KerberosKey (javax.security.auth.kerberos.KerberosKey)1 KerberosPrincipal (javax.security.auth.kerberos.KerberosPrincipal)1 KerberosTicket (javax.security.auth.kerberos.KerberosTicket)1 ASN1Template (org.mozilla.jss.asn1.ASN1Template)1 InvalidBERException (org.mozilla.jss.asn1.InvalidBERException)1