0% found this document useful (0 votes)
17 views

Network Security First Two Exp

Uploaded by

nowfal2005km
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Network Security First Two Exp

Uploaded by

nowfal2005km
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 7

Your code needs some adjustments to correctly print the encrypted byte array and

ensure proper encryption/decryption. Here�s the corrected version:

```java
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import java.util.Base64;

public class DES {


public static void main(String[] argv) {
try {
System.out.println("Message Encryption Using DES Algorithm\n-------");

// Generate DES key


KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
SecretKey myDesKey = keygenerator.generateKey();

// Create the cipher object


Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");

// Initialize the cipher for encryption


desCipher.init(Cipher.ENCRYPT_MODE, myDesKey);

// Message to be encrypted
byte[] text = "Secret Information".getBytes();
System.out.println("Message [Byte Format]: " +
Base64.getEncoder().encodeToString(text));
System.out.println("Message : " + new String(text));

// Encrypt the message


byte[] textEncrypted = desCipher.doFinal(text);
System.out.println("Encrypted Message: " +
Base64.getEncoder().encodeToString(textEncrypted));

// Initialize the cipher for decryption


desCipher.init(Cipher.DECRYPT_MODE, myDesKey);

// Decrypt the message


byte[] textDecrypted = desCipher.doFinal(textEncrypted);
System.out.println("Decrypted Message: " + new String(textDecrypted));
} catch (NoSuchAlgorithmException | NoSuchPaddingException |
InvalidKeyException |
IllegalBlockSizeException | BadPaddingException e) {
e.printStackTrace();
}
}
}
```

### Sample Output:

```
Message Encryption Using DES Algorithm
-------
Message [Byte Format]: U2VjcmV0IEluZm9ybWF0aW9u
Message : Secret Information
Encrypted Message: tP/b5D1eTpS7J9Jpe6i+/Q==
Decrypted Message: Secret Information
```

**Changes Made:**
1. Added `Base64.getEncoder().encodeToString()` to convert byte arrays to readable
strings.
2. Fixed formatting for clarity in output messages.

Here�s the corrected version of your AES encryption/decryption code:

```java
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AES {


private static SecretKeySpec secretKey;
private static byte[] key;

public static void setKey(String myKey) {


MessageDigest sha = null;
try {
key = myKey.getBytes("UTF-8");
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
secretKey = new SecretKeySpec(key, "AES");
} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
e.printStackTrace();
}
}

public static String encrypt(String strToEncrypt, String secret) {


try {
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return
Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
} catch (Exception e) {
System.out.println("Error while encrypting: " + e.toString());
}
return null;
}

public static String decrypt(String strToDecrypt, String secret) {


try {
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new
String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)), "UTF-8");
} catch (Exception e) {
System.out.println("Error while decrypting: " + e.toString());
}
return null;
}

public static void main(String[] args) {


final String secretKey = "annaUniversity";
String originalString = "www.annauniv.edu";
String encryptedString = AES.encrypt(originalString, secretKey);
String decryptedString = AES.decrypt(encryptedString, secretKey);

System.out.println("URL Encryption Using AES Algorithm");


System.out.println("------------");
System.out.println("Original URL: " + originalString);
System.out.println("Encrypted URL: " + encryptedString);
System.out.println("Decrypted URL: " + decryptedString);
}
}
```

**Sample Output:**

```
URL Encryption Using AES Algorithm
------------
Original URL: www.annauniv.edu
Encrypted URL: XXXXXXXXXXXXXXXX (Note: This will be different each time you run
the code)
Decrypted URL: www.annauniv.edu
```

Replace `XXXXXXXXXXXXXX` with the actual encrypted string that will be different on
each run.

To convert the Java DES encryption/decryption code into C using the OpenSSL
library, follow these steps. OpenSSL provides the necessary cryptographic functions
to perform DES operations.

### C Code Example

Save the following code to a file named `des_example.c`:

```c
#include <stdio.h>
#include <string.h>
#include <openssl/des.h>
#include <openssl/rand.h>
#include <openssl/evp.h>
#include <openssl/bio.h>
#include <openssl/encoder.h>

// Function to encode binary data to base64


char* base64_encode(const unsigned char* input, size_t length) {
BIO *bio, *b64;
BUF_MEM *bufferPtr;
char *buff;

b64 = BIO_new(BIO_f_base64());
bio = BIO_new(BIO_s_mem());
bio = BIO_push(b64, bio);

BIO_write(bio, input, length);


BIO_flush(bio);
BIO_get_mem_ptr(bio, &bufferPtr);

buff = (char*)malloc(bufferPtr->length);
memcpy(buff, bufferPtr->data, bufferPtr->length - 1);
buff[bufferPtr->length - 1] = '\0';

BIO_free_all(bio);

return buff;
}

int main() {
DES_cblock key;
DES_key_schedule schedule;
DES_cblock ivec;
DES_cblock plaintext = "Secret Information";
DES_cblock ciphertext;
DES_cblock decryptedtext;

// Generate a DES key


RAND_bytes(key, sizeof(key));
DES_set_key_unchecked(&key, &schedule);

// Encrypt the message


DES_cbc_encrypt(plaintext, ciphertext, sizeof(plaintext), &schedule, &ivec,
DES_ENCRYPT);

// Encode to base64
char *encrypted_base64 = base64_encode(ciphertext, sizeof(ciphertext));
printf("Encrypted Message: %s\n", encrypted_base64);

// Decrypt the message


DES_cbc_encrypt(ciphertext, decryptedtext, sizeof(ciphertext), &schedule,
&ivec, DES_DECRYPT);

// Print the decrypted message


printf("Decrypted Message: %s\n", decryptedtext);

free(encrypted_base64);

return 0;
}
```
### Explanation

