+//g++ cipher_jpg.cpp -o cipher_jpg -O3
+
+//cipher_jpg ~/Pictures/ecuador\ 2013/IMG_7548.JPG 38762
+//usage cipher_jpg image seed
+
+#include <iostream>
+#include <fstream>
+#include <iterator>
+#include <vector>
+
+
+using namespace std;
+
+typedef unsigned char uchar;
+
+uchar modulo(int x,int N){ return (x % N + N) %N; }
+
+void fxor(uchar *buf,int sz, int seed,int enc) {
+ int start,end;
+
+ for(int i=1;i<sz;i++) {
+ if(((uint)buf[i-1])==0xFF && ((uint)buf[i])==0xDA) {
+ cout<<"s "<<i+1<<endl;
+ start=i+16;//not nice
+ }
+ if(((uint)buf[i-1])==0xFF && ((uint)buf[i])==0xD9) {
+ cout<<"e "<<i-2<<endl;
+ end=i-2;
+ }
+ }
+
+
+
+
+ srand48(seed);
+
+
+ for(int i=0;i<(end-start)/10;i++) {
+ int p=lrand48()%(end-start)+start;
+ if(p<=start || p>=end)
+ cout<<"pb"<<endl;
+ while(buf[p-1]==255 || buf[p]==255 ){
+ p=lrand48()%(end-start)+start;
+ if(p<=start || p>=end)
+ cout<<"pb"<<endl;
+ }
+ uchar v=lrand48()%255;
+ if(enc) {
+ buf[p]=modulo((int)buf[p]+(int)v,255);
+ }
+ else {
+ buf[p]=modulo((int)buf[p]-(int)v,255);
+ }
+ }
+
+}
+
+
+int main(int argc, char **argv){
+ cout<<argv[1]<< endl;
+
+ FILE *fp;
+ fp = fopen(argv[1], "r");
+ fseek(fp, 0L, SEEK_END);
+ int sz = ftell(fp);
+ fseek(fp, 0, SEEK_SET);
+
+ uchar *buf=(uchar*)malloc(sz);
+ uchar *buf2=(uchar*)malloc(sz);
+ fread(buf, sz, 1, fp);
+ fclose(fp);
+
+
+ int seed=atoi(argv[2]);
+ cout<<sz<<endl;
+
+
+ fxor(buf,sz,seed,1);
+
+
+ fp = fopen("lena2.jpg", "w");
+ fwrite (buf , 1, sz, fp);
+ fclose(fp);
+
+ for(int i=0;i<sz;i++) {
+ buf2[i]=buf[i];
+ }
+
+
+
+
+ fxor(buf2,sz,seed,0);
+
+ fp = fopen("lena3.jpg", "w");
+ fwrite (buf2 , 1, sz, fp);
+ fclose(fp);
+
+
+
+
+
+
+ uchar res=modulo(-1,255);
+ cout<<(int)res<<endl;
+ cout<<-1%255<<endl;
+}