Read public key from file - java

i am trying to verify a file with my java program. I have no idea what i am doing wrong, all the solutions i found does not work.
Here is my code:
public boolean pruefeSignatur(File file, File signatur, File publicKey) {
boolean verifies = false;
try {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
// encode public key bytes
FileInputStream keyfis = new FileInputStream(publicKey);
byte [] encKey = new byte[keyfis.available()];
keyfis.read(encKey);
keyfis.close();
// key specification
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encKey);
// conversion
KeyFactory keyFactory = KeyFactory.getInstance(pubKeySpec.getFormat());
// generate publicKey
PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
// input signature bytes
FileInputStream sigfis = new FileInputStream(signatur);
byte[] sigToVerify = new byte[sigfis.available()];
sigfis.read(sigToVerify);
sigfis.close();
// initialize the signature
Signature sig = Signature.getInstance("RSA");
sig.initVerify(pubKey);
// supply signature object with the data to be verified
FileInputStream datafis = new FileInputStream(file);
BufferedInputStream bufin = new BufferedInputStream(datafis);
byte[] buffer = new byte[1024];
int len;
while(bufin.available() != 0) {
len = bufin.read(buffer);
sig.update(buffer, 0, len);
}
bufin.close();
//verify signature
verifies = sig.verify(sigToVerify);
} catch (Exception e) {
e.printStackTrace();
}
return verifies;
}
With this code i get the exception:
java.security.spec.InvalidKeySpecException: java.lang.ClassCastException: org.bouncycastle.asn1.DERUnknownTag cannot be cast to org.bouncycastle.asn1.ASN1Object
When i use Base64, for example:
Base64 decoder = new Base64();
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(decoder.decode(encKey));
I get the exception:
java.security.spec.InvalidKeySpecException: java.io.IOException: unexpected end-of-contents marker
Another solution i found was changing it to:
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encKey);
// conversion
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
But then i get the exception:
java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format
I made my keys with Gpg4win and Kleopatra.
Edit:
Now I do not get an error, but the function always returns false. So I am not sure if everything is right.
public boolean pruefeSignatur(File file, File signaturFile, File publicKeyFile) throws IOException {
boolean verifies = false;
FileInputStream keyfis = null;
DataInputStream keydis = null;
FileInputStream sigfis = null;
DataInputStream sigdis = null;
FileInputStream datafis = null;
DataInputStream datadis = null;
try {
// add provider
Security.addProvider(new BouncyCastleProvider());
// encode public key bytes
keyfis = new FileInputStream(publicKeyFile);
keydis = new DataInputStream(keyfis);
byte[] keyBytes = new byte[(int) publicKeyFile.length()];
keydis.readFully(keyBytes);
keyfis.close();
keydis.close();
// key specification
String modulusBase64 = new String(keyBytes);
Base64 b64 = new Base64();
String exponentBase64 = "65337"; //festgelegte Zahl http://crypto.stackexchange.com/questions/3110/impacts-of-not-using-rsa-exponent-of-65537
RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(1, b64.decode(modulusBase64)), new BigInteger(1, b64.decode(exponentBase64)));
// conversion
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
// generate publicKey
PublicKey publicKey = keyFactory.generatePublic(pubKeySpec);
// read signature
sigfis = new FileInputStream(signaturFile);
sigdis = new DataInputStream(sigfis);
byte[] sigBytes = new byte[(int) signaturFile.length()];
sigdis.readFully(sigBytes);
sigfis.close();
sigdis.close();
// initialize the signature
Signature sig = Signature.getInstance("RSA");
sig.initVerify(publicKey);
// supply signature object with the data to be verified
datafis = new FileInputStream(file);
datadis = new DataInputStream(datafis);
byte[] dataBytes = new byte[(int) file.length()];
datadis.readFully(dataBytes);
/*
int len;
while(datadis.available() != 0) {
len = datadis.read(dataBytes);
sig.update(dataBytes, 0, len);
}
*/
datadis.close();
datafis.close();
sig.update(dataBytes);
//verify signature
verifies = sig.verify(sigBytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (keyfis != null) {
keyfis.close();
}
if (keydis != null) {
keydis.close();
}
if (sigfis != null) {
sigfis.close();
}
if (sigdis != null) {
sigdis.close();
}
if (datafis != null) {
datafis.close();
}
if (datadis != null) {
datadis.close();
}
}
return verifies;
}

Finally i have a solution:
InputStream inSig = PGPUtil.getDecoderStream(new FileInputStream(signaturFile));
//ArmoredInputStream inSig = new ArmoredInputStream(new FileInputStream(signaturFile));
JcaPGPObjectFactory objFactory = new JcaPGPObjectFactory(inSig);
PGPSignatureList signatureList = (PGPSignatureList) objFactory.nextObject();
PGPSignature signature = signatureList.get(0);
InputStream keyIn = PGPUtil.getDecoderStream(new FileInputStream(publicKeyFile));
//ArmoredInputStream keyIn = new ArmoredInputStream(new FileInputStream(publicKeyFile));
JcaPGPPublicKeyRingCollection pgpRing = new JcaPGPPublicKeyRingCollection(keyIn);
PGPPublicKey publicKey = pgpRing.getPublicKey(signature.getKeyID());
byte[] bytePublicKeyFingerprint = publicKey.getFingerprint();
char[] publicKeyFingerprintHexArray = org.apache.commons.codec.binary.Hex.encodeHex(bytePublicKeyFingerprint);
String publicKeyFingerprintHex = new String(publicKeyFingerprintHexArray);
signature.init(new JcaPGPContentVerifierBuilderProvider().setProvider("BC"), publicKey);
FileInputStream in = new FileInputStream(file);
byte[] byteData = new byte[(int) file.length()];
in.read(byteData);
in.close();
signature.update(byteData);
if (signature.verify() && publicKeyFingerprintHex.equals(fingerprint)) {
return true;
} else {
return false;
}

Related

AES+ Base64 Decrypt file appeared garbled

I am using socket to transfer file and AES 256 to encrypt/decrypt, I use the byte array to accept file's content and encrypt it, but only the first byte size array success to decrypt and other appeared garbled(the encrypted byte size extend to 1368 and AES block size is 128bits not sure is it effect),below is my code:
public void sendfile() {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
byte[] byteArray = new byte[1024];
int bytesCount = 0;
while ((bytesCount = fis.read(byteArray)) >= 0) {
String encryptString = new String(byteArray, "UTF-8");
bos.write(EncryptAES.encrypt(encryptString, "12345").getBytes("UTF-8"));
}
}
public void receiveFile(File file, BufferedInputStream bis) {
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
byte[] byteArray = new byte[1024];
int bytesCount = 0;
while ((bytesCount = bis.read(byteArray)) >= 0) {
String encryptString = new String(byteArray, "UTF-8");
bos.write(EncryptAES.decrypt(encryptString, "12345").getBytes("UTF-8"));
}
}
public static String encrypt(String content,SecretKey secretKey) {
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] byteContent = cipher.doFinal(content.getBytes("UTF-8"));
return Base64.getEncoder().withoutPadding().encodeToString(byteContent);
}
public static String decrypt(String content,SecretKey secretKey) {
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Security.addProvider(new BouncyCastleProvider());
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding", "BC");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] byteCipherText = Base64.getDecoder().decode(content);
String encryptString = new String(byteCipherText, "UTF-8");
byte[] decryptedText = cipher.doFinal(byteCipherText);
encryptString = new String(decryptedText, "UTF-8");
return new String(decryptedText, "UTF-8");
}

How to encrypt & decrypt large video file

I would like to store video files in storage that can be accessed only my application. outside the user should not be able to access his video. I tried Encryption & Decryption but the video file is too large (1GB) it takes a lot of time.
Do you have any Idea guys how can I do?
Please find below my Encryption & Decryption Code :
private File sdCardRoot;
private ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sdCardRoot = Environment.getExternalStorageDirectory();
Button encrypt = findViewById(R.id.zip);
Button dencrypt = findViewById(R.id.unzip);
progressBar = findViewById(R.id.progress);
encrypt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
progressBar.setVisibility(View.VISIBLE);
try {
Log.e("file", "try");
encryption();
} catch (Exception e) {
Log.e("file", "catch" + String.valueOf(e));
e.printStackTrace();
}
}
});
dencrypt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
progressBar.setVisibility(View.VISIBLE);
try {
dcryption();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void dcryption() throws Exception {
progressBar.setVisibility(View.VISIBLE);
String password = "javapapers";
// reading the salt
// user should have secure mechanism to transfer the
// salt, iv and password to the recipient
File fileSalt = new File(sdCardRoot, "/salt.enc");
FileInputStream saltFis = new FileInputStream(fileSalt);
byte[] salt = new byte[8];
saltFis.read(salt);
saltFis.close();
// reading the iv
File fileIv = new File(sdCardRoot, "/iv.enc");
FileInputStream ivFis = new FileInputStream(fileIv);
byte[] iv = new byte[16];
ivFis.read(iv);
ivFis.close();
SecretKeyFactory factory = SecretKeyFactory
.getInstance("PBKDF2WithHmacSHA1");
KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, 65536,
256);
SecretKey tmp = factory.generateSecret(keySpec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
// file decryption
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
File oldFile = new File(sdCardRoot, "/wp.mp4");
File oldFile1 = new File(sdCardRoot, "/w.des");
FileInputStream fis = new FileInputStream(oldFile1);
FileOutputStream fos = new FileOutputStream(oldFile);
byte[] in = new byte[64];
int read;
while ((read = fis.read(in)) != -1) {
byte[] output = cipher.update(in, 0, read);
if (output != null)
fos.write(output);
}
byte[] output = cipher.doFinal();
if (output != null) {
fos.write(output);
fis.close();
fos.flush();
fos.close();
}
if (fileIv.exists() && fileSalt.exists() && oldFile1.exists()) {
fileIv.delete();
fileSalt.delete();
oldFile1.delete();
}
progressBar.setVisibility(View.GONE);
System.out.println("File Decrypted.");
}
private void encryption() throws Exception {
File oldFile = new File(sdCardRoot, "/w.mp4");
File oldFile1 = new File(sdCardRoot, "/w.des");
Log.e("file", String.valueOf(oldFile));
FileInputStream inFile = new FileInputStream(oldFile);
Log.e("file", String.valueOf(inFile));
// encrypted file
FileOutputStream outFile = new FileOutputStream(oldFile1);
Log.e("file", String.valueOf(outFile));
// password to encrypt the file
String password = "javapapers";
// password, iv and salt should be transferred to the other end
// in a secure manner
// salt is used for encoding
// writing it to a file
// salt should be transferred to the recipient securely
// for decryption
byte[] salt = new byte[8];
SecureRandom secureRandom = new SecureRandom();
secureRandom.nextBytes(salt);
Log.e("file", "a");
File fileSalt = new File(sdCardRoot, "/salt.enc");
FileOutputStream saltOutFile = new FileOutputStream(fileSalt);
Log.e("file", "b");
saltOutFile.write(salt);
saltOutFile.close();
SecretKeyFactory factory = SecretKeyFactory
.getInstance("PBKDF2WithHmacSHA1");
KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, 65536,
256);
SecretKey secretKey = factory.generateSecret(keySpec);
SecretKey secret = new SecretKeySpec(secretKey.getEncoded(), "AES");
//
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
AlgorithmParameters params = cipher.getParameters();
// iv adds randomness to the text and just makes the mechanism more
// secure
// used while initializing the cipher
// file to store the iv
Log.e("file", "c");
File fileIv = new File(sdCardRoot, "/iv.enc");
FileOutputStream ivOutFile = new FileOutputStream(fileIv);
Log.e("file", "d");
byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
ivOutFile.write(iv);
ivOutFile.close();
//file encryption
byte[] input = new byte[64];
int bytesRead;
while ((bytesRead = inFile.read(input)) != -1) {
byte[] output = cipher.update(input, 0, bytesRead);
if (output != null)
outFile.write(output);
}
byte[] output = cipher.doFinal();
if (output != null)
outFile.write(output);
inFile.close();
outFile.flush();
outFile.close();
if (oldFile.exists()) {
oldFile.delete();
}
System.out.println("File Encrypted.");
}
Use Below Code:
import java.io.File;
import java.io.RandomAccessFile;
public class VideoCrypt {
public static final int REVERSE_BYTE_COUNT = 1024;
public static boolean decrypt(String path) {
try {
if (path == null) return false;
File source = new File(path);
int byteToReverse = source.length() < REVERSE_BYTE_COUNT ? ((int) source.length()) : REVERSE_BYTE_COUNT;
RandomAccessFile f = new RandomAccessFile(source, "rw");
f.seek(0);
byte b[] = new byte[byteToReverse];
f.read(b);
f.seek(0);
reverseBytes(b);
f.write(b);
f.seek(0);
b = new byte[byteToReverse];
f.read(b);
f.close();
return true;
} catch (Exception e) {
return false;
}
}
public static boolean encrypt(String path) {
try {
if (path == null) return false;
File source = new File(path);
RandomAccessFile f = new RandomAccessFile(source, "rw");
f.seek(0);
int byteToReverse = source.length() < REVERSE_BYTE_COUNT ? ((int) source.length()) : REVERSE_BYTE_COUNT;
byte b[] = new byte[byteToReverse];
f.read(b);
f.seek(0);
reverseBytes(b);
f.write(b);
f.seek(0);
b = new byte[byteToReverse];
f.read(b);
f.close();
return true;
} catch (Exception e) {
return false;
}
}
private static void reverseBytes(byte[] array) {
if (array == null) return;
int i = 0;
int j = array.length - 1;
byte tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j--;
i++;
}
}
}
File types are identified by file extension and file magic. If you want to skip encrypting the file you can edit the file header by changing its magic so that programs can't recognize the type. A "magic" is a few bytes at the start of the file that define its type.

