viernes, 22 de mayo de 2020

CTF: FluxFingers4Future - Evil Corp Solution

For this years hack.lu CTF I felt like creating a challenge. Since I work a lot with TLS it was only natural for me to create a TLS challenge. I was informed that TLS challenges are quite uncommon but nevertheless I thought it would be nice to spice the competition up with something "unusual". The challenge mostly requires you to know a lot of details on how the TLS record layer and the key derivation works. The challenge was only solved by one team (0ops from China) during the CTF. Good job!



So let me introduce the challenge first.

The Challenge


You were called by the incident response team of Evil-Corp, the urgently need your help. Somebody broke into the main server of the company, bricked the device and stole all the files! Nothing is left! This should have been impossible. The hacker used some secret backdoor to bypass authentication. Without the knowledge of the secret backdoor other servers are at risk as well! The incident response team has a full packet capture of the incident and performed an emergency cold boot attack on the server to retrieve the contents of the memory (its a really important server, Evil Corp is always ready for such kinds of incidents). However they were unable to retrieve much information from the RAM, what's left is only some parts of the "key_block" of the TLS server. Can you help Evil-Corp to analyze the exploit the attacker used?

(Flag is inside of the attackers' secret message).


TT = Could not recover

key_block:
6B 4F 93 6A TT TT TT TT  TT TT 00 D9 F2 9B 4C B0
2D 88 36 CF B0 CB F1 A6  7B 53 B2 00 B6 D9 DC EF
66 E6 2C 33 5D 89 6A 92  ED D9 7C 07 49 57 AD E1
TT TT TT TT TT TT TT TT  56 C6 D8 3A TT TT TT TT
TT TT TT TT TT TT TT TT  94 TT 0C EB 50 8D 81 C4
E4 40 B6 26 DF E3 40 9A  6C F3 95 84 E6 C5 86 40
49 FD 4E F2 A0 A3 01 06

If you are not interested in the solution and want to try the challenge on your own first, do not read past this point. Spoilers ahead.


The Solution

So lets analyze first what we got. We have something called a "key_block" but we do not have all parts of it. Some of the bytes have been destroyed and are unknown to us. Additionally, we have a PCAP file with some weird messages in them. Lets look at the general structure of the message exchange first.



So looking at the IP address and TCP ports we see that the attacker/client was 127.0.0.1:36674 and was talking with the Server 127.0.0.1:4433. When looking at the individual messages we can see that the message exchange looked something like this:

ENC HS MESSAGE .... ENC HS MESSAGE ->
<- SERVER HELLO, CERTIFICATE, SERVER HELLO DONE
ENC HS MESSAGE .... ENC HS MESSAGE CCS ENC HS MESSAGE, ENC HS MESSAGE ->
<-CCS, ENC HS MESSAGE
ENC HEARTBEAT ->
<- ENC HEARTBEAT
-> ENC APPLICATION DATA
<- INTERNAL ERROR ... INTERNAL ERROR

So this message exchange appears weird. Usually the client is supposed to send a ClientHello in the beginning of the connection, and not encrypted handshake messages. The same is true for the second flight of the client. Usually it transmits its ClientKeyExchange message here, then a ChangeCipherSpec message and finally its Finished message. If we click at the first flight of the client, we can also see some ASCII text fragments in its messages.

Furthermore we can assume that the message sent after the ChangeCipherSpec from the server is actually a TLS Finished message.

Since we cannot read a lot from the messages the client is sending (in Wireshark at least), we can look at the messages the server is sending to get a better hold of what is going on. In the ServerHello message the server selects the parameters for the connection. This reveals that this is indeed a TLS 1.1 connection with TLS_RSA_WITH_AES_256_CBC_SHA , no compression and the Heartbeat Extension negotiated. We can also see that the ServerRandom is: 1023047c60b420bb3321d9d47acb933dbe70399bf6c92da33af01d4fb770e98c (note that it is always 32 bytes long, the UNIX time is part of the ServerRandom).

Looking at the certificate the server sent we can see that the server used a self-signed certificate for Evil.corp.com with an 800-bit RSA modulus:

00ad87f086a4e1acd255d1d77324a05ea7d250f285f3a6de35b9f07c5d083add5166677425b8335328255e7b562f944d55c56ff084f4316fdc9e3f5b009fefd65015a5ca228c94e3fd35c6aba83ea4e20800a34548aa36a5d40e3c7496c65bdbc864e8f161

and the public exponent 65537.


If you pay very close attention to the handshake you can see another weird thing. The size of the exchanged HeartbeatMessages is highly uneven. The client/attacker sent 3500 bytes, the server is supposed to decrypt these messages, and reflect the contents of them. However, the Server sent ~64000 bytes instead. The heartbeat extension became surprisingly well known in 2014, due to the Heartbleed bug in OpenSSL. The bug causes a buffer over-read on the server, causing it to reflect parts of its memory content in return to malicious heartbeat requests. This is a good indicator that this bug might play a role in this challenge.

But what is this key_block thing we got from the incident response team? TLS 1.1 CBC uses 4 symmetric keys in total. Both parties derive these keys from the "master secret" as the key_block. This key_block is then chunked into the individual keys. You can imagine the key_block as some PRF output and both parties knowing which parts of the output to use for which individual key. In TLS 1.1 CBC the key_block is chunked as follows: The first N bytes are the client_write_MAC key, the next N bytes are the server_write_MAC key, the next P bytes are the client_write key and the last P bytes are the server_write key. N is the length of the HMAC key (which is at the time of writing for all cipher suites the length of the HMAC) and P is the length of the key for the block cipher.

In the present handshake AES-256 was negotiated as the block cipher and SHA (SHA-1) was negotiated for the HMAC. This means that N is 20 (SHA-1 is 20 bytes) and P is 32 (AES-256 requires 32 bytes of key material).

Looking at the given key_block we can chunk it into the individual keys:
client_write_MAC = 6B4F936ATTTTTTTTTTTT00D9F29B4CB02D8836CF
server_write_MAC = B0CBF1A67B53B200B6D9DCEF66E62C335D896A92
client_write = EDD97C074957ADE1TTTTTTTTTTTTTTTT56C6D83ATTTTTTTTTTTTTTTTTTTTTTTT
server_write = 94TT0CEB508D81C4E440B626DFE3409A6CF39584E6C5864049FD4EF2A0A30106

Since not all parts of the key_block are present, we can see that we actually have 14/20 bytes of the client_write_MAC key, the whole server_write_MAC key, 12/32 bytes of the client_write key and 31/32 bytes of the server_write key.

The client_write_MAC key is used in the HMAC computations from the client to the server (the server uses the same key to verify the HMAC),
The server_write_MAC key is used in the HMAC computations from the server to the client (the client uses the same key to verify the HMAC),
The client_write key is used to encrypt messages from the client to the server, while the server_write key is used to encrypt messages from the server to the client.

So looking at the keys we could compute HMAC's from the client if we could guess the remaining 6 bytes. We could compute HMAC's from the server directly, we have not enough key material to decrypt the client messages, but we could decrypt server messages if we brute-forced one byte of the server_write key. But how would you brute force this byte? When do we know when we got the correct key? Lets look at how the TLS record layer works to find out :)

The Record Layer

TLS consists out of multiple protocols (Handshake, Alert, CCS, Application (and Heartbeat)). If one of those protocols wants to send any data, it has to pass this data to the record layer. The record layer will chunk this data, compress it if necessary, encrypt it and attach a "record header" to it.


This means, that if we want to decrypt a message we know that if we used the correct key the message should always have a correct padding. If we are unsure we could even check the HMAC with the server_write_MAC key.

In TLS 1.0 - TLS 1.2 the padding looks like this:

1 byte padding  : 00
2 bytes padding: 01 01
3 bytes padding: 02 02 02
4 bytes padding: 03 03 03 03
...

So if we guessed the correct key we know that the plaintext has to have valid padding.
An ideal candidate for our brute force attack is the server Finished message. So lets use that to check our key guesses.
The ciphertext looks like this:
0325f41d3ebaf8986da712c82bcd4d55c3bb45c1bc2eacd79e2ea13041fc66990e217bdfe4f6c25023381bab9ddc8749535973bd4cacc7a4140a14d78cc9bddd


The first 16 bytes of the ciphertext are the IV:
IV: 0325f41d3ebaf8986da712c82bcd4d55
Therefore the actual ciphertext is:
Ciphertext: c3bb45c1bc2eacd79e2ea13041fc66990e217bdfe4f6c25023381bab9ddc8749535973bd4cacc7a4140a14d78cc9bddd

The 256 key candidates are quick to check, and it is revealed that 0xDC was the missing byte.
(The plaintext of the Finished is 1400000C455379AAA141E1B9410B413320C435DEC948BFA451C64E4F30FE5F6928B816CA0B0B0B0B0B0B0B0B0B0B0B0B)

Now that we have the full server_write key we can use it to decrypt the heartbeat records.

This is done in the same way as with the Finished. Looking at the decrypted heartbeat messages we can see a lot of structured data, which is an indicator that we are actually dealing
with the Heartbleed bug. If we convert the content of the heartbeat messages to ASCII we can actually see that the private key of the server is PEM encoded in the first heartbeat message.

Note: This is different to a real heartbeat exploit. Here you don't usually get the private key nicely encoded but have to extract it using the coppersmith's attack or similar things. I did not want to make this challenge even harder so I was so nice to write it to the memory for you :)


