这篇文章仅作为记录.脚本是我从网上搜集来的,做一个归整.
混淆包括:类名,方法名,字段名,字符串,垃圾类代码
脚本经过我的处理,做好路径配置及混淆字符标记配置后可以直接使用.
先看混淆效果图
类名混淆效果:
方法及字段混淆效果:
字符串混淆效果:
垃圾类代码效果:
接下来是脚本代码
类名&方法名&字段名混淆脚本
混淆代码:
#!/bin/sh
##################################
# (该脚本是在https://github.com/heqingliang/CodeObfus 上找到的)
# 代码混淆脚本
#
##################################
#识别含有多字节编码字符时遇到的解析冲突问题
export LC_CTYPE=C
export LANG=C
#配置项:
#项目路径,会混淆该路径下的文件
ProjectPath="/Users/项目路径/"
FileDir="/Users/存放路径"
#这个路径是混淆成功后,原文本和替换文本解密对应的文件存放路径(该路径不能在项目目录或其子目录),混淆成功后会在该路径下生成一个解密时需要的文件,根据该文件的文本内容把混淆后的内容更换为原文本内容,该文件名的组成由$(date +%Y%m%d)"_"$(date +%H%M)及日期_小时组成,每分钟会不一样。所以解密的时候需要每次更换文件路径
SecretFile=$FileDir"/tihuan"$(date +%Y%m%d)"_"$(date +%H%M)
if [[ ! -d "$FileDir" ]]; #判断此目录是否不存在
then
mkdir $FileDir; #不存在则创建
fi
#第一个参数为项目路径
if [[ $1 ]]
then
if [[ $1 != "_" ]]; then
ProjectPath=$1
fi
fi
#第二个参数指定密钥文件路径及文件名
if [[ $2 ]]
then
if [[ $2 != "_" ]]; then
SecretFile=$2
fi
fi
#词库
s0="Comment,Plate,Salary,Incorrect,Act,Cliff,Credit,Northwest,Partial,Direct,Simple,Vice,Horizon,Cut,Drum,Thermometer,Pail,Cinema,Seventy,Sea,Pistol,Basic,Male,Forgive,Despair,Republic,"
s1="Astro,Nomia,Booty,Music,Impact,Template,Secret,Done,Raft,Stake,Encountering,Fur,Many,Parts,Bolster,Raging,Care,Without,Action,Address,Strong,Sorrow,Keep,Human,Hope,Happy,Always,"
s2="Special,Alan,Luv,Global,Deadly,Strow,Letter,a,Waiting,b,Berry,c,Ten,d,Scale,e,Twelve,Distribution,y,Production,z,Be,Way,Back,Home,Humanity,Put,Yourself,Shoes,Feel,Hurts,It,Of,"
s3="Sunshine,Cover,Shaking,Teenage,Are,We,Eight,tough,Tackle,Eighteen,Timber,Twenty,Victory,Speak,Louder,Stage,Recent,also,Era,Player,Stronger,Probably,Person,Too,Happiest,Let,Heartaches,"
s4="Young,Increasingly,Open,Inclusive,Sugar,Become,Uptown,Funk,Traveling,Thirteen,Summer,Maroon,Still,Panama,Rhythm,PartOfMe,Perhaps,Fat,PriceTag,Do,Not,Necessarily,Best,Everything,"
s5="Before,Departure,Far,Over,Targets,First,Outbreak,Require,Moves,Monsters,Tremendous,AtArms,Nineteen,Lemon,Nine,Coronavirus,Alleviating,Vicetone,Response,They,Those,Who,Hurt,Search,"
s6="Jealousy,Like,Romance,Geisha,Beautiful,Creep,Tiger,Reunion,Despite,Beethoven,Virus,common,Nothing,Gonna,Beyond,Prosperity,Peace,security,universal,Tried,Appreciate,Importance,"
s7="Lasting,Both,Rarely,Enjoys,Give,Crises,Cup,Cooperation,World,All,Natural,Falls,Fear,Shoulder,Agenda,Jagger,Possible,Dining,Beart,Rain,Decline,Context,Touched,Lives,Begins,Smile,"
s8="Goodtime,HeyJude,HereWithYou,Seen,Challenges,HotAirBallon,Piano,Seven,Seventeen,President,Immortals,Emotional,Teams,Country,Apologize,Curiosity,Aloha,Grows,Ends,Brightest,Will,"
s9="Meeting,Though,Heja,Soaked,Achieve,He,Neutrality,Upholding,Dioxide,Emissions,Confidence,Discipline,Carbon,Peak,Announced,Event,Goal,Striving,torm,Water,Based,Forgotten,Past,Well,"
s10="Boosted,Efficient,Deeds,Jacket,Hands,Fourteen,Through,Bodies,Tears,Words,organizations,Historic,Trails,Sanded,Five,Miles,Industry,Cap,Watching,Survive,Lifeuntil,Were,Born,Crying,"
s11="History,Poverty,Sealed,Davos,Glass,Lips,Poured,People,Eradication,GoodGov,BadGov,Today,o,Remarkable,p,Debt,q,Relief,r,s,Especially,t,Important,u,v,Soul,Everyone,Around,Smiling,"
s12="Tomorrow,Lead,Led,Exposure,Outside,Browned,Footsteps,Returning,Melon,Placed,Seed,Faith,Cat,Dog,Actions,International,Fifteen,Panda,Student,Floor,Along,Live,Die,Please,Send,This,"
s13="Love,Belt,Road,Trillion,Totaled,TheWay,YouLie,Teacher,Micro,Between,Soft,Fox,Juice,Reason,Scab,Ice,Army,Mole,Bacon,instead,Airport,Provided,Affordable,Message,Mean,Another,Note,"
s14="Opportunities,Instance,Vine,Growth,Accelerated,Recovery,Ability,Together,Created,Combines,Globalization,Hunderd,Sour,Grape,Wood,Economic,Flat,Blight,Blow,Really,Brighter,Bad,"
s15="Fifty,Cross,Blame,Sauce,Ground,Unnels,Southwest,Truly,Besides,Oil,Peach,Bloom,Darling,Dear,Lief,Loving,Tootsy,Forum,Under,Trials,Sweet,Dorsal,Ride,Jointly,Side,Friendship,Gas,"
s16="Africa,Dreams,Enough,Real,Initiative,Tipped,Hug,Desc,Them,Poor,Grow,Comes,Want,Awfully,Sixteen,Pick,Have,Only,Just,Virtual,There,While,Critical,Much,Shared,Worry,Happen,Out,"
s17="Community,Building,Moments,Slow,Counting,Morning,Enhance,Build,Privacy,Leave,Slime,Coffee,Forget,Key,Label,Count,Into,Random,Others,One,Two,Force,Mankind,Opportunity,Brighten,"
s18="Three,Joint,Thus,Six,Use,Salar,Sub,Cons,Mobile,Seabed,Assistance,Likely,bring,Boring,Devastate,Colonial,Dialect,Unevenly,Anti,Tool,Can,Efforts,Down,Working,Day,Planned,Hang,"
s19="Pass,Future,Forward,Allow,Glider,Said,Cleaner,Step,Say,Better,Notably,Inter,Container,Other,Know,From,City,More,Made,Vaccines,Swap,File,May,Max,Load,Burning,Consider,Ignore,"
s20="Date,Data,Msg,Gap,Or,Net,Book,Every,Forces,Been,Site,Bin,My,Idaho,Bess,Me,Present,Anymore,Province,expert,Engaged,Perfect,Scouring,Info,Secend,Online,Moment,Believe,Desting,"
s21="Air,Assisting,Myanmar,Camera,Joining,Need,Birthday,Indignation,Caused,Tracks,Photos,Bus,Tree,See,Start,Hard,Come,Plan,Dis,Dev,Photo,Free,Easy,Economy,Read,Write,Discourage,"
s22="Any,Secure,Public,Tackling,Cry,Kiss,Protect,Support,Del,Ensure,Func,Hooray,Board,Plane,April,Trade,Snowing,Foreign,Time,Make,Runs,Big,Resulting,Impetus,Go,Injected,Laugh,Lip,"
s23="Hello,Recession,Int,Population,h,Uphold,i,Multilateralism,j,Countries,k,Accessible,l,m,Test,Your,Vocabulary,With,Our,Fun,Image,Quizzes,Joy,Kid,Taken,Later,Min,Nor,Opp,Eyes,Aid,"
s24="Pig,Promote,Que,Tools,Res,Sub,Ter,Until,Eleven,Tame,Responsibilit,Vc,Extreme,Win,Xin,Graze,Aversion,Arsenal,Obsession,Barren,Called,Aerial,Yun,Zoo,Com,Only,Memory,Never,"
s25="Ache,Blind,About,Cable,Rich,Drp,Because,Eys,Million,pushed,Team,Fly,Climate,Good,High,Index,Making,f,Which,g,Their,n,Due,w,Take,x,Job,Join,Select,Last,Lag,Jump,And,Often,Nut,"
s26="Kind,Line,Moon,Night,Option,Off,Actively,These,Supplies,Needed,On,Members,Capacity,In,Offered,Call,Medical,Once,Tangible,Urgently,Advanced,Field,Immense,Drive,Percent,Matter,"
s27="Pressure,Epidemic,Control,Prevention,Than,Pandemic,Devoted,Against,Talk,Fight,Itself,The,Walked,Order,Onunaiju,Promises,Stepped,Director,Studies,Empty,Pic,Abuja,Sustainable,"
s28="Que,Assume,Center,Showed,Charles,Red,Sole,Concrete,Tip,Up,Ver,Wind,Xrc,Year,Zero,Life,When,You,Miss,Someone,So,That,To,And,For,Dream,What,Where,Chance,Things,Happiness,Easier,"
s29="Weekend,She,Wolf,Turning,Guard,Atmosphere,Refuse,Convenience,Tube,Cause,Biscuit,Pardon,Illegal,Self,Arouse,Shift,Probably,Recommend,Invest,Green,Adventure,Weed,Rank,Fade,No,"
s30="Displease,Fill,Stain,Exercise,Establishment,Anyone,Clothes,Strength,Butcher,Pension,blast,Negative,Gown,Handsome,Laughter,Breeze,Startle,Drought,Tailor,Rag,Band,Towel,Judge,"
s31="Percentage,Territory,Staff,Consequence,,Eighth,Phrase,Distinguish,Marble,Miracle,Historical,House,Saddle,Stove,Disposal,Rat,Flour,Possession,Peep,Accustom,Bind,Nobody,Type,"
s32="Broom,Extremely,Dynamic,Flame,Betray,Strange,Rice,Childish,Weather,Expand,Admire,Nevertheless,Possibly,Passport,Storage,Restore,Feedback,Moderate,Behalf,Geography,Traditional,"
s33="Outward,Strap,Partly,Hardware,Rational,Scorn,Greeting,Serious,Retreat,Midnight,Direction,Scientific,Tight,Profession,Battery,Differ,Sunset,Eagle,Feeble,Therefore,Youthful,Luggage,"
s34="Yearly,Machine,Boy,Probability,Embarrass,Cottage,Milk,Overtake,Revise,Frequently,Collective,Settlement,Pocket,Dress,Insert,Motion,Suffer,Stretch,Target,Survey,Equip,Spare,Queue,"
s35="Slight,Selection,Lion,Complex,Reputation,Rug,Inevitable,Relationship,Fisherman,Attach,Pacific,Hatch,Voluntary,Magazine,Plentiful,Drunk,Generate,Travel,Fundamental,Menu,Steer,"
s36="Cancer,Invade,Optical,North,Wife,Speciality,Commerce,Dye,Preceding,Listen,Mistake,Genuine,Mediterranean,Charity,Atom,Seek,Angry,Pronoun,Identify,Coil,Surrender,Wool,Among,Strip,"
s37="Sand,Option,Grey,Seat,Constitution,Readily,Slam,Dismiss,Merchant,Sum,Philosopher,Signal,Tenth,Prime,Shoot,Anyhow,Lawn,Bolt,Replace,Ministry,Desirable,Agent,Surprise,Fish,Retain,"
s38="Except,Able,Prior,Hopeless,Grasp,Equality,Harness,Visible,Structural,Almost,Crazy,Tag,Treat,Globe,Throw,Foolish,Whisper,July,Cellar,Liar,Tray,County,Patient,Observation,Simplify,"
s39="Muscle,Excellent,Season,Transportatio,Pleasant,Rose,Snowy,Finance,Bench,Phenomenon,Experimental,Deceive,Confuse,Corporation,Disclose,Tear,Fortunately,Traffic,Breed,Sample,Childhood,"
s40="Dimension,Tone,Hospital,Chop,Loyal,Exhaust,Remark,Shepherd,Ever,Lung,Classroom,Argument,Curl,Surname,Tub,Rule,Subway,Goods,Shelter,League,Federal,Crust,Fond,Van,Respond,Tunnel,"
s41="Conjunction,Stern,Owner,Song,Robber,Soak,Clue,Spade,Mature,Deposit,Sleepy,Glad,Unlikely,Faulty,Artistic,Text,Organism,Divide,Battle,Strain,Understand,Swan,Entire,Cost,Trust,"
s42="Route,Pond,Fairly,Hour,Whisky,Sunny,External,Indicate,Honour,Loop,Instant,Half,Jazz,Discover,Dairy,Port,Path,Cloak,Success,Delegation,Arithmetic,Motor,Twelfth,Hungry,Unhappy,"
s43="Heat,Vinegar,Hardship,Typewriter,Fashionable,Honesty,Navigation,Meaning,Minus,Bite,Flush,East,Patch,Centre,Slippery,Peasant,Joyful,Proud,Reap,Skillful,Chief,Technical,Impose,"
s44="Mercury,Tutor,Resemble,Comb,Suck,Protein,Visual,Pale,Ought,Bargain,Chart,Horse,Plot,Inside,Lend,Game,Express,Listener,Prove,Standpoint,Deck,Writing,Official,Commonly,Shady,Most,"
s45="Consult,Compile,Acre,Definition,Lesson,Reign,Identical,Length,Thumb,Attain,Nerve,Frog,Tent,Paradise,Melt,Rather,Tea,Stress,Weary,Legend,Wreath,Voltage,Lid,Within,Violence,Spell,"
s46="Neutral,Save,Evaporate,Operator,Prosperous,Cafe,Disaster,Conscience,Catch,Locomotive,Satisfy,Transformatio,Endless,Bell,Rapidly,Form,Sixth,Revolution,Outdoors,Continuous,Pound,"
s47="Ninth,Drop,Cricket,Southern,Frontier,Tire,Wrong,Angel,Whole,Wild,Press,Coin,Military,Truck,Portion,Fertilizer,Pie,French,Mother,Outset,Sandy,Grandson,Qualify,Knock,Bush,Anxious,"
s48="Sweep,Underground,Mount,Mark,Rock,Unjust,Ancient,Comprise,Secretary,Substantial,Sickness,Asia,Rebellion,Stop,Postman,Remains,Area,Ahead,Justice,Motive,Tourist,Regulate,Impression,"
s49="Banana,Touch,Price,Collection,Blank,Sparkle,Liter,Logic,Hall,Dwelling,Premier,Incline,Wealth,Subtract,Radish,Anchor,Acid,Fan,Produce,Determine,Inch,Lavatory,Fault,Interaction,"
s50="Alarm,Network,Systematic,Accurate,Contradiction,Box,Pillow,Trunk,Influence,Dose,Jury,Dirty,Mostly,Concentrate,Volcano,Technology,Split,Surroundings,Spelling,Dread,Electronic,Restraint,"
s51="Stay,Thin,Equipment,Kettle,Construct,Sudden,Rainbow,Character,Pupil,Harbour,Capture,Cream,Recorder,Pint,Chicken,Comparative,Definite,Screen,Queen,Frame,Downward,Sober,Various,"
s52="Unable,Next,Transfer,Its,Wipe,Trumpet,Receive,Brass,Plunge,Invisible,Characteristi,Muddy,Mood,Brain,Beer,Sorry,Certificate,Pride,Circle,Parliament,Ill,Acute,Item,Island,Widely,"
s53="Relevant,Little,Beginning,Atomic,Scold,Thief,Inquire,Outlet,Earnest,Why,Outcome,Afterward,Elastic,Married,Skill,Spoon,Anything,Countryside,Temptation,Unfair,Staircase,Accommodation,"
s54="Closely,Conventional,Bottle,Repair,Grieve,Stiffen,Illustration,Contain,Unfortunately,Expansion,Eve,Manual,Hasten,Headquarters,Cave,Attend,Thank,Comfortable,Pilot,Orange,Yard,"
s55="Sticky,Trousers,Dinner,Insult,Deliver,Centimetre,Idea,Private,Crash,Learn,Exit,Fact,Fridge,Mental,Classmate,Pop,Rifle,Repent,Telegram,Quality,Headache,Rest,Donkey,Square,Topic,"
s56="Busy,Scene,Contemporary,Sure,Garage,Rid,Core,Mutual,Publication,Nail,Stem,Son,Candy,Gain,Naughty,Bury,Scrape,Complaint,Duck,Roller,Symbol,Overhead,Fortunate,Boot,Summary,Knot,"
s57="Furious,Cheat,Hundred,Exceedingly,Carrier,Pen,Prejudice,Indignant,Onion,Kindness,Unpleasant,Noun,Institute,Lever,Interpret,Hut,Hateful,Disappear,Accent,Cathedral,Nod,Properly,"
s58="Quick,,Receipt,Employee,Christian,Uncle,Coal,Purify,Haircut,Ditch,Object,Pluck,Pencil,Welcome,Camp,Horn,Clearly,Prevail,Tie,Independent,Tiny,Pinch,Watch,Mainland,Broad,Famous,"
s59="Golden,Utter,Draft,Release,Xray,Horsepower,Wavelength,Withdraw,Carriage,Hell,Brick,Cultivate,Amongst,Paper,Seldom,Explore,Blood,China,Spy,Mislead,Forest,Hen,Eat,Uneasy,Chimney,"
s60="Soda,Fibre,Decade,Bulk,Successful,Away,Actual,Straight,Wonderful,Tick,Handle,Australia,Glove,Edge,Italian,Mouthful,Folk,Shopkeeper,Right,Executive,Contribute,Vessel,Effective,"
s61="Tablet,Following,Idle,Shed,Removal,Shave,Location,Operational,Deduce,Native,Dispose,Utmost,Twin,Successive,Lump,Glue,Graduate,Bosom,Succeed,Sword,Refine,Egg,Farther,Moreover,"
s62="Fair,Gymnasium,Defence,Hillside,Accommodate,Judgement,Rural,Multiple,Risk,Develop,Marvelous,Novel,Criminal,True,Tragedy,All,Wear,Dew,Hammer,Easily,Single,Rotten,Linen,Worthless,"
s63="Humble,Blade,Code,Actor,Yours,Reading,Reality,Disguise,Glimpse,Group,West,Pain,Desire,Contempt,Phone,Warm,Shot,Slope,Presently,Industrialize,Conclude,Engine,White,Statesman,Turbine,"
s64="Visitor,Sign,Investigate,Seize,Information,Suddenly,Vary,Shall,Fee,Crew,Insurance,Leading,Block,Draw,View,Billion,Devise,Jewish,Attract,Stroke,Upstairs,Junior,Vapour,Wooden,Shallow,"
s65="Germany,Upwards,Flag,Strengthen,Reference,Interval,Inn,Overtime,Liner,Scholar,Academy,Reliability"
#金山词霸 四级必备词汇 第50课完
s1000="${s0}${s1}${s2}${s3}${s4}${s5}${s6}${s7}${s8}${s9}${s19}${s18}${s17}${s16}${s15}${s14}${s13}${s12}${s11}${s10}${s20}${s21}${s22}${s23}${s24}${s25}${s26}${s27}${s28}${s29}"
s1001="${s30}${s31}${s32}${s33}${s34}${s35}${s36}${s37}${s38}${s39}${s40}${s41}${s42}${s43}${s44}${s45}${s46}${s47}${s48}${s49}${s50}${s51}${s52}${s53}${s54}${s55}${s56}${s57}${s58}${s59}"
s1002="${s60}${s61}${s62}${s63}${s64}${s65}"
s="${s1000}${s1001}${s1002}"
array=(${s//,/ })
count=${#array[*]}
echo "词库长度:"$count
list="a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z"
arr=(${list//,/ })
length=${#arr[*]}
#转小写为大写
function tolower(){
echo $1 | awk '{print toupper($0)}'
}
#获取随机数
function rand(){
echo $(($RANDOM%$1+1))
}
#前缀词
prefix=$(tolower ${arr[$(rand length)]})${arr[$(rand length)]}${arr[$(rand length)]}
echo "随机生成的前缀词:"$prefix
######################!注意 字段的中间不要包含obf_或者_fuc !############## chmod 777
#查找文本中所有要求混淆的属性方法类,只会替换文本中符合 obf_[A-Za-z0-9_]*_fuc 的字符串(区分大小写,例如oBf_就不会做混淆),如果注释内容有该类型的字符串,也会进行替换。对于使用 _下划线访问的变量属性,不会有影响,一样会替换成对应_的混淆内容。resultfiles=`grep 'obf_[A-Za-z0-9_]*_fuc' -rl $ProjectPath`
#查找结果为空则退出
if [[ -z $resultfiles ]]
then
echo "项目没有需要混淆的代码"
exit
else
echo "开始混淆代码..."
echo > $SecretFile
fi
x=$(awk '
BEGIN{srand();k=0;prefix="'"$prefix"'";alpbetnum=split("'"$s"'", alpbet, ",");}
#随机数生成函数
function random_int(min, max) {
return int( rand()*(max-min+1) ) + min;
}
#随机字符串生成函数
function random_string(len) {
#固定前缀+数字
result=prefix""k;
for (i=0; i<len; i++) {
result = result""alpbet[ random_int(1, alpbetnum) ];
}
return result;
}
/obf_[A-Za-z0-9_]*_fuc/{
x = $0;
#匹配需要混淆的属性变量方法
while (match(x, "obf_[A-Za-z0-9_]*_fuc") > 0) {
tempstr=substr(x, RSTART, RLENGTH);
#判断是否有之前已经找过的重复字符串
for ( i = 0; i < k; i++ ){
if (strarr[i] == tempstr){break;}
}
if(i<k){
#重复字符串,直接删除。所以不用担心混淆内容过多,可能会出现重复的混淆字符串
x=substr(x, RSTART+RLENGTH);
continue;
}else{
#不是重复字符串,添加到替换数组
strarr[k++]=tempstr;
}
#最长替换单词数为6,最少为1.也可以设置成其他数值
randomstr=random_string(random_int(1, 6));
printf("%s:%s|", tempstr,randomstr);
#替换随机字符串
gsub(tempstr,randomstr, x);
x = substr(x, RSTART+RLENGTH);
}
}' $resultfiles )
#加密对写入密钥文件
echo $x > $SecretFile
recordnum=1
while [[ 1 == 1 ]]; do
record=`echo $x|cut -d "|" -f$recordnum`
if [[ -z $record ]]
then
break
fi
record1=`echo $record|cut -d ":" -f1`
echo "原项:"$record1
record2=`echo $record|cut -d ":" -f2`
echo "加密项:"$record2
#替换文件夹中所有文件的内容(支持正则)
#单引号不能扩展
sed -i '' "s/${record1}/${record2}/g" `grep $record1 -rl $ProjectPath`
echo "第"$recordnum"项混淆代码处理完毕"
let "recordnum = $recordnum + 1"
done
#查找需要混淆的文件名并替换
filerecordnum=1
while [[ 1 == 1 ]]; do
filerecord=`echo $x|cut -d "|" -f$filerecordnum`
if [[ -z $filerecord ]]
then
break
fi
filerecord1=`echo $filerecord|cut -d ":" -f1`
#echo "原项:"$filerecord1
filerecord2=`echo $filerecord|cut -d ":" -f2`
#echo "加密项:"$filerecord2
#改文件名
find $ProjectPath -name $filerecord1"*"| awk '
BEGIN{frecord1="'"$filerecord1"'";frecord2="'"$filerecord2"'";finish=1}
{
filestr=$0;
gsub(frecord1,frecord2,filestr);
print "mv " $0 " " filestr";echo 第"finish"个混淆文件处理完毕";
finish++;
}'|bash
let "filerecordnum = $filerecordnum + 1"
done
还原代码:
#!/bin/sh
######################################
#
# 代码还原脚本
#
######################################
#识别含有多字节编码字符时遇到的解析冲突问题
export LC_CTYPE=C
export LANG=C
#配置项:
#已经混淆的项目路径
ProjectPath="/Users/项目路径/"
#这个是文件路径而不是目录,是混淆的时候生成的文本文件路径,每次不一样。所以每次加密后,解密时需要更换路径
SecretFile="/Users/存放路径/tihuan20200603_1714"
#控制混淆方向 1为解混淆,其它值为按SecretFile文件混淆回去
HxOrJm=1
#第一个参数为项目路径
if [[ $1 ]]
then
if [[ $1 != "_" ]]; then
ProjectPath=$1
fi
fi
#第二个参数指定密钥文件路径及文件名
if [[ $2 ]]
then
if [[ $2 != "_" ]]; then
SecretFile=$2
fi
fi
##############################################################################
#内容还原
x=`cat $SecretFile`
recordnum=1
while [[ 1 == 1 ]]; do
record=`echo $x|cut -d "|" -f$recordnum`
if [[ -z $record ]]
then
break
fi
if [[ $HxOrJm == 1 ]]; then
record1=`echo $record|cut -d ":" -f1`
echo "原项:"$record1
record2=`echo $record|cut -d ":" -f2`
echo "加密项:"$record2
elif [[ $HxOrJm != 1 ]]; then
record1=`echo $record|cut -d ":" -f2`
echo "原项:"$record1
record2=`echo $record|cut -d ":" -f1`
echo "加密项:"$record2
fi
#若项目中加密项与密钥文件的加密项不符合则退出程序
searchresult=`grep $record2 -rl $ProjectPath`
if [[ -z $searchresult ]]; then
echo "指定的密钥文件不能还原"
exit
fi
#替换文件夹中所有文件的内容(支持正则)
#单引号不能扩展
sed -i '' "s/${record2}/${record1}/g" $searchresult
echo "第"$recordnum"项混淆代码还原完毕"
let "recordnum = $recordnum + 1"
done
#文件还原
filerecordnum=1
while [[ 1 == 1 ]]; do
filerecord=`echo $x|cut -d "|" -f$filerecordnum`
if [[ -z $filerecord ]]
then
break
fi
if [[ $HxOrJm == 1 ]]; then
filerecord1=`echo $filerecord|cut -d ":" -f1`
#echo "原项:"$filerecord1
filerecord2=`echo $filerecord|cut -d ":" -f2`
#echo "加密项:"$filerecord2
elif [[ $HxOrJm != 1 ]]; then
filerecord1=`echo $filerecord|cut -d ":" -f2`
filerecord2=`echo $filerecord|cut -d ":" -f1`
fi
#改文件名
find $ProjectPath -name $filerecord2"*"| awk '
BEGIN{
frecord1="'"$filerecord1"'";
frecord2="'"$filerecord2"'";
finish=1;
}
{
filestr=$0;
gsub(frecord2,frecord1,filestr);
print "mv " $0 " "filestr ";echo 第"finish"个混淆文件还原完毕"
finish++;
}'|bash
let "filerecordnum = $filerecordnum + 1"
done
使用:
- 把脚本代码添加到 obfuscation.sh 和dis_obfuscation.sh 中 配置好路径,及混淆字符串(如:要混淆study字符 要写成 obf_study_fuc)
- 终端cd到脚本所在目录 执行 chmod 777 obfuscation.sh
- 执行 ./obfuscation.sh ,或直接把文件拖入到终端,回车即可
- 还原时 把生成的 tihuan20200603_1714 文件路径替换好 再执行 ./dis_obfuscation.sh
- 设置HxOrJm=2或其它值非1的值,可以按tihuan20200603_1714 文件的内容还原为原混淆代码。
字符串混淆脚本(需要python环境)
项目代码中需加入下边这些宏定义以及还原字符串方法
//confusion_NSSTRING(@"字符串混淆加密 和 解密的宏开关")
//#define obfuscation_confusion
#ifdef obfuscation_confusion
#define confusion_NSSTRING(string) obf_decryptConstString_fuc(string)
#else
#define confusion_NSSTRING(string) string
#endif
static NSString* obf_decryptConstString_fuc(NSString* s){
//confusion_NSSTRING(@"先执行decryptConfusionString函数解密字符串")
if(s.length > 0){
NSString *t = [[NSString alloc]initWithData:[[NSData alloc]initWithBase64EncodedString:s options:0] encoding:NSUTF8StringEncoding];
NSRegularExpression *r = [NSRegularExpression regularExpressionWithPattern:@"[^a-zA-Z0-9\u4e00-\u9fa5/@?%&_:.=-\\]" options:NSRegularExpressionCaseInsensitive | NSRegularExpressionUseUnixLineSeparators | NSRegularExpressionDotMatchesLineSeparators | NSRegularExpressionAnchorsMatchLines | NSRegularExpressionAllowCommentsAndWhitespace error:nil];
t = [r stringByReplacingMatchesInString:t options:0 range:NSMakeRange(0, [t length]) withTemplate:@""];
if(t.length > 0){
return t ;
}
}
return s;
}
混淆代码:
#!/usr/bin/env python
# encoding=utf8
# -*- coding: utf-8 -*-
# author by one
# 脚本将会用于对指定目录下的.h .m源码中的字符串进行转换
# 替换所有字符串常量为base64串
import importlib
import os
import re
import sys
import base64
import random
if sys.getdefaultencoding() != 'utf-8':
reload(sys)
sys.setdefaultencoding('utf-8')
#配置穿插字符串的字符集
s0= '✽✾✿❁❃❋❀⚘☑✓✔☐☒✗✘ㄨ✕✖✖⋆✢✣✤✥❋✦✧✩✰✪✫✬✭✮✯❂✡★✱✲✳✴✵✶✷✸✹✺✻✼❄❅❆❇❈❉❊☼☀'+'♂♀☿☁☂☄☾☽☃ﭢ♥❤❥❣❦❧♡۵웃유ღ♨❖☪✙✡☭♫♬♭♩♪'
s1= '。,?()「」【】!:;《》·œ†ß∂©℗®™℠˙㍿∆˚¬…æ–ç'+'€£Ұ₴₰¢₤¥₳₲₪₵₣₱฿¤₡₮₭₩ރ₢₥₫₦ł﷼₠₧₯₨čर₹ƒ₸¢'+'ℂℍℕℙℚℝℤℬℰℯℱℊℋℎℐℒℓℳℴ℘ℛℭ℮ℌℑℜℨ'
s2= 'ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫⅬⅭⅮⅯⅰⅱⅲⅳⅴⅵⅶⅷⅸⅹⅺⅻⅼⅽⅾⅿ'+'āáǎàōóǒòēéěèīíǐìūúǔùǖǘǚǜüêɑńňɡ'+'⁰¹²³⁴⁵⁶⁷⁸⁹₀₁₂₃₄₅₆₇₈₉°′″℃℉Åå﹪‰㎡㏕㎜㎝㎞㏎³㎎㎏㏄º○¤⁺⁻⁼⁽⁾ʲʰʳʷʸⁿ'
s3= 'ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζνξοπρσηθικλμτυφχψω'+'АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя'
s4= '☰☲☱☴☵☶☳☷☯'+'♚♛♝♞♜♟♔♕♗♘♖♟'+'㊎㊍㊌㊋㊏㊚㊛㊐㊊㊣㊤㊥㊦㊧㊨㊒㊫㊑㊓㊔㊕㊖㊗㊘㊜㊝㊞㊟㊠㊡㊢㊩㊪㊬㊭㊮㊯㊰㉿'
s5= 'ㄱㄲㄳㄴㄵㄶㄷㄸㄹㄺㄻㄼㄽㄾㄿㅀㅁㅂㅃㅄㅅㅆㅇㅈㅉㅊㅋㅌㅍㅎㅏㅐㅑㅒㅓㅔㅗㅘㅙㅚㅛㅜㅝㅞㅟㅠㅡㅢㅥㅦㅧㅨㅩㅪㅫㅬㅭㅮㅯㅰㅱㅲㅳㅴㅵㅶㅷㅸㅹㅺㅻㅼㅽㅾㅿㆀㆁㆂㆃㆄㆅㆆㆇㆈㆉㆊ'
s6= '㊀㊁㊂㊃㊄㊅㊆㊇㊈㊉⑴⑵⑶⑷⑸⑹⑺⑻⑼⑽⑾⑿⒀⒁⒂⒃⒄⒅⒆⒇❶❷❸❹❺❻❼❽❾❿⓫⓬⓭⓮⓯⓰⓱⓲⓳⓴①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳⓪⒈⒉⒊⒋⒌⒍⒎⒏⒐⒑⒒⒓⒔⒕⒖⒗⒘⒙⒚⒛'
s7= 'ⒶⒷⒸⒹⒺⒻⒼⒽⒾⒿⓀⓁⓂⓃⓄⓅⓆⓇⓈⓉⓊⓋⓌⓍⓎⓏⓐⓑⓒⓓⓔⓕⓖⓗⓘⓙⓚⓛⓜⓝⓞⓟⓠⓡⓢⓣⓤⓥⓦⓧⓨⓩ'
s8= '㋀㋁㋂㋃㋄㋅㋆㋇㋈㋉㋊㋋㏠㏡㏢㏣㏤㏥㏦㏧㏨㏩㏪㏫㏬㏭㏮㏯㏰㏱㏲㏳㏴㏵㏶㏷㏸㏹㏺㏻㏼㏽㏾㍙㍚㍛㍜㍝㍞㍟㍠㍡㍢㍣㍤㍥㍦㍧㍨㍩㍪㍫㍬㍭㍮㍯㍰㍘'
s9= '﹢﹣×÷±≌∽≦≧≒﹤﹥≈≡≠≤≥≮≯∷∶∝∞∧∨∑∏∪∩∈∵∴⊥∥∠⌒⊙⊕√∟⊿㏒㏑‰⅟½⅓⅕⅙⅛⅔⅖⅚⅜¾⅗⅝⅞⅘≂≃≄≅≆≇≈≉≊≋≌≍≎≏≐≑≒≓≔≕≖≗≘≙≚≛≜≝≞≟≠≡≢≣≤≥≦≧≨≩⊰⊱⋛⋚∫∬∭∮∯∰∱∲∳℅‰‱øØπ'
s10= '↑↓←→↖↗↘↙↔↕➻➼➽➸➳➺➻➴➵➶➷➹▶►▷◁◀◄«»➩➪➫➬➭➮➯➱⏎➲➾➔➘➙➚➛➜➝➞➟➠➡➢➣➤➥➦➧➨↚↛↜↝↞↟↠↠↡↢↣↤↤↥↦↧↨⇄⇅⇆⇇⇈⇉⇊⇋⇌⇍⇎⇏⇐⇑⇒⇓⇔⇖⇗⇘⇙⇜↩↪↫↬↭↮↯↰↱↲↳↴↵↶↷↸↹☇☈↼↽↾↿⇀⇁⇂⇃⇞⇟⇠⇡⇢⇣⇤⇥⇦⇧⇨⇩⇪↺↻⇚⇛♐'
s11= 'ကခဂဃငစဆဇဈညဋဌဍဎဏတထဒဓနပဖဗဘမယရလဝသဟဠအဢဣဤဥဦဧဨဩဪါာိီုူေဲဳဴဵံ့း္်ျြွှဿ၀၁၂၃၄၅၆၇၈၉၊။၌၍၎၏ၐၑၒၔၕၖၗၘၙၚၛၜၝၞၟၠ'+'ཀཁགངཅཆཇཉཏཐདནཔཕབམཙཚཛཝཞཟའཡརལཤསཧཨཀྵཪཫཬ'
s12= '𐠀𐠁𐠂𐠃𐠄𐠅𐠈𐠊𐠋𐠌𐠍𐠎𐠏𐠐𐠑𐠒𐠓𐠔𐠕𐠖𐠗𐠘𐠙𐠚𐠛𐠜𐠝𐠞𐠟𐠠𐠡𐠢𐠣𐠤𐠥𐠦𐠧𐠨𐠩𐠪𐠫𐠬𐠭𐠮𐠯𐠰𐠱𐠲𐠳𐠴𐠵𐠷𐠸𐠼𐠿'+'אבגדהוזחטיכךלמםנןסעפףצץקרשת'+'𐤀𐤁𐤂𐤃𐤄𐤅𐤆𐤇𐤈𐤉𐤊𐤋𐤌𐤍𐤎𐤏𐤐𐤑𐤒𐤓𐤔𐤕𐤖𐤗𐤘𐤙𐤚𐤛𐤟'
s13= '𐎠𐎡𐎢𐎣𐎤𐎥𐎦𐎧𐎨𐎩𐎪𐎫𐎬𐎭𐎮𐎯𐎰𐎱𐎲𐎳𐎴𐎵𐎶𐎷𐎸𐎹𐎺𐎻𐎽𐎾𐎿𐏀𐏁𐏂𐏃𐏈𐏉𐏊𐏋𐏌𐏍𐏎𐏏𐏐𐏑𐏒𐏓𐏔𐏕'+'ᠠᠡᠢᠣᠤᠥᠧᠨᠩᠪᠫᠬᠭᠮᠯᠰᠱᠲᠳᠴᠵᠶᠷᠸᠹᠺᠻᠼᠽᠾᠿᡀᡁᡂ'
s = s0+s1+s2+s3+s4+s5+s6+s7+s8+s9+s10+s11+s12+s13
charlist = list(s.decode('utf-8'))
# replace替换字符串为base64串的形式,每次混淆base64串都不一样
def replace(match):
string = match.group(2)
print("string : "+string)
#可以自定义的特殊符号数组,避免使用编程代码中使用到的符号及中文文字符号,如 <>?,;&%$*+-=.:'"_/\@!^()[]{}~ 。日元货币符号:円 等
#charlist = ['。',',','?','(',')','「','」','【','】','!',':',';','、','《','》','·','œ','®','†','ø','å','ß','∂','©','˙','˚','¬','…','æ','≈','ç','√','∫','≤','≥','÷','≠','Α','Β','Γ','Δ','Ε','Ζ','Η','Θ','Ι','Κ','Λ','Μ','Ν','Ξ','Ο','Π','Ρ','Σ','Τ','Υ','Φ','Χ','Ψ','Ω','α','β','γ','δ','ε','ζ','ν','ξ','ο','π','ρ','σ','η','θ','ι','κ','λ','μ','τ','υ','φ','χ','ψ','ω','€','£','Ұ','₴','₰','¢','₤','¥','₳','₲','₪','₵','₣','₱','฿','¤','₡','₮','₭','₩','ރ','₢','₥','₫','₦','ł','﷼','₠','₧','₯','₨','č','र','₹','ƒ','₸','¢']
list_str = [charlist[random.randint(0,len(charlist)-1)]+v+charlist[random.randint(0,len(charlist)-1)] for v in string.decode("utf-8")]
replaced_string = ''.join(str(i) for i in list_str)
print("base64前 :" + replaced_string)
replaced_string = '@\"' + base64.b64encode(string.encode("utf-8")) + '\"'
print("替换后 :" + replaced_string)
return match.group(1) + replaced_string + match.group(3)
# obfuscate方法是修改传入文件源代码中用confusion_NSSTRING标记的所有字符串
# 使用replace函数对字符串进行异或转换
def obfuscate(file):
with open(file, 'r') as f:
code = f.read()
f.close()
code = re.sub(r'(confusion_NSSTRING\(|confusion_CSTRING\()\@"(.*?)"(\))', replace, code)
# code = re.sub(r'(confusion_TAG\(|confusion_CSTRING\()(.*?)(\))', replace, code)
code = re.sub(r'//#define obfuscation_confusion', '#define obfuscation_confusion', code)
with open(file, 'w') as f:
f.write(code)
f.close()
# openSrcFile方法是读取源码路径下的所有.h和.m 文件
# 对每个文件执行obfuscate函数
def openSrcFile(path):
print("混淆的路径为 : "+ path)
# this folder is custom
for parent,dirnames,filenames in os.walk(path):
#case 1:
# for dirname in dirnames:
# print((" parent folder is:" + parent).encode('utf-8'))
# print((" dirname is:" + dirname).encode('utf-8'))
#case 2
for filename in filenames:
extendedName = os.path.splitext(os.path.join(parent,filename))
if (extendedName[1] == '.h' or extendedName[1] == '.m'):
print("\n处理源代码文件: "+ os.path.join(parent,filename))
obfuscate(os.path.join(parent,filename))
#这里需要修改源码的路径为自己工程的文件夹名称
srcPath = '/Users/项目目录'
if __name__ == '__main__':
print("本脚本用于对源代码中被标记的字符串进行加密")
if len(srcPath) > 0:
openSrcFile(srcPath)
else:
print("请输入正确的源代码路径")
sys.exit()
还原代码:
#!/usr/bin/env python
# encoding=utf8
# -*- coding: utf-8 -*-
# author by one
# 解密脚本
# 替换所有标记过的base64串为原字符串
import importlib
import os
import re
import base64
import sys
if sys.getdefaultencoding() != 'utf-8':
reload(sys)
sys.setdefaultencoding('utf-8')
# 替换base64串为字符串
def replace(match):
string = match.group(2)
string = base64.b64decode(string).decode("utf-8")
print("string = " + string)
regex = re.compile(ur"[^\u4e00-\u9fa5a-zA-Z0-9/@?%&\_:;,.=\-\s\\]")
decodeConfusion_string = regex.sub('',string.decode("utf-8"))
replaced_string = '@\"' + decodeConfusion_string + '\"' print("replaced_string = " + replaced_string)
return match.group(1) + replaced_string + match.group(3)
# 修改源代码,加入字符串加密的函数
def obfuscate(file):
with open(file, 'r') as f:
code = f.read()
f.close()
code = re.sub(r'(confusion_NSSTRING\(|confusion_CSTRING\()\@"(.*?)"(\))', replace, code)
# code = re.sub(r'(confusion_TAG\(|confusion_CSTRING\()(.*?)(\))', replace, code)
code = re.sub(r'#define obfuscation_confusion', '//#define obfuscation_confusion', code)
with open(file, 'w') as f:
f.write(code)
f.close()
#读取源码路径下的所有.h和.m 文件
def openSrcFile(path):
print("解密路径: "+ path)
# this folder is custom
for parent,dirnames,filenames in os.walk(path):
#case 1:
# for dirname in dirnames:
# print((" parent folder is:" + parent).encode('utf-8'))
# print((" dirname is:" + dirname).encode('utf-8'))
#case 2
for filename in filenames:
extendedName = os.path.splitext(os.path.join(parent,filename))
#读取所有.h和.m 的源文件
if (extendedName[1] == '.h' or extendedName[1] == '.m'):
print("已解密文件:"+ os.path.join(parent,filename))
obfuscate(os.path.join(parent,filename))
#源码路径
srcPath = '/Users/项目目录'
if __name__ == '__main__':
print("字符串解混淆脚本,将被标记过的base64串转为字符串,还原代码")
if len(srcPath) > 0:
openSrcFile(srcPath)
else:
print("请输入正确的源代码路径!")
sys.exit()
使用:
- 将脚本代码添加到 confusion.py 和 decrypt.py 文件中,设置好项目路径,标记要混淆的字符串明文, 如:要混淆 NSLog(@"url = %@",url) 写成NSLog(confusion_NSSTRING(@"url = %@"),url)
- 混淆明文字符串 在终端运行 python 脚本所在目录/confusion.py,或直接把文件拖入到终端,回车即可
- 还原明文字符串 在终端运行 python 脚本所在目录/decrypt.py,或直接把文件拖入到终端,回车即可
生成垃圾类代码
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
#第一步:首先生成一个500位的数组 驼峰类型的元素 用作文件名 eg:AsdfdfGsd
import random
import os,sys
import string
first = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
second = "abcdefghijklmnopqrstuvwxyz"
number = "345"
index = 0
array = []
for i in range(500):
final=(random.choice(first))
index = random.randint(3, 5)
for i in range(index):
final+=(random.choice(second))
final += (random.choice(first))
for i in range(index):
final+=(random.choice(second))
array.append(final)
print (array)
#第二步:
#用上边生成的数组来创建对应的.h和.m文件
# -*- coding: utf-8 -*-
import random
import os
import string
#创建.h文件
def text_createH(fileNmae,msg,msg1,propertyNumber,methodArray,msg3):
# full_path = sys.path[0] + '/OCFiles/' + fileNmae + '.h' #文件所在文件夹
full_path = '/Users/垃圾类代码存放目录/' + fileNmae + '.h' #工程所在目录
file = open(full_path, 'w')
file.write('//\n// '+fileNmae+'.h\n\n')
file.write(msg)
file.write(msg1)
propryNameArray = []
for index in range(1,propertyNumber):
propryNameArray.append(random.choice(array))
propryNameArray = list(set(propryNameArray))
for propertyName in propryNameArray:
file.write('@property(nonatomic,strong)'+random.choice(classArray)+' * '+'obf_'+propertyName+'_fuc;\n')
file.write('\n\n')
for methodName in methodArray:
file.write('- (void)obf_pushTo'+methodName+'VC_fuc:(NSDictionary *)obf_info_fuc;\n')
file.write(msg3)
file.close()
print('Done')
#创建.m文件
def text_createM(fileNmae,msg,msg1,methodArray,msg3):
# full_path = sys.path[0] + '/OCFiles/' + fileNmae + '.m' #文件所在文件夹
full_path = '/Users/垃圾类代码存放目录/' + fileNmae + '.m'#工程所在目录 file = open(full_path, 'w')
file.write('//\n// '+fileNmae+'.m\n\n\n')
file.write(msg)
file.write(msg1)
for methodName in methodArray:
file.write('- (void)obf_pushTo'+methodName+'VC_fuc:(NSDictionary *)obf_info_fuc\n{\n\n NSMutableArray *obf_'+methodName+'_fuc = [NSMutableArray array];\n')
number = random.randint(3, 10)
for i in range(1,number):
file.write(' [obf_'+methodName+'_fuc addObject:@"'+random.choice(array)+'"];\n')
file.write('\n}\n\n')
file.write(msg3)
file.close()
print('Done')
classArray = ['NSString','UILabel','NSDictionary','NSData','UIScrollView','UIView']
array = ['HwxrFvrj', 'QnzduQbtdd', 'PvcrwLtqhf', 'UvdhDbjn', 'SuntmyTxvyzg', 'CvlxwBipbp', 'GzrdyzIbimvz', 'CqsjqMmgsp', 'OxaaeuWjhasc', 'NjiardRvwgbi', 'NcculmLtpljq', 'ApoqQrll', 'GkgokDyvjb', 'EblldkVouplj', 'KfdrFvnw', 'SfhyhObftc', 'SmruByoc', 'YzcccvXmpmit', 'OmqvaHpxat', 'XzytsUyvyd', 'MjforNnnyi', 'ZvjhuIdogs', 'BzfrxzSeahxc', 'PycycwFjtpny', 'XvngtoSedljr', 'DktiaCbucd', 'AqbplNuodc', 'MzkvgZuala', 'KdwzIoej', 'AaynatUpqcfd', 'IyvwhZvtjc', 'UmijGmsy', 'AoayndXxghym']
array = list(set(array))
for name in array:
number = random.randint(3, 10)
methodArray = []
for i in range(1,5):
methodArray.append(random.choice(array))
methodArray = list(set(methodArray))#数组去重
text_createH('obf_'+name+'ViewController_fuc', '#import <UIKit/UIKit.h>\n','@interface '+'obf_'+name+ 'ViewController_fuc:'+ 'UIViewController\n\n',number,methodArray,'\n\n@end')
text_createM('obf_'+name+'ViewController_fuc', '#import "'+'obf_'+name+'ViewController_fuc.h"\n\n' '@interface '+'obf_'+ name+'ViewController_fuc()\n\n @end\n\n','@implementation '+'obf_'+name+'ViewController_fuc\n\n- (void)viewDidLoad { \n\n [super viewDidLoad];\n\n}\n\n',methodArray,'\n\n@end')
使用:
- 将代码添加到obfuscation_addCode.py文件中
- 配置好存放目录
- 终端执行 python 脚本所在目录/obfuscation_addCode.py,或直接把文件拖入到终端,回车即可
先执行这个脚本生成垃圾类代码,再执行上面的混淆脚本,可以把生成的垃圾类一起混淆
脚本文件的编辑使用的 Sublime Text
最后,混淆之前,做好备份~!