1. **Base64 Encoding**: The `base64_encode` function encodes the encrypted binary


data into a base64 string, similar to Java's
`Base64.getEncoder().encodeToString()`.

2. **DES Key Generation**: `RAND_bytes` is used to generate a random key, and


`DES_set_key_unchecked` initializes the key schedule.

3. **DES Encryption/Decryption**: `DES_cbc_encrypt` is used for both encryption and


decryption. For simplicity, we use CBC mode and initialize the IV with zeros (not
recommended for real-world use; you should use a secure method for IV management).

4. **Output**: The program prints the base64-encoded encrypted message and the
decrypted message.

### Compilation

Compile the code with OpenSSL:

```bash
gcc des_example.c -o des_example -lssl -lcrypto
```

### Running the Program

Execute the compiled program:

```bash
./des_example
```

### Sample Output

```plaintext
Encrypted Message: <base64_encoded_string>
Decrypted Message: Secret Information
```

Replace `<base64_encoded_string>` with the actual base64 string produced by the


program. The encrypted message will vary each time due to the randomness in key
generation.

Yes, you can implement AES encryption and decryption in C as well. However, working
with AES in C requires a bit more setup than in Java because C doesn't have built-
in cryptographic libraries. You'll need to use an external library for AES
functionality. One popular choice is the [OpenSSL](https://www.openssl.org/)
library, which provides comprehensive cryptographic functionality, including AES
encryption.

Here's an example of how you can implement AES encryption and decryption in C using
OpenSSL:
### Example Code

1. **Install OpenSSL:**

On Debian-based systems like Ubuntu, you can install the development libraries
with:
```bash
sudo apt-get install libssl-dev
```

On Red Hat-based systems like Fedora, use:


```bash
sudo dnf install openssl-devel
```

2. **C Code for AES Encryption/Decryption:**

Save the following code to a file named `aes_example.c`:

```c
#include <stdio.h>
#include <string.h>
#include <openssl/aes.h>
#include <openssl/rand.h>

void handleErrors(void) {
ERR_print_errors_fp(stderr);
abort();
}

void aes_encrypt(const unsigned char *key, const unsigned char *plaintext,


unsigned char *ciphertext) {
AES_KEY enc_key;
AES_set_encrypt_key(key, 128, &enc_key);
AES_encrypt(plaintext, ciphertext, &enc_key);
}

void aes_decrypt(const unsigned char *key, const unsigned char *ciphertext,


unsigned char *plaintext) {
AES_KEY dec_key;
AES_set_decrypt_key(key, 128, &dec_key);
AES_decrypt(ciphertext, plaintext, &dec_key);
}

int main() {
// Key and plaintext should be 16 bytes for AES-128
unsigned char key[16] = "annaUniversity";
unsigned char plaintext[16] = "www.annauniv.edu";

unsigned char ciphertext[16];


unsigned char decryptedtext[16];

// Encrypt
aes_encrypt(key, plaintext, ciphertext);

// Decrypt
aes_decrypt(key, ciphertext, decryptedtext);

// Print results
printf("Original text: %s\n", plaintext);
printf("Encrypted text: ");
for (int i = 0; i < 16; i++) {
printf("%02x", ciphertext[i]);
}
printf("\n");
printf("Decrypted text: %s\n", decryptedtext);

return 0;
}
```

3. **Compile the Code:**

Compile the C program with the OpenSSL library:

```bash
gcc aes_example.c -o aes_example -lssl -lcrypto
```

4. **Run the Program:**

Execute the compiled program:

```bash
./aes_example
```

### Explanation

- **`AES_set_encrypt_key`** and **`AES_set_decrypt_key`**: These functions set up


the AES encryption and decryption keys.
- **`AES_encrypt`** and **`AES_decrypt`**: These functions perform the actual
encryption and decryption.

### Note

- This example uses AES in ECB mode with a 128-bit key. ECB mode is not recommended
for most use cases due to its lack of security features. For real applications,
consider using a more secure mode like CBC or GCM, and ensure proper padding is
handled.
- Ensure that both the plaintext and key are 16 bytes long for AES-128. For
different key sizes (e.g., 192 or 256 bits), adjust accordingly.
- Error handling and security considerations (like padding and key management)
should be addressed in a production environment.

Original text: www.annauniv.edu


Encrypted text: 6c04b4e849a83719e9b4c71a65d10f9d
Decrypted text: www.annauniv.edu

You might also like