The private key within the Heartbeat messages looks like this:
-----BEGIN RSA PRIVATE KEY-----
MIIB3gIBAAJlAK2H8Iak4azSVdHXcySgXqfSUPKF86beNbnwfF0IOt1RZmd0Jbgz
UyglXntWL5RNVcVv8IT0MW/cnj9bAJ/v1lAVpcoijJTj/TXGq6g+pOIIAKNFSKo2
pdQOPHSWxlvbyGTo8WECAwEAAQJkJj95P2QmLb5qlgbj5SXH1zufBeWKb7Q4qVQd
RTAkMVXYuWK7UZ9Wa9nYulyjvg9RoWOO+SaDNqhiTWKosQ+ZrvG3A1TDMcVZSkPx
bXCuhhRpp4j0T9levQi0s8tR1YuFzVFi8QIzANNLrgK2YOJiDlyu78t/eVbBey4m
uh2xaxvEd8xGX4bIBlTuWlKIqwPNxE8fygmv4uHFAjMA0j7Uk1ThY+UCYdeCm4/P
eVqkPYu7jNTHG2TGr/B6hstxyFpXBlq6MJQ/qPdRXLkLFu0CMwCf/OLCTQPpBiQn
y5HoPRpMNW4m0M4F46vdN5MaCoMUU+pvbpbXfYI3/BrTapeZZCNfnQIzAJ7XzW9K
j8cTPIuDcS/qpQvAiZneOmKaV5vAtcQzYb75cgu3BUzNuyH8v2P/Br+RJmm5AjMA
jp9N+xdEm4dW51lyUp6boVU6fxZimfYRfYANU2bVFmbsSAU9jzjWb0BuXexKKcX7
XGo=
-----END RSA PRIVATE KEY-----

We should store it in a file and decode it with OpenSSL to get the actual key material.

>> openssl rsa -in key.pem -text -noout
RSA Private-Key: (800 bit, 2 primes)
modulus:
    00:ad:87:f0:86:a4:e1:ac:d2:55:d1:d7:73:24:a0:
    5e:a7:d2:50:f2:85:f3:a6:de:35:b9:f0:7c:5d:08:
    3a:dd:51:66:67:74:25:b8:33:53:28:25:5e:7b:56:
    2f:94:4d:55:c5:6f:f0:84:f4:31:6f:dc:9e:3f:5b:
    00:9f:ef:d6:50:15:a5:ca:22:8c:94:e3:fd:35:c6:
    ab:a8:3e:a4:e2:08:00:a3:45:48:aa:36:a5:d4:0e:
    3c:74:96:c6:5b:db:c8:64:e8:f1:61
publicExponent: 65537 (0x10001)
privateExponent:
    26:3f:79:3f:64:26:2d:be:6a:96:06:e3:e5:25:c7:
    d7:3b:9f:05:e5:8a:6f:b4:38:a9:54:1d:45:30:24:
    31:55:d8:b9:62:bb:51:9f:56:6b:d9:d8:ba:5c:a3:
    be:0f:51:a1:63:8e:f9:26:83:36:a8:62:4d:62:a8:
    b1:0f:99:ae:f1:b7:03:54:c3:31:c5:59:4a:43:f1:
    6d:70:ae:86:14:69:a7:88:f4:4f:d9:5e:bd:08:b4:
    b3:cb:51:d5:8b:85:cd:51:62:f1
prime1:
    00:d3:4b:ae:02:b6:60:e2:62:0e:5c:ae:ef:cb:7f:
    79:56:c1:7b:2e:26:ba:1d:b1:6b:1b:c4:77:cc:46:
    5f:86:c8:06:54:ee:5a:52:88:ab:03:cd:c4:4f:1f:
    ca:09:af:e2:e1:c5
prime2:
    00:d2:3e:d4:93:54:e1:63:e5:02:61:d7:82:9b:8f:
    cf:79:5a:a4:3d:8b:bb:8c:d4:c7:1b:64:c6:af:f0:
    7a:86:cb:71:c8:5a:57:06:5a:ba:30:94:3f:a8:f7:
    51:5c:b9:0b:16:ed
exponent1:
    00:9f:fc:e2:c2:4d:03:e9:06:24:27:cb:91:e8:3d:
    1a:4c:35:6e:26:d0:ce:05:e3:ab:dd:37:93:1a:0a:
    83:14:53:ea:6f:6e:96:d7:7d:82:37:fc:1a:d3:6a:
    97:99:64:23:5f:9d
exponent2:
    00:9e:d7:cd:6f:4a:8f:c7:13:3c:8b:83:71:2f:ea:
    a5:0b:c0:89:99:de:3a:62:9a:57:9b:c0:b5:c4:33:
    61:be:f9:72:0b:b7:05:4c:cd:bb:21:fc:bf:63:ff:
    06:bf:91:26:69:b9
coefficient:
    00:8e:9f:4d:fb:17:44:9b:87:56:e7:59:72:52:9e:
    9b:a1:55:3a:7f:16:62:99:f6:11:7d:80:0d:53:66:
    d5:16:66:ec:48:05:3d:8f:38:d6:6f:40:6e:5d:ec:
    4a:29:c5:fb:5c:6a

So now we got the private key. But what do we do with it? Since this is an RSA handshake we should be able to decrypt the whole session (RSA is not perfect forward secure). Loading it into Wireshark does not work, as Wireshark is unable to read the messages sent by the client. What is going on there?

De-fragmentation


So if you do not yet have a good idea of what the record layer is for, you can imagine it like envelops. If someone wants to send some bytes, you have to put them in an envelop and transmit them. Usually implementations use one big envelop for every message, however you can also send a single message in multiple envelops.

The attacker did exactly that. He fragmented its messages into multiple records. This is not very common for handshake messages but fine according to the specification and accepted by almost all implementations. However, Wireshark is unable to decode these kinds of messages and therefore unable to use our private key to decrypt the connection. So we have to do this step manually.

So each record has the following fields:
Type | Version | Length | Data
If we want to reconstruct the ClientHello message we have to get all the data fields of the records of the first flight and decode them.
This is simply done by clicking on each record in Wireshark and concatenating the data fields. This step is at least on my Wireshark version (3.0.5) not very easy as the copying is actually buggy, and Wireshark is not copying the correct bytes.

 As you can see in the image, the record is supposed to have a length of 8 bytes, but Wireshark is only copying 4 bytes. I am not sure if this bug is actually only in my version or affects all Wireshark versions. Instead of copying the records individually I therefore copied the whole TCP payload and chunked it manually into the individual records.

16030200080100009e03020000
160302000800000000004e6f62
16030200086f64796b6e6f7773
1603020008696d616361740000
16030200080000000000002053
1603020008746f70206c6f6f6b
1603020008696e67206e6f7468
1603020008696e6720746f2066
1603020008696e646865726500
16030200080200350100005300
16030200080f00010113370015
16030200084576696c436f7270
1603020008206b696c6c732070
1603020008656f706c65000d00
16030200082c002a0102020203
16030200080204020502060201
16030200080102010301040105
16030200080106010103020303
160302000803040305030603ed
1603020008edeeeeefefff0100
16030200020100

If we structure this data it looks like this:
Type  Version Length  Payload
16    0302    0008    0100009e03020000
16    0302    0008    00000000004e6f62
16    0302    0008    6f64796b6e6f7773
16    0302    0008    696d616361740000
16    0302    0008    0000000000002053
16    0302    0008    746f70206c6f6f6b
16    0302    0008    696e67206e6f7468
16    0302    0008    696e6720746f2066
16    0302    0008    696e646865726500
16    0302    0008    0200350100005300
16    0302    0008    0f00010113370015
16    0302    0008    4576696c436f7270
16    0302    0008    206b696c6c732070
16    0302    0008    656f706c65000d00
16    0302    0008    2c002a0102020203
16    0302    0008    0204020502060201
16    0302    0008    0102010301040105
16    0302    0008    0106010103020303
16    0302    0008    03040305030603ed
16    0302    0008    edeeeeefefff0100
16    0302    0002    0100

The actual message is the concatenation of the record payloads:

0100009e0302000000000000004e6f626f64796b6e6f7773696d6163617400000000000000002053746f70206c6f6f6b696e67206e6f7468696e6720746f2066696e64686572650002003501000053000f000101133700154576696c436f7270206b696c6c732070656f706c65000d002c002a010202020302040205020602010102010301040105010601010302030303040305030603ededeeeeefefff01000100

So what is left is to parse this message. There is an easy way on how to do this an a labor intensive manual way. Lets do the manual process first :) .
We know from the record header that his message is in fact a handshake message (0x16).
According to the specification handshake messages look like this:
    
      struct {
          HandshakeType msg_type;    /* handshake type */
          uint24 length;             /* bytes in message */
          select (HandshakeType) {
              case hello_request:       HelloRequest;
              case client_hello:        ClientHello;
              case server_hello:        ServerHello;
              case certificate:         Certificate;
              case server_key_exchange: ServerKeyExchange;
              case certificate_request: CertificateRequest;
              case server_hello_done:   ServerHelloDone;
              case certificate_verify:  CertificateVerify;
              case client_key_exchange: ClientKeyExchange;
              case finished:            Finished;
          } body;
      } Handshake;
    
This is RFC speak for: Each handshake message starts with a type field which says which handshake message this is, followed by a 3 byte length field which determines the length of rest of the handshake message.
So in our case the msg_type is 0x01 , followed by a 3 Byte length field (0x00009e, 158[base10]). 0x01 means ClientHello (https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-7). This means we have to parse the bytes after the length field as a ClientHello.
    
      {
          ProtocolVersion client_version;
          Random random;
          SessionID session_id;
          CipherSuite cipher_suites<2..2^16-2>;
          CompressionMethod compression_methods<1..2^8-1>;
          select (extensions_present) {
              case false:
                  struct {};
              case true:
                  Extension extensions<0..2^16-1>;
          };
      } ClientHello;

This means: The next 2 bytes are the ProtocolVersion, the next 32 bytes are the ClientRandom, the next byte is the SessionID Length, the next SessionID Length many bytes are the SessionID, the next 2 bytes are the CipherSuite Length bytes, followed by CipherSuite Length many CipherSuites, followed by a 1 byte Compression Length field, followed by Compression Length many CompressionBytes followed by a 2 byte Extension Length field followed by extension length many ExtensionBytes. So lets try to parse this:

Handshakye Type   : 01
Handshake Length  : 00009e
ProtocolVersion   : 0302
ClientRandom      : 000000000000004e6f626f64796b6e6f7773696d616361740000000000000000
SessionID Length  : 20
SessionID         : 53746f70206c6f6f6b696e67206e6f7468696e6720746f2066696e6468657265
CipherSuite Length: 0002
CipherSuites      : 0035
Compression Length: 01
CompressionBytes  : 00
Extension Length  : 0053
ExtensionBytes:   : 000f000101133700154576696c436f7270206b696c6c732070656f706c65000d002c002a010202020302040205020602010102010301040105010601010302030303040305030603ededeeeeefefff01000100

