Simple file encryption/decryption

Source: Internet
Author: User

This file encryption method is different or way to each byte in the text of the XOR or encryption, the logic is very simple:



File Encryption Code implementation:

</pre><pre name= "code" class= "java" >package ********//<span "color: #33cc00;"

> Own definition </span>;
Import Java.io.File;
Import Java.io.RandomAccessFile;

Import Java.util.Scanner;
		public class Test1 {public static void main (string[] args) {System.out.println ("Input file path:");
		String s = new Scanner (system.in). nextline ();
		File f =new file (s);
			if (!f.isfile ()) {System.out.println ("Please enter the correct file path");
			
		return;
		} System.out.println ("KEY:");
		int key =new Scanner (system.in). Nextint ();
			try {Encrypt (f,key);
		SYSTEM.OUT.PRINTLN ("Encryption/decryption complete");
			catch (Exception e) {System.out.println ("Encryption/decryption failed");
		E.printstacktrace (); } private static void Encrypt (File f, int key) throws exception{/* 1. New Randomaccessfile Object assigned to RAF * 2. Single byte loop read The byte value that is read is assigned to B * 3.b or key, and the result is assigned to B * 4. Position subscript back to previous position seek (Raf.getfilepointer ()-1) * 5. Write byte value b back to file * 6. Close Raf
<span style= "White-space:pre" >		</span> * Using Single-byte access is slower, here in byte array form
		 * *
		
		randomaccessfile RAF =new Randomaccessfile (F, "RW");
		Single byte access
		/*int B;
		while ((B=raf.read ())!=-1) {
			b=b^key;
			Raf.seek (Raf.getfilepointer ()-1);;
			Raf.write (b);
		} *
		//byte array access
		//1024 2048 4096 8192
		byte[] Buff =new];
		int n;//Saves the number of each batch while
		((N=raf.read (Buff))!=-1) {for
			(int i=0;i<n;i++) {
				buff[i] ^= key;
			}
			Raf.seek (Raf.getfilepointer ()-n);
			Raf.write (buff, 0, N);
		}
		
		Raf.close ();
	}




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.