javax.crypto.BadPaddingException: Given final block not properly padded while decrypting a file

I am trying to write a program to encrypt and decrypt files using java, but I get an error on the decrypt function:
Caused by: javax.crypto.BadPaddingException: Given final block not properly padded
here is the code for the encryption:
public static void EncryptFile(String inFile, PublicKey rsaPublicKey) {
AesManaged aesManaged = new AesManaged();
try {
aesManaged.keySize = 256;
aesManaged.blockSize = 128;
aesManaged.mode = "AES/CBC/PKCS5Padding";
byte[] key = generateKey(aesManaged.keySize);
byte[] keyEncrypted = encryptKey(key, rsaPublicKey);
byte[] LenK = new byte[4];
byte[] LenIV = new byte[4];
int lKey = keyEncrypted.length;
LenK = BitConverter.GetBytes(lKey);
int lIV = aesManaged.IV().length;
LenIV = BitConverter.GetBytes(lIV);
// Write the following to the FileStream
// for the encrypted file (outFs):
// - length of the key
// - length of the IV
// - ecrypted key
// - the IV
// - the encrypted cipher content
String outFile = "test.lamar";
ByteArrayOutputStream outFs = new ByteArrayOutputStream();
outFs.write(LenK);
outFs.write(LenIV);
outFs.write(keyEncrypted);
byte[] i = aesManaged.IV();
outFs.write(i);
IvParameterSpec ivspec = new IvParameterSpec(aesManaged.IV());
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance(aesManaged.mode);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivspec);
FileInputStream fileIn = new FileInputStream(inFile);
CipherOutputStream cipherOut = new CipherOutputStream(outFs, cipher);
int blockSiseByte = aesManaged.blockSize / 8;
byte[] data = new byte[blockSiseByte];
int count;
// Read in the data from the file and encrypt it
while ((count = fileIn.read(data, 0, blockSiseByte)) != -1) {
cipherOut.write(data, 0, count);
}
try (OutputStream outputStream = new FileOutputStream(outFile)) {
outFs.writeTo(outputStream);
}
// Close the encrypted file
fileIn.close();
outFs.close();
cipherOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
and the code for the decryption:
public static void DecryptFile(String inFile, String outFile,
PrivateKey rsaPrivateKey) {
FileOutputStream outFs = null;
try {
// Create instance of AesManaged for
// symetric decryption of the data.
AesManaged aesManaged = new AesManaged();
{
aesManaged.keySize = 256;
aesManaged.blockSize = 128;
aesManaged.mode = "AES/CBC/PKCS5Padding";
// Create byte arrays to get the length of
// the encrypted key and IV.
// These values were stored as 4 bytes each
// at the beginning of the encrypted package.
byte[] LenK = new byte[4];
byte[] LenIV = new byte[4];
// Use FileStream objects to read the encrypted
// file (inFs) and save the decrypted file (outFs).
{
byte[] fileBytes = FileUtils.readFileToByteArray(new File(inFile));
ByteArrayInputStream inFs = new ByteArrayInputStream(
fileBytes);
;
for (int i = 0; i < LenK.length; i++) {
LenK[i] = (byte) inFs.read();
}
for(int i = 0; i< LenIV.length;i++){
LenIV[i] = (byte)inFs.read();
}
// Convert the lengths to integer values.
int lenK = BitConverter.ToInt32(LenK, 0);
int lenIV = BitConverter.ToInt32(LenIV, 0);
//int startC = lenK + lenIV + 8;
//int lenC = (int) fileBytes.length - startC;
// Create the byte arrays for
// the encrypted AesManaged key,
// the IV, and the cipher text.
byte[] KeyEncrypted = new byte[lenK];
byte[] IV = new byte[lenIV];
// Extract the key and IV
for(int i = 0;i<lenK;i++){
KeyEncrypted[i] = (byte)inFs.read();
}
for(int i =0;i<lenIV;i++){
IV[i] = (byte)inFs.read();
}
// to decrypt the AesManaged key.
byte[] KeyDecrypted = decryptKey(KeyEncrypted,rsaPrivateKey);
Cipher transform = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ivspec = new IvParameterSpec(IV);
SecretKeySpec secretKeySpec = new SecretKeySpec(KeyDecrypted, "AES");
transform.init(Cipher.DECRYPT_MODE, secretKeySpec, ivspec);
// Decrypt the key.
outFs = new FileOutputStream(outFile);
int count = 0;
int offset = 0;
int blockSizeBytes = aesManaged.blockSize / 8;
byte[] data = new byte[blockSizeBytes];
CipherInputStream cipherIn = new CipherInputStream(
inFs, transform);
while ((count = cipherIn.read(data, 0, blockSizeBytes)) != -1) {
outFs.write(data, 0, count);
}
inFs.close();
cipherIn.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
The error occurred at the line:while ((count = cipherIn.read(data, 0, blockSizeBytes)) != -1) after many iterations.
What am I missing here?

RSA - Encrypt in Android / Decrypt in PHP

I encrypt a word in java and I have trouble decrypting it in php.
here is how I create the keys in android:
public void GenerateAndSaveToFile(){
try {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
KeyPair kp = kpg.genKeyPair();
Key publicKey = kp.getPublic();
Key privateKey = kp.getPrivate();
KeyFactory fact = KeyFactory.getInstance("RSA");
RSAPublicKeySpec pub = fact.getKeySpec(kp.getPublic(), RSAPublicKeySpec.class);
RSAPrivateKeySpec priv = fact.getKeySpec(kp.getPrivate(), RSAPrivateKeySpec.class);
//////////////////////////
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
File myDir = new File(root + "/keys");
myDir.mkdirs();
File file = new File (myDir, "private.key");
FileOutputStream fileout1 = new FileOutputStream(file);
ObjectOutputStream oout1 = new ObjectOutputStream(fileout1);
oout1.writeObject(priv.getModulus());
oout1.writeObject( priv.getPrivateExponent());
oout1.close();
///////////////////////
File file2 = new File (myDir, "public.key");
FileOutputStream fileout2 = new FileOutputStream(file2);
ObjectOutputStream oout2 = new ObjectOutputStream(new BufferedOutputStream(fileout2));
oout2.writeObject(pub.getModulus());
oout2.writeObject( pub.getPublicExponent());
oout2.close();
}
catch (Exception ex){
Exception e = ex;
}
}
here is how I encrypt the word with generated public key in android:
byte[] u1Encrypted = RSAEncrypt(String.valueOf(inputEmail.getText()).getBytes());
public byte[] RSAEncrypt(byte[] data) {
try {
PublicKey pubKey = ReadPublicKey();
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] cipherData = cipher.doFinal(data);
return cipherData;
}
catch (Exception ex)
{
Exception e = ex;
return null;
}
}
private PublicKey ReadPublicKey() throws IOException {
try {
AssetManager assetManager = getAssets();
InputStream in = assetManager.open("public.key");
ObjectInputStream oin = new ObjectInputStream(new BufferedInputStream(in));
try {
BigInteger m = (BigInteger) oin.readObject();
BigInteger e = (BigInteger) oin.readObject();
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);
KeyFactory fact = KeyFactory.getInstance("RSA");
PublicKey pubKey = fact.generatePublic(keySpec);
return pubKey;
} catch (Exception e) {
throw new RuntimeException("Spurious serialisation error", e);
} finally {
oin.close();
}
}
catch (Exception ex)
{
Exception e = ex;
return null;
}
}
then I convert the encrypted string to base64 in android:
String u1EncryptedBase64 = Base64.encodeToString(u1Encrypted, Base64.DEFAULT);
and in php I decode the base64 string:
$encryptedString = base64_decode(u1EncryptedBase64);
get the private key:
$keytmp = fopen("../../../private.key", "r") or die("Unable to open file!");
$key = fread($keytmp,filesize("../../../private.key"));
$res = openssl_get_privatekey($key);
and finally I try to decrypt the string in php:
if (openssl_private_decrypt($encryptedString, $decrypted, $res)) {
echo $decrypted;
}
else
{
echo "problem";
}
and error I get is:
Warning: openssl_private_decrypt(): key parameter is not a valid private key ...
please guide me how to accompolish this task.
thanks
I can show you how i have done encryption in my android and decryption in php. It worked wonderfully fine.May be you can get some help from this. In android the code is like:
final private static String RSA_public_key="MIIBIDANBgkqhkiG9w0BAQEFAAOCAQ0AMIIBCAKCAQEApeRuOhn71+wcRtlN6JoW\n" +
"JLrVE5HKLPukFgpMdguNskBwDOPrrdYKP1e3rZMHN9oVB/QTTpkQM4CrGYlstUmT\n" +
"u5nEfdsH4lHRxe3qhi9+zOknWKJCnW4Cq70oITCAK08BIJ/4ZcGM1SUyv1+0u1aB\n" +
"cx6g1aKhthttRjNpck2LBaHVolt7Z4FTb5SdZMwJKRyEv8fuP6yyR0CJGEbQKZKA\n" +
"ODNKyqJ42sVzUQ2AMQIWdhkFdAFahKCL4MChGvKU6F20cHdvokyxXJjU3sZobjNf\n" +
"i+8FzH9hd7y8kmi4o3AKP69p5asgflXoXHpo135i3NzZqlNJ+Bs9pY+90u9iLScp\n" +
"JwIBAw==";
static String enccriptData(String txt)
{
String encoded = "";
byte[] encrypted = null;
try {
byte[] publicBytes = Base64.decode(RSA_public_key, Base64.DEFAULT);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pubKey = keyFactory.generatePublic(keySpec);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING"); //or try with "RSA"
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
encrypted = cipher.doFinal(txt.getBytes());
encoded = Base64.encodeToString(encrypted, Base64.DEFAULT);
}
catch (Exception e) {
e.printStackTrace();
}
return encoded;
}
I have paste that encoded string that is returned in the above function in below $string. This is the code for php:
<?php
$string="W39VlV1Q96QzDIR/jINzaEL7rh2Z+Z90uxJ1DtaSfkVKzIgt2TIkxsuRY+A2icwPtTdq6+9j1Xb009KT+ck2KD+dot3wPL5UaHqApbZSi6UZan/nDbFCNJdffTlTWsPS2ThEefeMMSs8HE2ORSt42D8cxYlogOvkvlLr60cHYKwfC1itLSqPuYR+C/gPAf6yCteLbj//EkJp8TemlmPi0eSsH492FgrmBqiTOS4LzpzsPFpSI4KJbuM2dvqp5jkt7MnpR1laILmyC37fA5XPUQmEQChoG5eSbMxqO7SPboYC1BH9ATy6uTS1MGXGDzJ2FSJ41MMRV1Ul/4UNFVA8Ng==";
$encryptedString = base64_decode($string);
$key="-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCl5G46GfvX7BxG
2U3omhYkutUTkcos+6QWCkx2C42yQHAM4+ut1go/V7etkwc32hUH9BNOmRAzgKsZ
iWy1SZO7mcR92wfiUdHF7eqGL37M6SdYokKdbgKrvSghMIArTwEgn/hlwYzVJTK/
X7S7VoFzHqDVoqG2G21GM2lyTYsFodWiW3tngVNvlJ1kzAkpHIS/x+4/rLJHQIkY
RtApkoA4M0rKonjaxXNRDYAxAhZ2GQV0AVqEoIvgwKEa8pToXbRwd2+iTLFcmNTe
xmhuM1+L7wXMf2F3vLySaLijcAo/r2nlqyB+VehcemjXfmLc3NmqU0n4Gz2lj73S
72ItJyknAgEDAoIBAG6YSXwRUo/yvYSQ3psRZBh8jg0L3B39GA6xiE6yXnbVoAiX
8nPkBtTlJR5iBM/muK/4DN8QtXerHLuw8yOGYn0RLak8r+w2i9lJRwQfqd3wxOXB
gb5JVx0oxWt1qseKAMBqpZkrszjDdyo/zdI5q6IUazkXFnlnni7M8PbeXK5q0PE6
0XclC1W79jX71D8d24SITAfXDqaXOwObSn9dadw1gsxx8fPd6Fr7ZTS0AddxJZN2
jNK14xkv2rkxdP1W529gnCVQUhju5SPJS5QwphI7KyfH7wTHnBOhbhp3FpaVKPz0
biLwZ6D0xgR6reZofz+t1cvDOha54wC4ZZYJyTsCgYEA0blJn8zxAHDSj8z/01zz
dc1qdYfdlf9gEWgr+APS9XSowGg+CdQN2W0XwySlpPoMZyCKM/aH0DNcl11yynpL
Mkm5MU2V2T+VKWXwUNHrGXSVRJkgLu+iD1Pt0oGPfS9qRYydG5TBjQEVrBrh4Jtk
KdsMBA82mgxEdFqtERbTpi0CgYEAyn85oWfYwf4oHEbSd218RauRBqwMhk39nyqx
6Gaza/k6Ri+5hBjqvVt8pT1Obrji5fZFU1IH5wecQae1mvIQJv+tVBy+XPedU8Mo
Jj3/TPwBAHezTADvQyEIwPot6y5lZt2fX7Urv+n1k7XkfWfb8O/ChTc/zHc0dPct
uLVE1SMCgYEAi9Dbv932AEs3CoiqjOiiTojxo6/pDqpAC5rH+q03Tk3F1ZrUBo1e
kPNlLMMZGKay72sGzU8FNXeTD5Oh3FGHdtvQy4kOkNUOG5lK4IvyEPhjgxDAH0ps
Cjfz4au0/h+cLl2+EmMrs1YOcryWlbztcTyyrV95vAgtouceC2SNGXMCgYEAhv97
wO/l1qlwEtnhpPOoLnJgrx1drt6pFMchRZnM8qYm2XUmWBCcfjz9w340SdCXQ/mD
jOFamgUS1m/OZ0wKxKpzjWh+6KUTjSzFbtP/iKgAqvp3iACfghYF1fwenMmY7z5q
P84dKpv5DSPtqO/n9fUsWM9/3aTNo09z0HjYjhcCgYEAoN+1/ZzonPWDIY/u+7bW
e8BkcuBVpMZe7qBYHeVix89yvyuVE+erKqurnG7fN7YIDX8V1OcVP+qHw8fJNQKL
wd03nNIIJyTPXodgty3HYjBUe8fVn/8P+JOv2U7bJCkUGlFeyZIMZWEsYd8t5794
3fotiYXOUug9bFtnGHRyY7I=
-----END PRIVATE KEY-----";
openssl_private_decrypt($encryptedString, $decrypted, $key);
$string1=$decrypted;
echo $string1;
?>
The private and public keys are made for each other.

Issues in RSA encryption in Java class

public class MyEncrypt {
public void saveToFile(String fileName, BigInteger mod, BigInteger exp) throws IOException {
ObjectOutputStream oout = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(fileName)));
try {
oout.writeObject(mod);
oout.writeObject(exp);
} catch (Exception e) {
throw new IOException("Unexpected error", e);
} finally {
oout.close();
}
}
public static void main(String[] args) throws Exception {
MyEncrypt myEncrypt = new MyEncrypt();
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(128);
KeyPair kp = kpg.genKeyPair();
RSAPublicKey publicKey = (RSAPublicKey) kp.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) kp.getPrivate();
KeyFactory fact = KeyFactory.getInstance("RSA");
RSAPublicKeySpec pub = fact.getKeySpec(kp.getPublic(), RSAPublicKeySpec.class);
RSAPrivateKeySpec priv = fact.getKeySpec(kp.getPrivate(), RSAPrivateKeySpec.class);
myEncrypt.saveToFile("public.key", pub.getModulus(), pub.getPublicExponent());
myEncrypt.saveToFile("private.key", priv.getModulus(), priv.getPrivateExponent());
String encString = myEncrypt.bytes2String(myEncrypt.rsaEncrypt("pritesh".getBytes()));
System.out.println("encrypted : " + encString);
String decString = myEncrypt.bytes2String(myEncrypt.rsaDecrypt(encString.getBytes()));
System.out.println("decrypted : " + decString);
}
PublicKey readKeyFromFile(String keyFileName) throws Exception {
InputStream in = new FileInputStream(keyFileName);
ObjectInputStream oin = new ObjectInputStream(new BufferedInputStream(in));
try {
BigInteger m = (BigInteger) oin.readObject();
BigInteger e = (BigInteger) oin.readObject();
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);
KeyFactory fact = KeyFactory.getInstance("RSA");
PublicKey pubKey = fact.generatePublic(keySpec);
return pubKey;
} catch (Exception e) {
throw new RuntimeException("Spurious serialisation error", e);
} finally {
oin.close();
}
}
PrivateKey readPrivateKeyFromFile(String keyFileName) throws Exception {
InputStream in = new FileInputStream(keyFileName);
ObjectInputStream oin = new ObjectInputStream(new BufferedInputStream(in));
try {
BigInteger m = (BigInteger) oin.readObject();
BigInteger e = (BigInteger) oin.readObject();
RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(m, e);
KeyFactory fact = KeyFactory.getInstance("RSA");
PrivateKey pubKey = fact.generatePrivate(keySpec);
return pubKey;
} catch (Exception e) {
throw new RuntimeException("Spurious serialisation error", e);
} finally {
oin.close();
}
}
public byte[] rsaEncrypt(byte[] data) throws Exception {
byte[] src = new byte[] { (byte) 0xbe, (byte) 0xef };
PublicKey pubKey = this.readKeyFromFile("public.key");
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] cipherData = cipher.doFinal(data);
return cipherData;
}
public byte[] rsaDecrypt(byte[] data) throws Exception {
byte[] src = new byte[] { (byte) 0xbe, (byte) 0xef };
PrivateKey pubKey = this.readPrivateKeyFromFile("private.key");
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, pubKey);
byte[] cipherData = cipher.doFinal(data);
return cipherData;
}
private String bytes2String(byte[] bytes) {
StringBuilder string = new StringBuilder();
for (byte b: bytes) {
String hexString = Integer.toHexString(0x00FF & b);
string.append(hexString.length() == 1 ? "0" + hexString : hexString);
}
return string.toString();
}
}
I am getting this error:
Exception in thread "main" java.security.InvalidParameterException: RSA keys must be at least 512 bits long
at sun.security.rsa.RSAKeyPairGenerator.initialize(RSAKeyPairGenerator.java:70)
at java.security.KeyPairGenerator$Delegate.initialize(KeyPairGenerator.java:631)
at java.security.KeyPairGenerator.initialize(KeyPairGenerator.java:340)
at MyEncrypt.main(MyEncrypt.java:42)
I have make this class from http://www.javamex.com/tutorials/cryptography/rsa_encryption_2.shtml example
public class MyEncrypt {
static final String HEXES = "0123456789ABCDEF";
byte[] buf = new byte[1024];
public void saveToFile(String fileName, BigInteger mod, BigInteger exp) throws IOException {
ObjectOutputStream oout = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(fileName)));
try {
oout.writeObject(mod);
oout.writeObject(exp);
} catch (Exception e) {
throw new IOException("Unexpected error", e);
} finally {
oout.close();
}
}
public static void main(String[] args) throws Exception {
MyEncrypt myEncrypt = new MyEncrypt();
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair kp = kpg.genKeyPair();
RSAPublicKey publicKey = (RSAPublicKey) kp.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) kp.getPrivate();
KeyFactory fact = KeyFactory.getInstance("RSA");
RSAPublicKeySpec pub = fact.getKeySpec(kp.getPublic(), RSAPublicKeySpec.class);
RSAPrivateKeySpec priv = fact.getKeySpec(kp.getPrivate(), RSAPrivateKeySpec.class);
myEncrypt.saveToFile("public.key", pub.getModulus(), pub.getPublicExponent());
myEncrypt.saveToFile("private.key", priv.getModulus(), priv.getPrivateExponent());
String encString = myEncrypt.rsaEncrypt("pritesh");
System.out.println("encrypted : " + encString);
String decString = myEncrypt.rsaDecrypt(encString);
System.out.println("decrypted : " + decString);
String main_file_path = "resume.doc";
String main_encrypt_file_path = "encrypt.doc";
String main_decrypt_file_path = "decrypt.doc";
myEncrypt.rsaEncrypt(new FileInputStream(main_file_path),new FileOutputStream(main_encrypt_file_path));
// Decrypt
myEncrypt.rsaDecrypt(new FileInputStream(main_encrypt_file_path),new FileOutputStream(main_decrypt_file_path));
}
PublicKey readKeyFromFile(String keyFileName) throws Exception {
InputStream in = new FileInputStream(keyFileName);
ObjectInputStream oin = new ObjectInputStream(new BufferedInputStream(in));
try {
BigInteger m = (BigInteger) oin.readObject();
BigInteger e = (BigInteger) oin.readObject();
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);
KeyFactory fact = KeyFactory.getInstance("RSA");
PublicKey pubKey = fact.generatePublic(keySpec);
return pubKey;
} catch (Exception e) {
throw new RuntimeException("Spurious serialisation error", e);
} finally {
oin.close();
}
}
PrivateKey readPrivateKeyFromFile(String keyFileName) throws Exception {
InputStream in = new FileInputStream(keyFileName);
ObjectInputStream oin = new ObjectInputStream(new BufferedInputStream(in));
try {
BigInteger m = (BigInteger) oin.readObject();
BigInteger e = (BigInteger) oin.readObject();
RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(m, e);
KeyFactory fact = KeyFactory.getInstance("RSA");
PrivateKey pubKey = fact.generatePrivate(keySpec);
return pubKey;
} catch (Exception e) {
throw new RuntimeException("Spurious serialisation error", e);
} finally {
oin.close();
}
}
public String rsaEncrypt(String plaintext) throws Exception {
PublicKey pubKey = this.readKeyFromFile("public.key");
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] ciphertext = cipher.doFinal(plaintext.getBytes("UTF-8"));
return this.byteToHex(ciphertext);
}
public void rsaEncrypt(InputStream in, OutputStream out) throws Exception {
try {
PublicKey pubKey = this.readKeyFromFile("public.key");
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
// Bytes written to out will be encrypted
out = new CipherOutputStream(out, cipher);
// Read in the cleartext bytes and write to out to encrypt
int numRead = 0;
while ((numRead = in.read(buf)) >= 0){
out.write(buf, 0, numRead);
}
out.close();
}
catch (java.io.IOException e){
e.printStackTrace();
}
}
public void rsaDecrypt(InputStream in, OutputStream out) throws Exception {
try {
PrivateKey pubKey = this.readPrivateKeyFromFile("private.key");
Cipher dcipher = Cipher.getInstance("RSA");
dcipher.init(Cipher.DECRYPT_MODE, pubKey);
// Bytes read from in will be decrypted
in = new CipherInputStream(in, dcipher);
// Read in the decrypted bytes and write the cleartext to out
int numRead = 0;
while ((numRead = in.read(buf)) >= 0) {
out.write(buf, 0, numRead);
}
out.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
public String rsaDecrypt(String hexCipherText) throws Exception {
PrivateKey pubKey = this.readPrivateKeyFromFile("private.key");
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, pubKey);
String plaintext = new String(cipher.doFinal(this.hexToByte(hexCipherText)), "UTF-8");
return plaintext;
}
public static String byteToHex( byte [] raw ) {
if ( raw == null ) {
return null;
}
final StringBuilder hex = new StringBuilder( 2 * raw.length );
for ( final byte b : raw ) {
hex.append(HEXES.charAt((b & 0xF0) >> 4))
.append(HEXES.charAt((b & 0x0F)));
}
return hex.toString();
}
public static byte[] hexToByte( String hexString){
int len = hexString.length();
byte[] ba = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
ba[i/2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i+1), 16));
}
return ba;
}
}
It works well with text file but giving issue on files like docx and video any idea?
The error says it all: you're initializing with a keyset of 128 and RSA expects at least 512.
You have more than one problem:
Java does not support RSA keys of size less than 512. 2048 bit is a better choice. So change the key length:
kpg.initialize(2048);
String.getBytes() is not the inverse operation to your bytes2String(). After encrypting you convert the bytes to a hexadecimal string. But then you convert this hexadecimal string to its ASCII representation before decrypting, which yields a byte-array that is too long. Instead, use something like this to convert the hexadecimal string back:
private byte[] string2bytes(String s) {
int len = s.length();
byte[] res = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
res[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return res;
}
and then call that instead of String.getBytes():
// Note, this line is not completely fixed yet
String decString =
myEncrypt.bytes2String(
myEncrypt.rsaDecrypt(
myEncrypt.string2bytes(encString)
)
);
Finally you have the opposite problem. Your bytes2String() method does not reverse the String.getBytes() operation. You encrypted the output of "pritesh".getBytes(), so that is what you got out of the decrypt operation. Now you have to convert that back to a String. The String(byte[])-constructor will do that for you:
String decString =
new String(
myEncrypt.rsaDecrypt(
myEncrypt.string2bytes(encString)
)
);
Final ans
public class MyEncrypt {
public static final int AES_Key_Size = 128;
Cipher pkCipher, aesCipher;
byte[] aesKey;
SecretKeySpec aeskeySpec;
public static void main(String[] args) throws Exception {
//MyEncrypt.createRSAKeys(); //call to generated RSA keys
MyEncrypt secure = new MyEncrypt();
// to encrypt a file
secure.makeKey();
secure.saveKey(new File("keys/ase.key"), "keys/public.key");
secure.encrypt(new File("test/sample.pdf"), new File("test/encrypt_sample.pdf"));
// to decrypt it again
secure.loadKey(new File("keys/ase.key"), "keys/private.key");
secure.decrypt(new File("test/encrypt_sample.pdf"), new File("test/decrypted_sample.pdf"));
}
/**
* Constructor: creates ciphers
*/
public MyEncrypt() throws GeneralSecurityException {
// create RSA public key cipher
pkCipher = Cipher.getInstance("RSA");
// create AES shared key cipher
aesCipher = Cipher.getInstance("AES");
}
public static void createRSAKeys() throws Exception {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(512);
KeyPair kp = kpg.genKeyPair();
RSAPublicKey publicKey = (RSAPublicKey) kp.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) kp.getPrivate();
KeyFactory fact = KeyFactory.getInstance("RSA");
RSAPublicKeySpec pub = fact.getKeySpec(kp.getPublic(), RSAPublicKeySpec.class);
RSAPrivateKeySpec priv = fact.getKeySpec(kp.getPrivate(), RSAPrivateKeySpec.class);
saveToFile("keys/public.key", pub.getModulus(), pub.getPublicExponent());
saveToFile("keys/private.key", priv.getModulus(), priv.getPrivateExponent());
System.out.println("RSA public & private keys are generated");
}
private static void saveToFile(String fileName, BigInteger mod, BigInteger exp) throws IOException {
ObjectOutputStream oout = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(fileName)));
try {
oout.writeObject(mod);
oout.writeObject(exp);
} catch (Exception e) {
throw new IOException("Unexpected error", e);
} finally {
oout.close();
}
}
/**
* Creates a new AES key
*/
public void makeKey() throws NoSuchAlgorithmException {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(AES_Key_Size);
SecretKey key = kgen.generateKey();
aesKey = key.getEncoded();
aeskeySpec = new SecretKeySpec(aesKey, "AES");
}
/**
* Encrypts the AES key to a file using an RSA public key
*/
public void saveKey(File out, String publicKeyFile) throws IOException, GeneralSecurityException {
try {
// read public key to be used to encrypt the AES key
byte[] encodedKey = new byte[(int)publicKeyFile.length()];
new FileInputStream(publicKeyFile).read(encodedKey);
// create public key
//X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedKey);
//KeyFactory kf = KeyFactory.getInstance("RSA");
//PublicKey pk = kf.generatePublic(publicKeySpec);
PublicKey pk = this.readPublicKeyFromFile(publicKeyFile);
// write AES key
pkCipher.init(Cipher.ENCRYPT_MODE, pk);
CipherOutputStream os = new CipherOutputStream(new FileOutputStream(out), pkCipher);
os.write(aesKey);
os.close();
} catch (Exception e) {
//throw new Exception("Saving key exception", e);
}
}
private PublicKey readPublicKeyFromFile(String keyFileName) throws Exception {
InputStream in = new FileInputStream(keyFileName);
ObjectInputStream oin = new ObjectInputStream(new BufferedInputStream(in));
try {
BigInteger m = (BigInteger) oin.readObject();
BigInteger e = (BigInteger) oin.readObject();
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);
KeyFactory fact = KeyFactory.getInstance("RSA");
PublicKey pubKey = fact.generatePublic(keySpec);
return pubKey;
} catch (Exception e) {
throw new RuntimeException("Spurious serialisation error", e);
} finally {
oin.close();
}
}
private PrivateKey readPrivateKeyFromFile(String keyFileName) throws Exception {
InputStream in = new FileInputStream(keyFileName);
ObjectInputStream oin = new ObjectInputStream(new BufferedInputStream(in));
try {
BigInteger m = (BigInteger) oin.readObject();
BigInteger e = (BigInteger) oin.readObject();
RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(m, e);
KeyFactory fact = KeyFactory.getInstance("RSA");
PrivateKey pubKey = fact.generatePrivate(keySpec);
return pubKey;
} catch (Exception e) {
throw new RuntimeException("Spurious serialisation error", e);
} finally {
oin.close();
}
}
/**
* Decrypts an AES key from a file using an RSA private key
*/
public void loadKey(File in, String privateKeyFile) throws GeneralSecurityException, IOException {
try {
// read private key to be used to decrypt the AES key
byte[] encodedKey = new byte[(int)privateKeyFile.length()];
new FileInputStream(privateKeyFile).read(encodedKey);
// create private key
//PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedKey);
//KeyFactory kf = KeyFactory.getInstance("RSA");
//PrivateKey pk = kf.generatePrivate(privateKeySpec);
PrivateKey pk = this.readPrivateKeyFromFile(privateKeyFile);
// read AES key
pkCipher.init(Cipher.DECRYPT_MODE, pk);
aesKey = new byte[AES_Key_Size/8];
CipherInputStream is = new CipherInputStream(new FileInputStream(in), pkCipher);
is.read(aesKey);
aeskeySpec = new SecretKeySpec(aesKey, "AES");
} catch (Exception e) {
}
}
/**
* Encrypts and then copies the contents of a given file.
*/
public void encrypt(File in, File out) throws IOException, InvalidKeyException {
aesCipher.init(Cipher.ENCRYPT_MODE, aeskeySpec);
FileInputStream is = new FileInputStream(in);
CipherOutputStream os = new CipherOutputStream(new FileOutputStream(out), aesCipher);
copy(is, os);
os.close();
}
/**
* Decrypts and then copies the contents of a given file.
*/
public void decrypt(File in, File out) throws IOException, InvalidKeyException {
aesCipher.init(Cipher.DECRYPT_MODE, aeskeySpec);
CipherInputStream is = new CipherInputStream(new FileInputStream(in), aesCipher);
FileOutputStream os = new FileOutputStream(out);
copy(is, os);
is.close();
os.close();
}
/**
* Copies a stream.
*/
private void copy(InputStream is, OutputStream os) throws IOException {
int i;
byte[] b = new byte[1024];
while((i=is.read(b))!=-1) {
os.write(b, 0, i);
}
}
}

Categories