Created
August 3, 2017 03:46
-
-
Save pocari/82bb707436d0e4cfe50e8c22fc42bbcf to your computer and use it in GitHub Desktop.
java 暗号化 復号化
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import javax.crypto.*; | |
import javax.crypto.spec.*; | |
import java.security.*; | |
public class Test { | |
public static void main(String ...args) throws Exception { | |
String password = "01234567890ABCDEFGHIJKLMNOPQRSTU"; | |
encrypt("./hoge.zip", "hoge.encrypted", password); | |
decrypt("hoge.encrypted", "decrpted", password); | |
} | |
private static void encrypt(String filename, String encryptedFilename, String password) throws Exception { | |
FileInputStream fis = new FileInputStream(filename); | |
Key key = new SecretKeySpec(password.getBytes(), "AES"); | |
Cipher cipher = Cipher.getInstance("AES/PCBC/PKCS5Padding"); | |
cipher.init(Cipher.ENCRYPT_MODE, key); | |
FileOutputStream fos = new FileOutputStream(encryptedFilename); | |
CipherOutputStream cos = new CipherOutputStream(fos, cipher); | |
fos.write(cipher.getIV()); | |
byte[] a = new byte[8]; | |
int i = fis.read(a); | |
while (i != -1) { | |
cos.write(a, 0, i); | |
i = fis.read(a); | |
} | |
cos.flush(); | |
cos.close(); | |
} | |
private static void decrypt(String encryptedFilename, String outputFilename, String password) throws Exception { | |
Key key = new SecretKeySpec(password.getBytes(), "AES"); | |
FileInputStream fis = new FileInputStream(encryptedFilename); | |
byte[] iv = new byte[16]; | |
fis.read(iv); | |
Cipher cipher = Cipher.getInstance("AES/PCBC/PKCS5Padding"); | |
IvParameterSpec ivspec = new IvParameterSpec(iv); | |
cipher.init(Cipher.DECRYPT_MODE, key, ivspec); | |
CipherInputStream cis = new CipherInputStream(fis, cipher); | |
FileOutputStream out = new FileOutputStream(outputFilename); | |
output(cis, out); | |
cis.close(); | |
out.close(); | |
} | |
private static void output(InputStream input , OutputStream output) throws Exception { | |
int DEFAULT_BUFFER_SIZE = 1024 * 4; | |
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; | |
int size = -1; | |
while (-1 != (size = input.read(buffer))) { | |
output.write(buffer, 0, size); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment