Search code examples
javafileencryptionmp3byte

Changing Mp3 File Bytes


my approach is encrypting mp3 files that even after encryption the encrypted file could be played with any mp3 player ( its ok if what you hear is a trash ! only play ) . so i'm going to splitting my Mp3 files to byte arrays and then change the frames ( according to Mp3 File structure ) with my encryption method i use .

here is the code i use for getting bytes :

public class Audio {

public static void main(String[] args) throws FileNotFoundException, IOException {
    File file = new File("test.wmv");

    FileInputStream fis = new FileInputStream(file);
    //System.out.println(file.exists() + "!!");
    //InputStream in = resource.openStream();
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    byte[] buf = new byte[1024];
    try {
        for (int readNum; (readNum = fis.read(buf)) != -1;) {
            bos.write(buf, 0, readNum); //no doubt here is 0
            //Writes len bytes from the specified byte array starting at offset off to this byte array output stream.
            System.out.println("read " + readNum + " bytes,");

        }
    } catch (IOException ex) {
       // Logger.getLogger(genJpeg.class.getName()).log(Level.SEVERE, null, ex);
    }
    byte[] bytes = bos.toByteArray();
    byte temp ;


    for(int i = 0 ; i < bytes.length ; i++)
    {
        System.out.println(bytes[i]);
    }


    //below is the different part
    File someFile = new File("test2.wmv");
    FileOutputStream fos = new FileOutputStream(someFile);
    fos.write(bytes);
    fos.flush();
    fos.close();
}

Here is the thing , my encryption and changing bytes should be in frame parts right ? as far as i read we cant access to bits and the smallest part of a file we can change are bytes . so how can i change the frames that are defined by bits ?

I did "google it" ! and i'm pretty confused , If any one could show me the way i'll be thankfull .


Solution

  • Read full bytes, extract the bits, e.g. for the last 3 bits use b & ((1 << 3) - 1), for the first 3 bits use b & (((1 << 3) - 1) << (Byte.SIZE - 3)). Does not work for full bytes of course, unless you convert them to integer first and convert them back to bytes before use.

    Since Java 7 you can also simply wrap a byte array in a BitSet for easy access to individual bits.

    To encrypt bits, use a stream cipher mode like AES-CTR instead of a block cipher mode. The last step of a stream cipher is just a XOR which is perfect for encrypting bits. It does not require any padding either, though it does require a unique IV (per data encryption key). A hash over the filename could provide that, given that the name never changes of course.