Search in sources :

Example 36 with HexDumpEncoder

use of sun.misc.HexDumpEncoder in project jdk8u_jdk by JetBrains.

the class SignerInfo method toString.

public String toString() {
    HexDumpEncoder hexDump = new HexDumpEncoder();
    String out = "";
    out += "Signer Info for (issuer): " + issuerName + "\n";
    out += "\tversion: " + Debug.toHexString(version) + "\n";
    out += "\tcertificateSerialNumber: " + Debug.toHexString(certificateSerialNumber) + "\n";
    out += "\tdigestAlgorithmId: " + digestAlgorithmId + "\n";
    if (authenticatedAttributes != null) {
        out += "\tauthenticatedAttributes: " + authenticatedAttributes + "\n";
    }
    out += "\tdigestEncryptionAlgorithmId: " + digestEncryptionAlgorithmId + "\n";
    out += "\tencryptedDigest: " + "\n" + hexDump.encodeBuffer(encryptedDigest) + "\n";
    if (unauthenticatedAttributes != null) {
        out += "\tunauthenticatedAttributes: " + unauthenticatedAttributes + "\n";
    }
    return out;
}
Also used : HexDumpEncoder(sun.misc.HexDumpEncoder)

Example 37 with HexDumpEncoder

use of sun.misc.HexDumpEncoder in project jdk8u_jdk by JetBrains.

the class EngineInputRecord method read.

/*
     * Delineate or read a complete packet from src.
     *
     * If internal data (hs, alert, ccs), the data is read and
     * stored internally.
     *
     * If external data (app), return a new ByteBuffer which points
     * to the data to process.
     */
ByteBuffer read(ByteBuffer srcBB) throws IOException {
    /*
         * If we have anything besides application data,
         * or if we haven't even done the initial v2 verification,
         * we send this down to be processed by the underlying
         * internal cache.
         */
    if (!formatVerified || (srcBB.get(srcBB.position()) != ct_application_data)) {
        internalData = true;
        read(new ByteBufferInputStream(srcBB), (OutputStream) null);
        return tmpBB;
    }
    internalData = false;
    int srcPos = srcBB.position();
    int srcLim = srcBB.limit();
    ProtocolVersion recordVersion = ProtocolVersion.valueOf(srcBB.get(srcPos + 1), srcBB.get(srcPos + 2));
    // check the record version
    checkRecordVersion(recordVersion, false);
    /*
         * It's really application data.  How much to consume?
         * Jump over the header.
         */
    int len = bytesInCompletePacket(srcBB);
    assert (len > 0);
    if (debug != null && Debug.isOn("packet")) {
        try {
            HexDumpEncoder hd = new HexDumpEncoder();
            // Use copy of BB
            ByteBuffer bb = srcBB.duplicate();
            bb.limit(srcPos + len);
            System.out.println("[Raw read (bb)]: length = " + len);
            hd.encodeBuffer(bb, System.out);
        } catch (IOException e) {
        }
    }
    // Demarcate past header to end of packet.
    srcBB.position(srcPos + headerSize);
    srcBB.limit(srcPos + len);
    // Protect remainder of buffer, create slice to actually
    // operate on.
    ByteBuffer bb = srcBB.slice();
    srcBB.position(srcBB.limit());
    srcBB.limit(srcLim);
    return bb;
}
Also used : HexDumpEncoder(sun.misc.HexDumpEncoder)

Example 38 with HexDumpEncoder

use of sun.misc.HexDumpEncoder in project jdk8u_jdk by JetBrains.

the class CipherBox method decrypt.

/*
     * Decrypts a block of data, returning the size of the
     * resulting block if padding was required.
     *
     * For SSLv3 and TLSv1.0, with block ciphers in CBC mode the
     * Initialization Vector (IV) for the first record is generated by
     * the handshake protocol, the IV for subsequent records is the
     * last ciphertext block from the previous record.
     *
     * From TLSv1.1, the implicit IV is replaced with an explicit IV to
     * protect against CBC attacks.
     *
     * Differentiating between bad_record_mac and decryption_failed alerts
     * may permit certain attacks against CBC mode. It is preferable to
     * uniformly use the bad_record_mac alert to hide the specific type of
     * the error.
     */
