Professional Documents
Culture Documents
Encrypt A Message in Java
Encrypt A Message in Java
import java.io.*;
import javax.crypto.*;
import javax.crypto.spec.*;
SecretKeySpec keySpec =
IvParameterSpec ivSpec =
new IvParameterSpec("fedcba9876543210".getBytes());
FileInputStream fis =
FileOutputStream fos =
int i;
fos.write(b, 0, i);
fos.flush(); fos.close();
cis.close(); fis.close();
The above Java program will encrypted PDF file. It takes the unencrypted PDF file (plain.pdf) and create
encrypted.pdf (the encrypted file).
Now with the encrypted.pdf, we use a PHP program to decrypt it:
<?php
$secret_key = "01234567890abcde";
$iv = "fedcba9876543210";
$infile = "encrypted.pdf";
$outfile = "decrypted.pdf";
$crypttext = file_get_contents($infile);
$plaintext = mcrypt_decrypt(MCRYPT_RIJNDAEL_128,
header('Content-Type: application/octet-stream');
echo $plaintext;
?>
The PHP program takes the encrypted.pdf and force download the decrypted.pdf which should be the
same as the plain.pdf.
<?php
$secret_key = "01234567890abcde";
$iv = "fedcba9876543210";
$infile = "plain.pdf";
$outfile = "encrypted.pdf";
$plaintext = file_get_contents($infile);
$crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128,
header('Content-Type: application/octet-stream');
echo $crypttext;
?>
The above PHP program will force an encrypted PDF file down from your browser. It takes the
unencrypted PDF file (plain.pdf) and force a download of encrypted.pdf (the encrypted file).
Now after saving the encrypted.pdf, we use a Java program to decrypt it:
import java.io.*;
import javax.crypto.*;
import javax.crypto.spec.*;
int i;
fos.write(b, 0, i);
fos.flush(); fos.close();
cis.close(); fis.close();
?>
The Java program takes the encrypted.pdf and write out the decrypted.pdf which should be the same as
the plain.pdf.