This is manual parsing is the slow method of dealing with this. Instead of looking at the specification to parse this message we could also compare the message structure to another ClientHello. This eases this process a lot. What we could also do is record the transmission of this message as a de-fragmented message to something and let Wireshark decode it for us. To send the de-fragmented message we need to create a new record header ourselves. The record should look like this:

Type   : 16
Version: 0302
Length : 00A2
Payload: 0100009e0302000000000000004e6f626f64796b6e6f7773696d6163617400000000000000002053746f70206c6f6f6b696e67206e6f7468696e6720746f2066696e64686572650002003501000053000f000101133700154576696c436f7270206b696c6c732070656f706c65000d002c002a010202020302040205020602010102010301040105010601010302030303040305030603ededeeeeefefff01000100

To send this record we can simply use netcat:


echo '16030200A20100009e0302000000000000004e6f626f64796b6e6f7773696d6163617400000000000000002053746f70206c6f6f6b696e67206e6f7468696e6720746f2066696e64686572650002003501000053000f000101133700154576696c436f7270206b696c6c732070656f706c65000d002c002a010202020302040205020602010102010301040105010601010302030303040305030603ededeeeeefefff01000100' | xxd -r -p | nc localhost 4433


Now we can use Wireshark to parse this message. As we can see now, the weired ASCII fragments we could see in the previous version are actually the ClientRandom, the SessionID, and a custom extension from the attacker. Now that we have de-fragmented the message, we know the ClientRandom: 000000000000004e6f626f64796b6e6f7773696d616361740000000000000000


De-fragmenting the ClientKeyExchange message


Now that we have de-fragmented the first flight from the attacker, we can de-fragment the second flight from the client. We can do this in the same fashion as we de-fragmented the ClientHello.

16    0302    0008    1000006600645de1
16    0302    0008    66a6d3669bf21936
16    0302    0008    5ef3d35410c50283
16    0302    0008    c4dd038a1b6fedf5
16    0302    0008    26d5b193453d796f
16    0302    0008    6e63c144bbda6276
16    0302    0008    3740468e21891641
16    0302    0008    0671318e83da3c2a
16    0302    0008    de5f6da6482b09fc
16    0302    0008    a5c823eb4d9933fe
16    0302    0008    ae17d165a6db0e94
16    0302    0008    bb09574fc1f7b8ed
16    0302    0008    cfbcf9e9696b6173
16    0302    0002    f4b6

14    0302    0001    01

16    0302    0030    cbe6bf1ae7f2bc40a49709a06c0e3149a65b8cd93c2525b5bfa8f696e29880d3447aef3dc9a996ca2aff8be99b1a4157
16    0302    0030    9bf02969ca42d203e566bcc696de08fa80e0bfdf44b1b315aed17fe867aed6d0d600c73de59c14beb74b0328eacadcf9

Note that his time we have 3 record groups. First there is chain of handshake records, followed by a ChangeCipherSpec record, followed by 2 more handshake records. The TLS specification forbids that records of different types are interleaved. This means that the first few records a probably forming a group of messages. The ChangeCipherSpec record is telling the server that subsequent messages are encrypted. This seems to be true, since the following records do not appear to be plaintext handshake messages.

So lets de-fragment the first group of records by concatenating their payloads:

1000006600645de166a6d3669bf219365ef3d35410c50283c4dd038a1b6fedf526d5b193453d796f6e63c144bbda62763740468e218916410671318e83da3c2ade5f6da6482b09fca5c823eb4d9933feae17d165a6db0e94bb09574fc1f7b8edcfbcf9e9696b6173f4b6

Since this is a handshake message, we know that the first byte should tell us which handshake message this is. 0x10 means this is a ClientKeyExchange message. Since we already know that TLS_RSA_WITH_AES_256_CBC_SHA was negotiated for this connection, we know that this is an RSA ClientKeyExchange message.

These messages are supposed to look like this (I will spare you the lengthy RFC definition):

Type (0x10)
Length (Length of the content) (3 bytes)
EncryptedPMS Length(Length of the encrypted PMS) (2 bytes)
EncrpytedPMS  (EncryptedPMS Length many bytes)
    
For our message this should look like this:

Type: 10
Length: 000066
Encrypted PMS Length: 0064
Encrypted PMS: 5de166a6d3669bf219365ef3d35410c50283c4dd038a1b6fedf526d5b193453d796f6e63c144bbda62763740468e218916410671318e83da3c2ade5f6da6482b09fca5c823eb4d9933feae17d165a6db0e94bb09574fc1f7b8edcfbcf9e9696b6173f4b6

Now that we got the Encrypted PMS we can decrypt it with the private key. Since the connection negotiated RSA as the key exchange algorithm this is done with:

encPMS^privKey mod modulus = plainPMS

We can solve this equation with the private key from the leaked PEM file.

2445298227328938658090475430796587247849533931395726514458166123599560640691186073871766111778498132903314547451268864032761115999716779282639547079095457185023600638251088359459150271827705392301109265654638212139757207501494756926838535350 ^ 996241568615939319506903357646514527421543094912647981212056826138382708603915022492738949955085789668243947380114192578398909946764789724993340852568712934975428447805093957315585432465710754275221903967417599121549904545874609387437384433 mod 4519950410687629988405948449295924027942240900746985859791939647949545695657651701565014369207785212702506305257912346076285925743737740481250261638791708483082426162177210620191963762755634733255455674225810981506935192783436252402225312097

Solving this equation gives us:

204742908894949049937193473353729060739551644014729690547520028508481967333831905155391804994508783506773012994170720979080285416764402813364718099379387561201299457228993584122400808905739026823578773289385773545222916543755807247900961

in hexadecimal this is:

00020325f41d3ebaf8986da712c82bcd4d554bf0b54023c29b624de9ef9c2f931efc580f9afb081b12e107b1e805f2b4f5f0f1000302476574204861636b6564204e6f6f622c20796f752077696c6c206e65766572206361746368206d65212121212121

The PMS is PKCS#1.5 encoded. This means that it is supposed to start with 0x0002 followed by a padding which contains no 0x00 bytes, followed by a separator 0x00 byte followed by a payload. In TLS, the payload has to be exactly 48 bytes long and has to start with the highest proposed protocol version of the client. We can see that this is indeed the case for our decrypted payload. The whole decrypted payload is the PMS for the connection.

This results in the PMS: 0302476574204861636b6564204e6f6f622c20796f752077696c6c206e65766572206361746368206d65212121212121 (which besides the protocol version is also ASCII :) )

Now that we have the PMS its time to revisit the key scheduling in TLS. We already briefly touched it but here is a overview:

As you can see, we first have to compute the master secret. With the master secret we can reconstruct the key_block. If we have computed the key_block, we can finally get the client_write key and decrypt the message from the attacker.


master secret = PRF ( PMS, "master secret", ClientRandom | ServerRandom)

key_block = PRF (master_secret, "key expansion", ServerRandom |  ClientRandom )

Where "master secret" and "key expansion" are literally ASCII Strings.


Note that in the key_block computation ClientRandom and ServerRandom are exchanged.



To do this computation we can either implement the PRF ourselfs, or easier, steal it from somewhere. The PRF in TLS 1.1 is the same as in TLS 1.0. Good places to steal from are for example openssl (C/C++), the scapy project (python), the TLS-Attacker project (java) or your favourite TLS library. The master secret is exactly 48 bytes long. The length of the key_block varies depending on the selected cipher suite and protocol version. In our case we need 2 * 20 bytes (for the 2 HMAC keys) + 2 * 32 bytes (for the 2 AES keys) = 104 bytes.

I will use the TLS-Attacker framework for this computation. The code will look like this:


This results in the following master secret: 292EABADCF7EFFC495825AED17EE7EA575E02DF0BAB7213EC1B246BE23B2E0912DA2B99C752A1F8BD3D833E8331D649F  And the following key_block:
6B4F936ADE9B4010393B00D9F29B4CB02D8836CFB0CBF1A67B53B200B6D9DCEF66E62C335D896A92EDD97C074957ADE136D6BAE74AE8193D56C6D83ACDE6A3B365679C5604312A1994DC0CEB508D81C4E440B626DFE3409A6CF39584E6C5864049FD4EF2A0A30106

Now we can chunk our resulting key_block into its individual parts. This is done analogously to the beginning of the challenge.

client_write_mac key = 6B4F936ADE9B4010393B00D9F29B4CB02D8836CF
server_write_mac key = B0CBF1A67B53B200B6D9DCEF66E62C335D896A92
client_write key = EDD97C074957ADE136D6BAE74AE8193D56C6D83ACDE6A3B365679C5604312A19
server_write key = 94DC0CEB508D81C4E440B626DFE3409A6CF39584E6C5864049FD4EF2A0A30106

Now that we have the full client_write key we can use that key to decrypt the application data messages. But these messages are also fragmented. But since the messages are now encrypted, we cannot simply concatenate the payloads of the records, but we have to decrypt them individually and only concatenate the resulting plaintext.

Analogue to the decryption of the heartbeat message, the first 16 bytes of each encrypted record payload are used as an IV