int decrypt(byte[] buf, int offset, int len, int tagLen) throws BadPaddingException {
    if (cipher == null) {
        return len;
    }
    try {
        int newLen;
        if (cipherType == AEAD_CIPHER) {
            try {
                newLen = cipher.doFinal(buf, offset, len, buf, offset);
            } catch (IllegalBlockSizeException ibse) {
                // unlikely to happen
                throw new RuntimeException("Cipher error in AEAD mode in JCE provider " + cipher.getProvider().getName(), ibse);
            }
        } else {
            newLen = cipher.update(buf, offset, len, buf, offset);
            if (newLen != len) {
                // catch BouncyCastle buffering error
                throw new RuntimeException("Cipher buffering error " + "in JCE provider " + cipher.getProvider().getName());
            }
        }
        if (debug != null && Debug.isOn("plaintext")) {
            try {
                HexDumpEncoder hd = new HexDumpEncoder();
                System.out.println("Padded plaintext after DECRYPTION:  len = " + newLen);
                hd.encodeBuffer(new ByteArrayInputStream(buf, offset, newLen), System.out);
            } catch (IOException e) {
            }
        }
        if (cipherType == BLOCK_CIPHER) {
            int blockSize = cipher.getBlockSize();
            newLen = removePadding(buf, offset, newLen, tagLen, blockSize, protocolVersion);
            if (protocolVersion.v >= ProtocolVersion.TLS11.v) {
                if (newLen < blockSize) {
                    throw new BadPaddingException("invalid explicit IV");
                }
            }
        }
        return newLen;
    } catch (ShortBufferException e) {
        // unlikely to happen, we should have enough buffer space here
        throw new ArrayIndexOutOfBoundsException(e.toString());
    }
}
Also used : HexDumpEncoder(sun.misc.HexDumpEncoder) ByteArrayInputStream(java.io.ByteArrayInputStream) IOException(java.io.IOException)

Example 39 with HexDumpEncoder

use of sun.misc.HexDumpEncoder in project jdk8u_jdk by JetBrains.

the class CipherBox method decrypt.

/*
     * Decrypts a block of data, returning the size of the
     * resulting block if padding was required.  position and limit
     * point to the end of the decrypted/depadded data.  The initial
     * limit and new limit may be different, given we may
     * have stripped off some padding bytes.
     *
     *  @see decrypt(byte[], int, int)
     */
int decrypt(ByteBuffer bb, int tagLen) throws BadPaddingException {
    int len = bb.remaining();
    if (cipher == null) {
        bb.position(bb.limit());
        return len;
    }
    try {
        /*
             * Decrypt "in-place".
             */
        int pos = bb.position();
        ByteBuffer dup = bb.duplicate();
        int newLen;
        if (cipherType == AEAD_CIPHER) {
            try {
                newLen = cipher.doFinal(dup, bb);
            } catch (IllegalBlockSizeException ibse) {
                // unlikely to happen
                throw new RuntimeException("Cipher error in AEAD mode \"" + ibse.getMessage() + " \"in JCE provider " + cipher.getProvider().getName());
            }
        } else {
            newLen = cipher.update(dup, bb);
            if (newLen != len) {
                // catch BouncyCastle buffering error
                throw new RuntimeException("Cipher buffering error " + "in JCE provider " + cipher.getProvider().getName());
            }
        }
        // reset the limit to the end of the decryted data
        bb.limit(pos + newLen);
        if (debug != null && Debug.isOn("plaintext")) {
            try {
                HexDumpEncoder hd = new HexDumpEncoder();
                System.out.println("Padded plaintext after DECRYPTION:  len = " + newLen);
                hd.encodeBuffer((ByteBuffer) bb.duplicate().position(pos), System.out);
            } catch (IOException e) {
            }
        }
        /*
             * Remove the block padding.
             */
        if (cipherType == BLOCK_CIPHER) {
            int blockSize = cipher.getBlockSize();
            bb.position(pos);
            newLen = removePadding(bb, tagLen, blockSize, protocolVersion);
            // check the explicit IV of TLS v1.1 or later
            if (protocolVersion.v >= ProtocolVersion.TLS11.v) {
                if (newLen < blockSize) {
                    throw new BadPaddingException("invalid explicit IV");
                }
                // reset the position to the end of the decrypted data
                bb.position(bb.limit());
            }
        }
        return newLen;
    } catch (ShortBufferException e) {
        // unlikely to happen, we should have enough buffer space here
        throw new ArrayIndexOutOfBoundsException(e.toString());
    }
}
Also used : HexDumpEncoder(sun.misc.HexDumpEncoder) IOException(java.io.IOException)