IV, Ciphertext Plaintext
6297cb6d9afba63ec4c0dd7ac0184570    a9c605307eb5f8ccbe8bbc210ff1ff14943873906fad3eca017f49af8feaec87      557365723A20726FB181CF546350A88ACBE8D0248D6FF07675D1514E03030303
063c60d43e08c4315f261f8a4f06169a    cdb5818d80075143afe83c79b570ab0b349b2e8748f8b767c54c0133331fb886    6F743B0A50617373D6F734D45FB99850CCAF32DF113914FC412C523603030303
cd839b95954fcadf1e60ee983cbe5c21    ac6f6e1fe34ae4b1214cded895db4746b8e38d7960d7d45cb001aab8e18c7fc7    3A20726F6F743B0A937048A265327642BD5626E00E4BC79618F9A95C03030303
8092d75f72b16cb23a856b00c4c39898    8df099441e10dca5e850398e616e4597170796b7202e2a8726862cd760ebacdf    6563686F20224F7769EACFBEEB5EE5D1F0B72306F8C78AD86CB4835003030303
8e9f83b015fce7f9c925b8b64abee426    224a5fbd2d9b8fc6ded34222a943ec0e8e973bcf125b81f918e391a22b4b0e65    6E6564206279204061736E93BFDC5103C8C2FE8C543A72B924212E8403030303
0e24ba11e41bfcf66452dc80221288ce    a66fb3aed9bdc7e08a31a0e7f14e11ce0983ec3d20dd47c179425243b14b08c9    6963306E7A31223B84A3CAFA7980B461DE0A6410D6251551AE401DD903030303
0465fdb05b121cdc08fa01cdacb2c8f4    eff59402f4dbf35a85cc91a6d1264a895cd1b3d2014c91fbba03ec4c85d058c9     0A7375646F20726DB97422D8B30C54CC672FFEC3E9D771D4743D96B903030303
e2ddbbb83fe8318c41c26d57a5813fab    89549a874ff74d83e182de34ecf55fff1a57008afd3a29ef0d839b991143cd2a      202F202D72663B0A996F3F1789CB9B671223E73C66A0BA578D0C0F3203030303
524f5210190f73c984bd6a59b9cf424c    b7f30fafe5ea3ac51b6757c51911e86b0aa1a6bbf4861c961f8463154acea315    0A666C61677B436868BF764B01D2CDCB2C06EA0DFC5443DABB6EC9AE03030303
32765985e2e594cddca3d0f45bd21f49    a5edfe89fdb3782e2af978585c0e27ba3ef90eb658304716237297f97e4e72bc    696D696368616E67FBF32127FA3AF2F97770DE5B9C6D376A254EF51E03030303
e0ae69b1fa54785dc971221fd92215fb    14e918a9e6e37139153be8cb9c16d2a787385746f9a80d0596580ba22eaf254e    61467233346B7D8BE8B903A167C44945E7676BF99D888A4B86FA8E0404040404

The plaintext then has to be de-padded and de-MACed.

Data HMAC Pad:
557365723A20726F    B181CF546350A88ACBE8D0248D6FF07675D1514E    03030303
6F743B0A50617373    D6F734D45FB99850CCAF32DF113914FC412C5236    03030303
3A20726F6F743B0A    937048A265327642BD5626E00E4BC79618F9A95C    03030303
6563686F20224F77    69EACFBEEB5EE5D1F0B72306F8C78AD86CB48350    03030303
6E65642062792040    61736E93BFDC5103C8C2FE8C543A72B924212E84    03030303
6963306E7A31223B    84A3CAFA7980B461DE0A6410D6251551AE401DD9    03030303
0A7375646F20726D    B97422D8B30C54CC672FFEC3E9D771D4743D96B9    03030303
202F202D72663B0A    996F3F1789CB9B671223E73C66A0BA578D0C0F32    03030303
0A666C61677B4368    68BF764B01D2CDCB2C06EA0DFC5443DABB6EC9AE    03030303
696D696368616E67    FBF32127FA3AF2F97770DE5B9C6D376A254EF51E    03030303
61467233346B7D      8BE8B903A167C44945E7676BF99D888A4B86FA8E    0404040404

This then results in the following data:

Data:
557365723A20726F6F743B0A506173733A20726F6F743B0A6563686F20224F776E656420627920406963306E7A31223B0A7375646F20726D202F202D72663B0A0A666C61677B4368696D696368616E6761467233346B7D8B

Which is ASCII for:

User: root;
Pass: root;
echo "Owned by @ic0nz1";
sudo rm / -rf;

flag{ChimichangaFr34k}


Honestly this was quite a journey. But this presented solution is the tedious manual way. There is also a shortcut with which you can skip most of the manual cryptographic operations.

The Shortcut

After you de-fragmented the messages you can patch the PCAP file and then use Wireshark to decrypt the whole session. This way you can get the flag without performing any cryptographic operation after you got the private key. Alternatively you can replay the communication and record it with Wireshark. I will show you the replay of the messages. To recap the de-fragmented messages looks like this:

ClientHello
0100009e0302000000000000004e6f626f64796b6e6f7773696d6163617400000000000000002053746f70206c6f6f6b696e67206e6f7468696e6720746f2066696e64686572650002003501000053000f000101133700154576696c436f7270206b696c6c732070656f706c65000d002c002a010202020302040205020602010102010301040105010601010302030303040305030603ededeeeeefefff01000100

ClientKeyExchange:
1000006600645de166a6d3669bf219365ef3d35410c50283c4dd038a1b6fedf526d5b193453d796f6e63c144bbda62763740468e218916410671318e83da3c2ade5f6da6482b09fca5c823eb4d9933feae17d165a6db0e94bb09574fc1f7b8edcfbcf9e9696b6173f4b6

We should now add new (not fragmented) record header to the previously fragmented message. The messages sent from the server can stay as they are. The ApplicationData from the client can also stay the same. The messages should now look like this

ClientHello
16030200A20100009e0302000000000000004e6f626f64796b6e6f7773696d6163617400000000000000002053746f70206c6f6f6b696e67206e6f7468696e6720746f2066696e64686572650002003501000053000f000101133700154576696c436f7270206b696c6c732070656f706c65000d002c002a010202020302040205020602010102010301040105010601010302030303040305030603ededeeeeefefff01000100

ServerHello / Certificate / ServerHelloDone
160302006A1000006600645de166a6d3669bf219365ef3d35410c50283c4dd038a1b6fedf526d5b193453d796f6e63c144bbda62763740468e218916410671318e83da3c2ade5f6da6482b09fca5c823eb4d9933feae17d165a6db0e94bb09574fc1f7b8edcfbcf9e9696b6173f4b61403020001011603020030cbe6bf1ae7f2bc40a49709a06c0e3149a65b8cd93c2525b5bfa8f696e29880d3447aef3dc9a996ca2aff8be99b1a415716030200309bf02969ca42d203e566bcc696de08fa80e0bfdf44b1b315aed17fe867aed6d0d600c73de59c14beb74b0328eacadcf9

ClientKeyExchange / ChangeCipherSpec / Finished
160302006A1000006600645de166a6d3669bf219365ef3d35410c50283c4dd038a1b6fedf526d5b193453d796f6e63c144bbda62763740468e218916410671318e83da3c2ade5f6da6482b09fca5c823eb4d9933feae17d165a6db0e94bb09574fc1f7b8edcfbcf9e9696b6173f4b61403020001011603020030cbe6bf1ae7f2bc40a49709a06c0e3149a65b8cd93c2525b5bfa8f696e29880d3447aef3dc9a996ca2aff8be99b1a415716030200309bf02969ca42d203e566bcc696de08fa80e0bfdf44b1b315aed17fe867aed6d0d600c73de59c14beb74b0328eacadcf9')

ApplicationData
1703020030063c60d43e08c4315f261f8a4f06169acdb5818d80075143afe83c79b570ab0b349b2e8748f8b767c54c0133331fb8861703020030cd839b95954fcadf1e60ee983cbe5c21ac6f6e1fe34ae4b1214cded895db4746b8e38d7960d7d45cb001aab8e18c7fc717030200308092d75f72b16cb23a856b00c4c398988df099441e10dca5e850398e616e4597170796b7202e2a8726862cd760ebacdf17030200308e9f83b015fce7f9c925b8b64abee426224a5fbd2d9b8fc6ded34222a943ec0e8e973bcf125b81f918e391a22b4b0e6517030200300e24ba11e41bfcf66452dc80221288cea66fb3aed9bdc7e08a31a0e7f14e11ce0983ec3d20dd47c179425243b14b08c917030200300465fdb05b121cdc08fa01cdacb2c8f4eff59402f4dbf35a85cc91a6d1264a895cd1b3d2014c91fbba03ec4c85d058c91703020030e2ddbbb83fe8318c41c26d57a5813fab89549a874ff74d83e182de34ecf55fff1a57008afd3a29ef0d839b991143cd2a1703020030524f5210190f73c984bd6a59b9cf424cb7f30fafe5ea3ac51b6757c51911e86b0aa1a6bbf4861c961f8463154acea315170302003032765985e2e594cddca3d0f45bd21f49a5edfe89fdb3782e2af978585c0e27ba3ef90eb658304716237297f97e4e72bc1703020030e0ae69b1fa54785dc971221fd92215fb14e918a9e6e37139153be8cb9c16d2a787385746f9a80d0596580ba22eaf254e

What we want to do now is create the following conversation:
CH->
<-SH, CERT, SHD
-> CKE, CCS, FIN
-> APP, APP ,APP

This will be enough for Wireshark to decrypt the traffic. However, since we removed some messages (the whole HeartbeatMessages) our HMAC's will be invalid.

We need to record an interleaved transmission of these message with Wireshark. I will use these simple python programs to create the traffic:




If we record these transmissions and tick the flag in Wireshark to ignore invalid HMAC's we can see the plaintext (if we added the private key in Wireshark).

Challenge Creation

I used our TLS-Attacker project to create this challenge. With TLS-Attacker you can send arbitrary TLS messages with arbitrary content in an arbitrary order, save them in XML and replay them. The communication between the peers are therefore only two XML files which are loaded into TLS-Attacker talking to each other. I then copied parts of the key_block from the debug output and the challenge was completed :)

If you have question in regards to the challenge you can DM me at @ic0nz1
Happy Hacking
Related posts

  1. Hacking Etico Pdf
  2. Aprender A Ser Hacker
  3. Google Hacking Search
  4. Hacking Madrid
  5. Informatico Hacker
  6. Hacking Software
  7. Libros Hacking Pdf
  8. Hacking Con Buscadores Pdf
  9. Ethical Hacking Certification

WHO IS ETHICAL HACKER

Who is hacker?
A hacker is a Creative person and a creative Programmer,who have knowledge about Networking,Operating system,hacking & a best creative social engineer who control anyone's mind he is also a knowledgeable person.
Hacker are the problem solver and tool builder.

                                OR

A hacker is an individual who uses computer, networking and other skills to overcome a technical problem but it often refers to a person who uses his or her abilities to gain unauthorized access to system or networks in  order to commit crimes. 


Related news


Data Types, Variables And Arrays In Java



CHAPTER
3 Data Types, Variables, and Arrays
This chapter examines three of Java's most fundamental elements: data types, variables, and arrays. As with all modern programming languages, Java supports several types of data. You may use these types to declare variables and to create arrays. As you will see, Java's approach to these items is clean, efficient, and cohesive.
Java Is a Strongly Typed Language
It is important to state at the outset that Java is a strongly typed language. Indeed, part
of Java's safety and robustness comes from this fact. Let's see what this means. First, every variable has a type, every expression has a type, and every type is strictly defined. Second, all assignments, whether explicit or via parameter passing in method calls, are checked for type compatibility. There are no automatic coercions or conversions of conflicting types as in some languages. The Java compiler checks all expressions and parameters to ensure that the types are compatible. Any type mismatches are errors that must be corrected before the compiler will finish compiling the class.
The Primitive Types
Java defines eight primitive types of data: byte, short, int, long, char, float, double, and boolean. The primitive types are also commonly referred to as simple types, and both terms will be used in this book. These can be put in four groups:
• Integers This group includes byte, short, int, and long, which are for whole-valued signed numbers.
• Floating-point numbers This group includes float and double, which represent numbers with fractional precision.
• Characters This group includes char, which represents symbols in a character set, like letters and numbers.
• Boolean This group includes boolean, which is a special type for representing true/false values.
 
You can use these types as-is, or to construct arrays or your own class types. Thus, they form the basis for all other types of data that you can create.
The primitive types represent single values—not complex objects. Although Java is otherwise completely object-oriented, the primitive types are not. They are analogous to the simple types found in most other non–object-oriented languages. The reason for this is efficiency. Making the primitive types into objects would have degraded performance too much.
The primitive types are defined to have an explicit range and mathematical behavior. Languages such as C and C++ allow the size of an integer to vary based upon the dictates of the execution environment. However, Java is different. Because of Java's portability
requirement, all data types have a strictly defined range. For example, an int is always 32 bits, regardless of the particular platform. This allows programs to be written that are guaranteed to run without porting on any machine architecture. While  specifying the size of an integer may cause a small loss of performance in some environments, it is necessary in order to achieve portability.
Let's look at each type of data in turn.
Integers
Java defines four integer types: byte, short, int, and long. All of these are signed, positive and negative values. Java does not support unsigned, positive-only integers. Many other computer languages support both signed and unsigned integers. However, Java's designers felt that unsigned integers were unnecessary. Specifically, they felt that the concept of unsigned was used mostly to specify the behavior of the high-order bit, which defines the sign of an integer value. As you will see in Chapter 4, Java manages the meaning of the high- order bit differently, by adding a special "unsigned right shift" operator. Thus, the need for an unsigned integer type was eliminated.
The width of an integer type should not be thought of as the amount of storage it consumes, but rather as the behavior it defines for variables and expressions of that type. The Java run-time environment is free to use whatever size it wants, as long as the types behave as you declared them. The width and ranges of these integer types vary widely, as shown in this table:
Name Width Range
long 64 –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
int 32 –2,147,483,648 to 2,147,483,647
short 16 –32,768 to 32,767
byte 8 –128 to 127

Let's look at each type of integer.
byte
The smallest integer type is byte. This is a signed 8-bit type that has a range from –128 to
127. Variables of type byte are especially useful when you're working with a stream of data from a network or file. They are also useful when you're working with raw binary data that may not be directly compatible with Java's other built-in types.
 
Byte variables are declared by use of the byte keyword. For example, the following declares two byte variables called b and c:
byte b, c;

short
short is a signed 16-bit type. It has a range from –32,768 to 32,767. It is probably the least- used Java type. Here are some examples of short variable declarations:
short s; short t;
int
The most commonly used integer type is int. It is a signed 32-bit type that has a range from –2,147,483,648 to 2,147,483,647. In addition to other uses, variables of type int are commonly employed to control loops and to index arrays. Although you might think that using a byte or short would be more efficient than using an int in situations in which the larger range of an int is not needed, this may not be the case. The reason is that when byte and short values are used in an expression they are promoted to int when the expression is evaluated. (Type promotion is described later in this chapter.) Therefore, int is often the best choice when an integer is needed.
long
long is a signed 64-bit type and is useful for those occasions where an int type is not large enough to hold the desired value. The range of a long is quite large. This makes it useful when big, whole numbers are needed. For example, here is a program that computes the number of miles that light will travel in a specified number of days:
// Compute distance light travels using long variables. class Light {
public static void main(String args[]) { int lightspeed;
long days; long seconds; long distance;

// approximate speed of light in miles per second lightspeed = 186000;

days = 1000; // specify number of days here

seconds = days * 24 * 60 * 60; // convert to seconds distance = lightspeed * seconds; // compute distance
System.out.print("In " + days);
System.out.print(" days light will travel about "); System.out.println(distance + " miles.");
}
}
 
This program generates the following output:

In 1000 days light will travel about 16070400000000 miles.

Clearly, the result could not have been held in an int variable.

Floating-Point Types
Floating-point numbers, also known as real numbers, are used when evaluating expressions that require fractional precision. For example, calculations such as square root, or transcendentals such as sine and cosine, result in a value whose precision requires a floating- point type. Java implements the standard (IEEE–754) set of floating-point types and operators. There are two kinds of floating-point types, float and double, which represent single- and double-precision numbers, respectively. Their width and ranges are shown here:

Name Width in Bits Approximate Range
double 64 4.9e–324 to 1.8e+308
float 32 1.4e–045 to 3.4e+038

Each of these floating-point types is examined next.
float
The type float specifies a single-precision value that uses 32 bits of storage. Single precision is faster on some processors and takes half as much space as double precision, but will become imprecise when the values are either very large or very small. Variables of type float are useful when you need a fractional component, but don't require a large degree of precision. For example, float can be useful when representing dollars and cents.
Here are some example float variable declarations:

float hightemp, lowtemp;

double
Double precision, as denoted by the double keyword, uses 64 bits to store a value. Double precision is actually faster than single precision on some modern processors that have been optimized for high-speed mathematical calculations. All transcendental math functions, such as sin( ), cos( ), and sqrt( ), return double values. When you need to maintain accuracy over many iterative calculations, or are manipulating large-valued numbers, double is the best choice.
Here is a short program that uses double variables to compute the area of a circle:

// Compute the area of a circle. class Area {
public static void main(String args[]) { double pi, r, a;

r = 10.8; // radius of circle
pi = 3.1416; // pi, approximately
 
a = pi * r * r; // compute area

System.out.println("Area of circle is " + a);
}
}

Characters
In Java, the data type used to store characters is char. However, C/C++ programmers beware: char in Java is not the same as char in C or C++. In C/C++, char is 8 bits wide. This is not the case in Java. Instead, Java uses Unicode to represent characters. Unicode defines a fully international character set that can represent all of the characters found in all human languages. It is a unification of dozens of character sets, such as Latin, Greek, Arabic, Cyrillic, Hebrew, Katakana, Hangul, and many more. For this purpose, it requires 16 bits. Thus, in Java char is a 16-bit type. The range of a char is 0 to 65,536. There are no negative chars. The standard set of characters known as ASCII still ranges from 0 to 127 as always, and the extended 8-bit character set, ISO-Latin-1, ranges from 0 to 255. Since Java is designed to allow programs to be written for worldwide use, it makes sense that it would use Unicode to represent characters. Of course, the use of Unicode is somewhat inefficient for languages such as English, German, Spanish, or French, whose characters can easily be contained within 8 bits. But such is the price that must be paid for global portability.

NOTE More information about Unicode can be found at http://www.unicode.org.

Here is a program that demonstrates char variables:

// Demonstrate char data type. class CharDemo {
public static void main(String args[]) { char ch1, ch2;

ch1 = 88; // code for X ch2 = 'Y';

System.out.print("ch1 and ch2: "); System.out.println(ch1 + " " + ch2);
}
}
This program displays the following output:

ch1 and ch2: X Y

Notice that ch1 is assigned the value 88, which is the ASCII (and Unicode) value that corresponds to the letter X. As mentioned, the ASCII character set occupies the first 127 values in the Unicode character set. For this reason, all the "old tricks" that you may have used with characters in other languages will work in Java, too.
Although char is designed to hold Unicode characters, it can also be used as an integer type on which you can perform arithmetic operations. For example, you can add two
 
characters together, or increment the value of a character variable. Consider the following program:

// char variables behave like integers. class CharDemo2 {
public static void main(String args[]) { char ch1;

ch1 = 'X';
System.out.println("ch1 contains " + ch1);

ch1++; // increment ch1 System.out.println("ch1 is now " + ch1);
}
}

The output generated by this program is shown here:

ch1 contains X ch1 is now Y

In the program, ch1 is first given the value X. Next, ch1 is incremented. This results in ch1
containing Y, the next character in the ASCII (and Unicode) sequence.

NOTE In the formal specification for Java, char is referred to as an integral type, which means that it is in the same general category as int, short, long, and byte. However, because its principal use is for representing Unicode characters, char is commonly considered to be in a category of its own.

Booleans
Java has a primitive type, called boolean, for logical values. It can have only one of two possible values, true or false. This is the type returned by all relational operators, as in the case of a < b. boolean is also the type required by the conditional expressions that govern the control statements such as if and for.
Here is a program that demonstrates the boolean type:

// Demonstrate boolean values. class BoolTest {
public static void main(String args[]) { boolean b;

b = false;
System.out.println("b is " + b); b = true;
System.out.println("b is " + b);

// a boolean value can control the if statement if(b) System.out.println("This is executed.");

b = false;
if(b) System.out.println("This is not executed.");
 
// outcome of a relational operator is a boolean value System.out.println("10 > 9 is " + (10 > 9));
}
}
The output generated by this program is shown here:

b is false b is true
This is executed.
10 > 9 is true

There are three interesting things to notice about this program. First, as you can see, when a boolean value is output by println( ), "true" or "false" is displayed. Second, the value of a boolean variable is sufficient, by itself, to control the if statement. There is no need to write an if statement like this:

if(b == true) …

Third, the outcome of a relational operator, such as <, is a boolean value. This is why the expression 10>9 displays the value "true." Further, the extra set of parentheses around 10>9 is necessary because the + operator has a higher precedence than the >.

A Closer Look at Literals
Literals were mentioned briefly in Chapter 2. Now that the built-in types have been formally described, let's take a closer look at them.
Integer Literals
Integers are probably the most commonly used type in the typical program. Any whole number value is an integer literal. Examples are 1, 2, 3, and 42. These are all decimal values, meaning they are describing a base 10 number. There are two other bases which can be used in integer literals, octal (base eight) and hexadecimal (base 16). Octal values are denoted in Java by a leading zero. Normal decimal numbers cannot have a leading zero. Thus, the seemingly valid value 09 will produce an error from the compiler, since 9 is outside of octal's 0 to 7 range. A more common base for numbers used by programmers is hexadecimal, which matches cleanly with modulo 8 word sizes, such as 8, 16, 32, and 64 bits. You signify a hexadecimal constant with a leading zero-x, (0x or 0X). The range of a hexadecimal digit is 0 to 15, so A through F (or a through f ) are substituted for 10 through 15.
Integer literals create an int value, which in Java is a 32-bit integer value. Since Java is strongly typed, you might be wondering how it is possible to assign an integer literal to one of Java's other integer types, such as byte or long, without causing a type mismatch error.
Fortunately, such situations are easily handled. When a literal value is assigned to a byte or short variable, no error is generated if the literal value is within the range of the target type. An integer literal can always be assigned to a long variable. However, to specify a long literal, you will need to explicitly tell the compiler that the literal value is of type long. You do this by appending an upper- or lowercase L to the literal. For example, 0x7ffffffffffffffL or 9223372036854775807L is the largest long. An integer can also be assigned to a char as long as it is within range.
 
Beginning with JDK 7, you can also specify integer literals using binary. To do so, prefix the value with 0b or 0B. For example, this specifies the decimal value 10 using a binary literal:

int x = 0b1010;

Among other uses, the addition of binary literals makes it easier to enter values used as bitmasks. In such a case, the decimal (or hexadecimal) representation of the value does not visually convey its meaning relative to its use. The binary literal does.
Also beginning with JDK 7, you can embed one or more underscores in an integer literal. Doing so makes it easier to read large integer literals. When the literal is compiled, the underscores are discarded. For example, given

int x = 123_456_789;

the value given to x will be 123,456,789. The underscores will be ignored. Underscores can only be used to separate digits. They cannot come at the beginning or the end of a literal. It is, however, permissible for more than one underscore to be used between two digits. For example, this is valid:

int x = 123 456 789;

The use of underscores in an integer literal is especially useful when encoding such things as telephone numbers, customer ID numbers, part numbers, and so on. They are also useful for providing visual groupings when specifying binary literals. For example, binary values are often visually grouped in four-digits units, as shown here:

int x = 0b1101_0101_0001_1010;

Floating-Point Literals
Floating-point numbers represent decimal values with a fractional component. They can be expressed in either standard or scientific notation. Standard notation consists of a whole number component followed by a decimal point followed by a fractional component. For example, 2.0, 3.14159, and 0.6667 represent valid standard-notation floating-point numbers. Scientific notation uses a standard-notation, floating-point number plus a suffix that specifies a power of 10 by which the number is to be multiplied. The exponent is indicated by an E or e followed by a decimal number, which can be positive or negative. Examples include 6.022E23, 314159E–05, and 2e+100.
Floating-point literals in Java default to double precision. To specify a float literal, you must append an F or f to the constant. You can also explicitly specify a double literal by appending a D or d. Doing so is, of course, redundant. The default double type consumes 64 bits of storage, while the smaller float type requires only 32 bits.
Hexadecimal floating-point literals are also supported, but they are rarely used. They must be in a form similar to scientific notation, but a P or p, rather than an E or e, is used. For example, 0x12.2P2 is a valid floating-point literal. The value following the P, called the binary exponent, indicates the power-of-two by which the number is multiplied. Therefore, 0x12.2P2 represents 72.5.
 
Beginning with JDK 7, you can embed one or more underscores in a floating-point literal. This feature works the same as it does for integer literals, which were just described. Its purpose is to make it easier to read large floating-point literals. When the literal is compiled, the underscores are discarded. For example, given

double num = 9_423_497_862.0;

the value given to num will be 9,423,497,862.0. The underscores will be ignored. As is the case with integer literals, underscores can only be used to separate digits. They cannot come at the beginning or the end of a literal. It is, however, permissible for more than one underscore to be used between two digits. It is also permissible to use underscores in the fractional portion of the number. For example,

double num = 9_423_497.1_0_9;

is legal. In this case, the fractional part is .109.
Boolean Literals
Boolean literals are simple. There are only two logical values that a boolean value can have, true and false. The values of true and false do not convert into any numerical representation. The true literal in Java does not equal 1, nor does the false literal equal 0. In Java, the Boolean literals can only be assigned to variables declared as boolean or used in expressions with Boolean operators.
Character Literals
Characters in Java are indices into the Unicode character set. They are 16-bit values that can be converted into integers and manipulated with the integer operators, such as the addition and subtraction operators. A literal character is represented inside a pair of single quotes. All of the visible ASCII characters can be directly entered inside the quotes, such as 'a', 'z', and '@'. For characters that are impossible to enter directly, there are several escape sequences that allow you to enter the character you need, such as ' \" for the single-quote character itself and ' \n' for the newline character. There is also a mechanism for directly entering the value of a character in octal or hexadecimal. For octal notation, use the backslash followed by the three-digit number. For example, ' \141' is the letter 'a'. For hexadecimal, you enter a backslash-u ( \u), then exactly four hexadecimal digits. For example, ' \u0061' is the ISO-Latin-1 'a' because the top byte is zero. ' \ua432 ' is a Japanese Katakana character. Table 3-1 shows the character escape sequences.
String Literals
String literals in Java are specified like they are in most other languages—by enclosing a sequence of characters between a pair of double quotes. Examples of string literals are
"Hello World" "two\nlines"
" \"This is in quotes\""
 

Escape Sequence Description
\ddd Octal character (ddd)
\uxxxx Hexadecimal Unicode character (xxxx)
\' Single quote
\" Double quote
\\ Backslash
\r Carriage return
\n New line (also known as line feed)
\f Form feed
\t Tab
\b Backspace
Table 3-1 Character Escape Sequences

The escape sequences and octal/hexadecimal notations that were defined for character literals work the same way inside of string literals. One important thing to note about Java strings is that they must begin and end on the same line. There is no line-continuation escape sequence as there is in some other languages.

NOTE As you may know, in some other languages, including C/C++, strings are implemented as arrays of characters. However, this is not the case in Java. Strings are actually object types. As you will see later in this book, because Java implements strings as objects, Java includes extensive string-handling capabilities that are both powerful and easy to use.

Variables
The variable is the basic unit of storage in a Java program. A variable is defined by the combination of an identifier, a type, and an optional initializer. In addition, all variables have a scope, which defines their visibility, and a lifetime. These elements are examined next.

Declaring a Variable
In Java, all variables must be declared before they can be used. The basic form of a variable declaration is shown here:
type identifier [ = value ][, identifier [= value ] …];
The type is one of Java's atomic types, or the name of a class or interface. (Class and interface types are discussed later in Part I of this book.) The identifier is the name of the variable. You can initialize the variable by specifying an equal sign and a value. Keep in mind that the initialization expression must result in a value of the same (or compatible) type as that specified for the variable. To declare more than one variable of the specified type, use a comma-separated list.
Here are several examples of variable declarations of various types. Note that some include an initialization.
 
int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints, initializing
// d and f.
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi. char x = 'x'; // the variable x has the value 'x'.

The identifiers that you choose have nothing intrinsic in their names that indicates their type. Java allows any properly formed identifier to have any declared type.
Dynamic Initialization
Although the preceding examples have used only constants as initializers, Java allows variables to be initialized dynamically, using any expression valid at the time the variable is declared.
For example, here is a short program that computes the length of the hypotenuse of a right triangle given the lengths of its two opposing sides:

// Demonstrate dynamic initialization. class DynInit {
public static void main(String args[]) { double a = 3.0, b = 4.0;

// c is dynamically initialized double c = Math.sqrt(a * a + b * b);

System.out.println("Hypotenuse is " + c);
}
}
Here, three local variables—a, b, and c—are declared. The first two, a and b, are initialized by constants. However, c is initialized dynamically to the length of the hypotenuse (using the Pythagorean theorem). The program uses another of Java's built-in methods, sqrt( ), which is a member of the Math class, to compute the square root of its argument. The key point here is that the initialization expression may use any element valid at the time of the initialization, including calls to methods, other variables, or literals.
The Scope and Lifetime of Variables
So far, all of the variables used have been declared at the start of the main( ) method. However, Java allows variables to be declared within any block. As explained in Chapter 2, a block is begun with an opening curly brace and ended by a closing curly brace. A block
defines a scope. Thus, each time you start a new block, you are creating a new scope. A scope determines what objects are visible to other parts of your program. It also determines the lifetime of those objects.
Many other computer languages define two general categories of scopes: global and local. However, these traditional scopes do not fit well with Java's strict, object-oriented model. While it is possible to create what amounts to being a global scope, it is by far the exception, not the rule. In Java, the two major scopes are those defined by a class and those defined by a method. Even this distinction is somewhat artificial. However, since the class scope has several unique properties and attributes that do not apply to the scope defined
 
by a method, this distinction makes some sense. Because of the differences, a discussion of class scope (and variables declared within it) is deferred until Chapter 6, when classes are described. For now, we will only examine the scopes defined by or within a method.
The scope defined by a method begins with its opening curly brace. However, if that method has parameters, they too are included within the method's scope. Although this book will look more closely at parameters in Chapter 6, for the sake of this discussion, they work the same as any other method variable.
As a general rule, variables declared inside a scope are not visible (that is, accessible) to code that is defined outside that scope. Thus, when you declare a variable within a scope, you are localizing that variable and protecting it from unauthorized access and/or modification. Indeed, the scope rules provide the foundation for encapsulation.
Scopes can be nested. For example, each time you create a block of code, you are creating a new, nested scope. When this occurs, the outer scope encloses the inner scope. This means that objects declared in the outer scope will be visible to code within the inner scope. However, the reverse is not true. Objects declared within the inner scope will not be visible outside it.
To understand the effect of nested scopes, consider the following program:
// Demonstrate block scope. class Scope {
public static void main(String args[]) { int x; // known to all code within main

x = 10;
if(x == 10) { // start new scope
int y = 20; // known only to this block

// x and y both known here. System.out.println("x and y: " + x + " " + y); x = y * 2;
}
// y = 100; // Error! y not known here

// x is still known here. System.out.println("x is " + x);
}
}
As the comments indicate, the variable x is declared at the start of main( )'s scope and is accessible to all subsequent code within main( ). Within the if block, y is declared. Since a block defines a scope, y is only visible to other code within its block. This is why outside of its block, the line y = 100; is commented out. If you remove the leading comment symbol, a compile-time error will occur, because y is not visible outside of its block. Within the if block, x can be used because code within a block (that is, a nested scope) has access to variables declared by an enclosing scope.
Within a block, variables can be declared at any point, but are valid only after they are declared. Thus, if you define a variable at the start of a method, it is available to all of the code within that method. Conversely, if you declare a variable at the end of a block, it is effectively useless, because no code will have access to it. For example, this fragment is invalid because count cannot be used prior to its declaration:
 
// This fragment is wrong!
count = 100; // oops! cannot use count before it is declared! int count;

Here is another important point to remember: variables are created when their scope is entered, and destroyed when their scope is left. This means that a variable will not hold its value once it has gone out of scope. Therefore, variables declared within a method will not hold their values between calls to that method. Also, a variable declared within a block will lose its value when the block is left. Thus, the lifetime of a variable is confined to its scope.
If a variable declaration includes an initializer, then that variable will be reinitialized each time the block in which it is declared is entered. For example, consider the next program:

// Demonstrate lifetime of a variable. class LifeTime {
public static void main(String args[]) { int x;

for(x = 0; x < 3; x++) {
int y = -1; // y is initialized each time block is entered System.out.println("y is: " + y); // this always prints -1 y = 100;
System.out.println("y is now: " + y);
}
}
}

The output generated by this program is shown here:

y is: -1
y is now: 100
y is: -1
y is now: 100
y is: -1
y is now: 100
As you can see, y is reinitialized to –1 each time the inner for loop is entered. Even though it is subsequently assigned the value 100, this value is lost.
One last point: Although blocks can be nested, you cannot declare a variable to have the same name as one in an outer scope. For example, the following program is illegal:

// This program will not compile class ScopeErr {
public static void main(String args[]) { int bar = 1;
{ // creates a new scope
int bar = 2; // Compile-time error – bar already defined!
}
}
}
 
Type Conversion and Casting
If you have previous programming experience, then you already know that it is fairly common to assign a value of one type to a variable of another type. If the two types are compatible, then Java will perform the conversion automatically. For example, it is always possible to assign an int value to a long variable. However, not all types are compatible, and thus, not
all type conversions are implicitly allowed. For instance, there is no automatic conversion defined from double to byte. Fortunately, it is still possible to obtain a conversion between incompatible types. To do so, you must use a cast, which performs an explicit conversion between incompatible types. Let's look at both automatic type conversions and casting.
Java's Automatic Conversions
When one type of data is assigned to another type of variable, an automatic type conversion
will take place if the following two conditions are met:
• The two types are compatible.
• The destination type is larger than the source type.
When these two conditions are met, a widening conversion takes place. For example, the int type is always large enough to hold all valid byte values, so no explicit cast statement is required.
For widening conversions, the numeric types, including integer and floating-point types, are compatible with each other. However, there are no automatic conversions from the numeric types to char or boolean. Also, char and boolean are not compatible with each other.
As mentioned earlier, Java also performs an automatic type conversion when storing a literal integer constant into variables of type byte, short, long, or char.
Casting Incompatible Types
Although the automatic type conversions are helpful, they will not fulfill all needs. For example, what if you want to assign an int value to a byte variable? This conversion will not be performed automatically, because a byte is smaller than an int. This kind of conversion is sometimes called a narrowing conversion, since you are explicitly making the value narrower so that it will fit into the target type.
To create a conversion between two incompatible types, you must use a cast. A cast is simply an explicit type conversion. It has this general form:
(target-type) value
Here, target-type specifies the desired type to convert the specified value to. For example, the following fragment casts an int to a byte. If the integer's value is larger than the range of a byte, it will be reduced modulo (the remainder of an integer division by the) byte's range.

int a; byte b;
// …
b = (byte) a;
 
A different type of conversion will occur when a floating-point value is assigned to an integer type: truncation. As you know, integers do not have fractional components. Thus, when a floating-point value is assigned to an integer type, the fractional component is lost. For example, if the value 1.23 is assigned to an integer, the resulting value will simply be 1. The 0.23 will have been truncated. Of course, if the size of the whole number component is too large to fit into the target integer type, then that value will be reduced modulo the target type's range.
The following program demonstrates some type conversions that require casts:

// Demonstrate casts. class Conversion {
public static void main(String args[]) { byte b;
int i = 257;
double d = 323.142;

System.out.println("\nConversion of int to byte."); b = (byte) i;
System.out.println("i and b " + i + " " + b);

System.out.println("\nConversion of double to int."); i = (int) d;
System.out.println("d and i " + d + " " + i);

System.out.println("\nConversion of double to byte."); b = (byte) d;
System.out.println("d and b " + d + " " + b);
}
}

This program generates the following output:

Conversion of int to byte. i and b 257 1

Conversion of double to int. d and i 323.142 323

Conversion of double to byte. d and b 323.142 67

Let's look at each conversion. When the value 257 is cast into a byte variable, the result is the remainder of the division of 257 by 256 (the range of a byte), which is 1 in this case. When the d is converted to an int, its fractional component is lost. When d is converted to a byte, its fractional component is lost, and the value is reduced modulo 256, which in this case is 67.

Automatic Type Promotion in Expressions
In addition to assignments, there is another place where certain type conversions may occur: in expressions. To see why, consider the following. In an expression, the precision
 
required of an intermediate value will sometimes exceed the range of either operand. For example, examine the following expression:

byte a = 40; byte b = 50; byte c = 100;
int d = a * b / c;

The result of the intermediate term a * b easily exceeds the range of either of its byte operands. To handle this kind of problem, Java automatically promotes each byte, short, or char operand to int when evaluating an expression. This means that the subexpression a*b is performed using integers—not bytes. Thus, 2,000, the result of the intermediate expression, 50 * 40, is legal even though a and b are both specified as type byte.
As useful as the automatic promotions are, they can cause confusing compile-time errors. For example, this seemingly correct code causes a problem:

byte b = 50;
b = b * 2; // Error! Cannot assign an int to a byte!

The code is attempting to store 50 * 2, a perfectly valid byte value, back into a byte variable. However, because the operands were automatically promoted to int when the expression was evaluated, the result has also been promoted to int. Thus, the result of the expression is now of type int, which cannot be assigned to a byte without the use of a cast. This is true even if, as in this particular case, the value being assigned would still fit in the target type.
In cases where you understand the consequences of overflow, you should use an explicit cast, such as

byte b = 50;
b = (byte)(b * 2);

which yields the correct value of 100.
The Type Promotion Rules
Java defines several type promotion rules that apply to expressions. They are as follows: First, all byte, short, and char values are promoted to int, as just described. Then, if one operand is a long, the whole expression is promoted to long. If one operand is a float, the entire expression is promoted to float. If any of the operands are double, the result is double.
The following program demonstrates how each value in the expression gets promoted to match the second argument to each binary operator:

class Promote {
public static void main(String args[]) { byte b = 42;
char c = 'a'; short s = 1024; int i = 50000; float f = 5.67f; double d = .1234;
double result = (f * b) + (i / c) - (d * s);
 
System.out.println((f * b) + " + " + (i / c) + " - " + (d * s)); System.out.println("result = " + result);
}
}

Let's look closely at the type promotions that occur in this line from the program:

double result = (f * b) + (i / c) - (d * s);

In the first subexpression, f * b, b is promoted to a float and the result of the subexpression is float. Next, in the subexpression i/c, c is promoted to int, and the result is of type int.
Then, in d * s, the value of s is promoted to double, and the type of the subexpression is double. Finally, these three intermediate values, float, int, and double, are considered. The outcome of float plus an int is a float. Then the resultant float minus the last double is promoted to double, which is the type for the final result of the expression.

Arrays
An array is a group of like-typed variables that are referred to by a common name. Arrays of any type can be created and may have one or more dimensions. A specific element in an array is accessed by its index. Arrays offer a convenient means of grouping related information.

NOTE If you are familiar with C/C++, be careful. Arrays in Java work differently than they do in those languages.

One-Dimensional Arrays
A one-dimensional array is, essentially, a list of like-typed variables. To create an array, you first must create an array variable of the desired type. The general form of a one-dimensional array declaration is
type var-name[ ];
Here, type declares the element type (also called the base type) of the array. The element type determines the data type of each element that comprises the array. Thus, the element type for the array determines what type of data the array will hold. For example, the following declares an array named month_days with the type "array of int":
int month_days[];

Although this declaration establishes the fact that month_days is an array variable, no array actually exists. In fact, the value of month_days is set to null, which represents an array with no value. To link month_days with an actual, physical array of integers, you must allocate one using new and assign it to month_days. new is a special operator that allocates memory.
You will look more closely at new in a later chapter, but you need to use it now to allocate memory for arrays. The general form of new as it applies to one-dimensional arrays appears as follows:
array-var = new type [size];
 
Here, type specifies the type of data being allocated, size specifies the number of elements in the array, and array-var is the array variable that is linked to the array. That is, to use new to allocate an array, you must specify the type and number of elements to allocate. The elements in the array allocated by new will automatically be initialized to zero (for numeric types), false (for boolean), or null (for reference types, which are described in a later chapter). This example allocates a 12-element array of integers and links them to month_days:

month_days = new int[12];

After this statement executes, month_days will refer to an array of 12 integers. Further, all elements in the array will be initialized to zero.
Let's review: Obtaining an array is a two-step process. First, you must declare a variable of the desired array type. Second, you must allocate the memory that will hold the array, using new, and assign it to the array variable. Thus, in Java all arrays are dynamically allocated. If the concept of dynamic allocation is unfamiliar to you, don't worry. It will
be described at length later in this book.
Once you have allocated an array, you can access a specific element in the array by specifying its index within square brackets. All array indexes start at zero. For example, this statement assigns the value 28 to the second element of month_days:
month_days[1] = 28;

The next line displays the value stored at index 3:

System.out.println(month_days[3]);

Putting together all the pieces, here is a program that creates an array of the number of days in each month:

// Demonstrate a one-dimensional array. class Array {
public static void main(String args[]) { int month_days[];
month_days = new int[12]; month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println("April has " + month_days[3] + " days.");
}
}
 
When you run this program, it prints the number of days in April. As mentioned, Java array indexes start with zero, so the number of days in April is month_days[3] or 30.
It is possible to combine the declaration of the array variable with the allocation of the array itself, as shown here:
int month_days[] = new int[12];

This is the way that you will normally see it done in professionally written Java programs.
Arrays can be initialized when they are declared. The process is much the same as that used to initialize the simple types. An array initializer is a list of comma-separated expressions surrounded by curly braces. The commas separate the values of the array elements. The array will automatically be created large enough to hold the number of elements you specify in the array initializer. There is no need to use new. For example, to store the number of days in each month, the following code creates an initialized array of integers:

// An improved version of the previous program. class AutoArray {
public static void main(String args[]) {

int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,
30, 31 };
System.out.println("April has " + month_days[3] + " days.");
}
}
When you run this program, you see the same output as that generated by the previous version.
Java strictly checks to make sure you do not accidentally try to store or reference values outside of the range of the array. The Java run-time system will check to be sure that all array indexes are in the correct range. For example, the run-time system will check the value of each index into month_days to make sure that it is between 0 and 11 inclusive. If you try to access elements outside the range of the array (negative numbers or numbers greater than the length of the array), you will cause a run-time error.
Here is one more example that uses a one-dimensional array. It finds the average of a set of numbers.

// Average an array of values. class Average {
public static void main(String args[]) {
double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};
double result = 0; int i;

for(i=0; i<5; i++)
result = result + nums[i]; System.out.println("Average is " + result / 5);
}
}
 
Multidimensional Arrays
In Java, multidimensional arrays are actually arrays of arrays. These, as you might expect, look and act like regular multidimensional arrays. However, as you will see, there are a couple
of subtle differences. To declare a multidimensional array variable, specify each additional index using another set of square brackets. For example, the following declares a two- dimensional array variable called twoD:

int twoD[][] = new int[4][5];

This allocates a 4 by 5 array and assigns it to twoD. Internally this matrix is implemented as an array of arrays of int. Conceptually, this array will look like the one shown in Figure 3-1.
The following program numbers each element in the array from left to right, top to bottom, and then displays these values:

// Demonstrate a two-dimensional array. class TwoDArray {
public static void main(String args[]) { int twoD[][]= new int[4][5];
int i, j, k = 0;

for(i=0; i<4; i++) for(j=0; j<5; j++) {
twoD[i][j] = k; k++;
}

for(i=0; i<4; i++) { for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " "); System.out.println();
}
}
}
This program generates the following output:

0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19

When you allocate memory for a multidimensional array, you need only specify the memory for the first (leftmost) dimension. You can allocate the remaining dimensions separately. For example, this following code allocates memory for the first dimension of twoD when it is declared. It allocates the second dimension manually.

int twoD[][] = new int[4][]; twoD[0] = new int[5]; twoD[1] = new int[5]; twoD[2] = new int[5]; twoD[3] = new int[5];
 

















       
Figure 3-1 A conceptual view of a 4 by 5, two-dimensional array

While there is no advantage to individually allocating the second dimension arrays in this situation, there may be in others. For example, when you allocate dimensions manually, you do not need to allocate the same number of elements for each dimension. As stated earlier, since multidimensional arrays are actually arrays of arrays, the length of each array is under your control. For example, the following program creates a two-dimensional array in which the sizes of the second dimension are unequal:

// Manually allocate differing size second dimensions. class TwoDAgain {
public static void main(String args[]) { int twoD[][] = new int[4][];
twoD[0] = new int[1]; twoD[1] = new int[2]; twoD[2] = new int[3]; twoD[3] = new int[4];
int i, j, k = 0; for(i=0; i<4; i++)
for(j=0; j<i+1; j++) {
twoD[i][j] = k; k++;
}

for(i=0; i<4; i++) { for(j=0; j<i+1; j++)
System.out.print(twoD[i][j] + " "); System.out.println();
}
}
}
 
This program generates the following output:

0
1 2
3 4 5
6 7 8 9

The array created by this program looks like this:


 

 
 

 
 
 

 
 
 
 

The use of uneven (or irregular) multidimensional arrays may not be appropriate for many applications, because it runs contrary to what people expect to find when a
multidimensional array is encountered. However, irregular arrays can be used effectively in some situations. For example, if you need a very large two-dimensional array that is sparsely populated (that is, one in which not all of the elements will be used), then an irregular array might be a perfect solution.
It is possible to initialize multidimensional arrays. To do so, simply enclose each dimension's initializer within its own set of curly braces. The following program creates a matrix where each element contains the product of the row and column indexes. Also notice that you can use expressions as well as literal values inside of array initializers.

// Initialize a two-dimensional array. class Matrix {
public static void main(String args[]) { double m[][] = {
{ 0*0, 1*0, 2*0, 3*0 },
{ 0*1, 1*1, 2*1, 3*1 },
{ 0*2, 1*2, 2*2, 3*2 },
{ 0*3, 1*3, 2*3, 3*3 }
};
int i, j;

for(i=0; i<4; i++) { for(j=0; j<4; j++)
System.out.print(m[i][j] + " "); System.out.println();
}
}
}
 
When you run this program, you will get the following output:

0.0 0.0 0.0 0.0
0.0 1.0 2.0 3.0
0.0 2.0 4.0 6.0
0.0 3.0 6.0 9.0

As you can see, each row in the array is initialized as specified in the initialization lists.
Let's look at one more example that uses a multidimensional array. The following program creates a 3 by 4 by 5, three-dimensional array. It then loads each element with the product of its indexes. Finally, it displays these products.

// Demonstrate a three-dimensional array. class ThreeDMatrix {
public static void main(String args[]) { int threeD[][][] = new int[3][4][5]; int i, j, k;

for(i=0; i<3; i++) for(j=0; j<4; j++)
for(k=0; k<5; k++) threeD[i][j][k] = i * j * k;

for(i=0; i<3; i++) { for(j=0; j<4; j++) {
for(k=0; k<5; k++) System.out.print(threeD[i][j][k] + " ");
System.out.println();
}
System.out.println();
}
}
}
This program generates the following output:

0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 1 2 3 4
0 2 4 6 8
0 3 6 9 12
0 0 0 0 0
0 2 4 6 8
0 4 8 12 16
0 6 12 18 24
 
Alternative Array Declaration Syntax
There is a second form that may be used to declare an array:
type[ ] var-name;
Here, the square brackets follow the type specifier, and not the name of the array variable. For example, the following two declarations are equivalent:

int al[] = new int[3]; int[] a2 = new int[3];

The following declarations are also equivalent:

char twod1[][] = new char[3][4];
char[][] twod2 = new char[3][4];

This alternative declaration form offers convenience when declaring several arrays at the same time. For example,

int[] nums, nums2, nums3; // create three arrays creates three array variables of type int. It is the same as writing int nums[], nums2[], nums3[]; // create three arrays
The alternative declaration form is also useful when specifying an array as a return type for a method. Both forms are used in this book.

A Few Words About Strings
As you may have noticed, in the preceding discussion of data types and arrays there has been no mention of strings or a string data type. This is not because Java does not support such a type—it does. It is just that Java's string type, called String, is not a primitive type. Nor is it simply an array of characters. Rather, String defines an object, and a full description of it requires an understanding of several object-related features. As such, it will be covered later in this book, after objects are described. However, so that you can use simple strings in example programs, the following brief introduction is in order.
The String type is used to declare string variables. You can also declare arrays of strings. A quoted string constant can be assigned to a String variable. A variable of type String can be assigned to another variable of type String. You can use an object of type String as an argument to println( ). For example, consider the following fragment:

String str = "this is a test"; System.out.println(str);

Here, str is an object of type String. It is assigned the string "this is a test". This string is displayed by the println( ) statement.
As you will see later, String objects have many special features and attributes that make them quite powerful and easy to use. However, for the next few chapters, you will be using them only in their simplest form.
 
A Note to C/C++ Programmers About Pointers
If you are an experienced C/C++ programmer, then you know that these languages provide support for pointers. However, no mention of pointers has been made in this chapter. The reason for this is simple: Java does not support or allow pointers. (Or more properly, Java does not support pointers that can be accessed and/or modified by the programmer.) Java cannot allow pointers, because doing so would allow Java programs to breach the firewall between the Java execution environment and the host computer. (Remember, a pointer can be given any address in memory—even addresses that might be outside the Java run-time system.) Since C/C++ make extensive use of pointers, you might be thinking that their loss is a significant disadvantage to Java. However, this is not true. Java is designed in such a way that as long as you stay within the confines of the execution environment, you will never need to use a pointer, nor would there be any benefit in using one.

@£V£RYTHING NT
Continue reading
  1. Experto En Seguridad Informática
  2. Capture The Flag Hacking
  3. Hacker Definicion
  4. Fake Hacking
  5. Hacking Web Technologies Pdf
  6. Hacking Music
  7. Raspberry Pi Hacking
  8. Hacking Live
  9. Hardware Hacking Tools
  10. Life Hacking
  11. Linux Hacking
  12. Hacking Virus
  13. Hacking The Art Of Exploitation
  14. Como Aprender A Hackear