Example 40 with HexDumpEncoder

use of sun.misc.HexDumpEncoder in project jdk8u_jdk by JetBrains.

the class Krb5Context method initSecContext.

/**
     * Initiator context establishment call. This method may be
     * required to be called several times. A CONTINUE_NEEDED return
     * call indicates that more calls are needed after the next token
     * is received from the peer.
     *
     * @param is contains the token received from the peer. On the
     *  first call it will be ignored.
     * @return any token required to be sent to the peer
     *    It is responsibility of the caller
     *    to send the token to its peer for processing.
     * @exception GSSException
     */
public final byte[] initSecContext(InputStream is, int mechTokenSize) throws GSSException {
    byte[] retVal = null;
    InitialToken token = null;
    int errorCode = GSSException.FAILURE;
    if (DEBUG) {
        System.out.println("Entered Krb5Context.initSecContext with " + "state=" + printState(state));
    }
    if (!isInitiator()) {
        throw new GSSException(GSSException.FAILURE, -1, "initSecContext on an acceptor " + "GSSContext");
    }
    try {
        if (state == STATE_NEW) {
            state = STATE_IN_PROCESS;
            errorCode = GSSException.NO_CRED;
            if (myCred == null) {
                myCred = Krb5InitCredential.getInstance(caller, myName, GSSCredential.DEFAULT_LIFETIME);
            } else if (!myCred.isInitiatorCredential()) {
                throw new GSSException(errorCode, -1, "No TGT available");
            }
            myName = (Krb5NameElement) myCred.getName();
            Credentials tgt;
            final Krb5ProxyCredential second;
            if (myCred instanceof Krb5InitCredential) {
                second = null;
                tgt = ((Krb5InitCredential) myCred).getKrb5Credentials();
            } else {
                second = (Krb5ProxyCredential) myCred;
                tgt = second.self.getKrb5Credentials();
            }
            checkPermission(peerName.getKrb5PrincipalName().getName(), "initiate");
            /*
                     * If useSubjectCredsonly is true then
                     * we check whether we already have the ticket
                     * for this service in the Subject and reuse it
                     */
            final AccessControlContext acc = AccessController.getContext();
            if (GSSUtil.useSubjectCredsOnly(caller)) {
                KerberosTicket kerbTicket = null;
                try {
                    // get service ticket from caller's subject
                    kerbTicket = AccessController.doPrivileged(new PrivilegedExceptionAction<KerberosTicket>() {

                        public KerberosTicket run() throws Exception {
                            // instead of Krb5Util.getTicket
                            return Krb5Util.getTicket(GSSCaller.CALLER_UNKNOWN, // don't worry about the null
                            second == null ? myName.getKrb5PrincipalName().getName() : second.getName().getKrb5PrincipalName().getName(), peerName.getKrb5PrincipalName().getName(), acc);
                        }
                    });
                } catch (PrivilegedActionException e) {
                    if (DEBUG) {
                        System.out.println("Attempt to obtain service" + " ticket from the subject failed!");
                    }
                }
                if (kerbTicket != null) {
                    if (DEBUG) {
                        System.out.println("Found service ticket in " + "the subject" + kerbTicket);
                    }
                    // convert Ticket to serviceCreds
                    // XXX Should merge these two object types
                    // avoid converting back and forth
                    serviceCreds = Krb5Util.ticketToCreds(kerbTicket);
                }
            }
            if (serviceCreds == null) {
                // Subject or useSubjectCreds is false
                if (DEBUG) {
                    System.out.println("Service ticket not found in " + "the subject");
                }
                // Get Service ticket using the Kerberos protocols
                if (second == null) {
                    serviceCreds = Credentials.acquireServiceCreds(peerName.getKrb5PrincipalName().getName(), tgt);
                } else {
                    serviceCreds = Credentials.acquireS4U2proxyCreds(peerName.getKrb5PrincipalName().getName(), second.tkt, second.getName().getKrb5PrincipalName(), tgt);
                }
                if (GSSUtil.useSubjectCredsOnly(caller)) {
                    final Subject subject = AccessController.doPrivileged(new java.security.PrivilegedAction<Subject>() {

                        public Subject run() {
                            return (Subject.getSubject(acc));
                        }
                    });
                    if (subject != null && !subject.isReadOnly()) {
                        /*
                             * Store the service credentials as
                             * javax.security.auth.kerberos.KerberosTicket in
                             * the Subject. We could wait till the context is
                             * succesfully established; however it is easier
                             * to do here and there is no harm indoing it here.
                             */
                        final KerberosTicket kt = Krb5Util.credsToTicket(serviceCreds);
                        AccessController.doPrivileged(new java.security.PrivilegedAction<Void>() {

                            public Void run() {
                                subject.getPrivateCredentials().add(kt);
                                return null;
                            }
                        });
                    } else {
                        // log it for debugging purpose
                        if (DEBUG) {
                            System.out.println("Subject is " + "readOnly;Kerberos Service " + "ticket not stored");
                        }
                    }
                }
            }
            errorCode = GSSException.FAILURE;
            token = new InitSecContextToken(this, tgt, serviceCreds);
            apReq = ((InitSecContextToken) token).getKrbApReq();
            retVal = token.encode();
            myCred = null;
            if (!getMutualAuthState()) {
                state = STATE_DONE;
            }
            if (DEBUG) {
                System.out.println("Created InitSecContextToken:\n" + new HexDumpEncoder().encodeBuffer(retVal));
            }
        } else if (state == STATE_IN_PROCESS) {
            // No need to write anything;
            // just validate the incoming token
            new AcceptSecContextToken(this, serviceCreds, apReq, is);
            serviceCreds = null;
            apReq = null;
            state = STATE_DONE;
        } else {
            // XXX Use logging API?
            if (DEBUG) {
                System.out.println(state);
            }
        }
    } catch (KrbException e) {
        if (DEBUG) {
            e.printStackTrace();
        }
        GSSException gssException = new GSSException(errorCode, -1, e.getMessage());
        gssException.initCause(e);
        throw gssException;
    } catch (IOException e) {
        GSSException gssException = new GSSException(errorCode, -1, e.getMessage());
        gssException.initCause(e);
        throw gssException;
    }
    return retVal;
}
Also used : PrivilegedActionException(java.security.PrivilegedActionException) PrivilegedExceptionAction(java.security.PrivilegedExceptionAction) IOException(java.io.IOException) Subject(javax.security.auth.Subject) AccessControlContext(java.security.AccessControlContext) HexDumpEncoder(sun.misc.HexDumpEncoder)

Aggregations

HexDumpEncoder (sun.misc.HexDumpEncoder)51 IOException (java.io.IOException)15 ByteArrayInputStream (java.io.ByteArrayInputStream)6 CRLException (java.security.cert.CRLException)4 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3 CertificateException (java.security.cert.CertificateException)3 NamingException (javax.naming.NamingException)3 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 InvalidKeyException (java.security.InvalidKeyException)2 NoSuchProviderException (java.security.NoSuchProviderException)2 SignatureException (java.security.SignatureException)2 X509CRLEntry (java.security.cert.X509CRLEntry)2 PRF (sun.security.ssl.CipherSuite.PRF)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 Constructor (java.lang.reflect.Constructor)1 ByteBuffer (java.nio.ByteBuffer)1 AccessControlContext (java.security.AccessControlContext)1 GeneralSecurityException (java.security.GeneralSecurityException)1 PrivilegedActionException (java.security.PrivilegedActionException)1