Java文件加解密

Java文件加解密,第1张

做网站有时会处理一些上传下载的文件 可能会用到加解密功能 以下是一个加解密方法

Java代码

import java io File

import java io FileInputStream

import java io FileOutputStream

import java io IOException

import nf Conf

import mon time TimeHandler

/**

* 加解密单元

* @author lupingui

* : :

*/

public class EncryptDecrypt {

//加解密KEY 这个不能变动 这里可以由任意的字符组成 尽量用特殊字符

static final byte[] KEYVALUE = getBytes()

//读取字节的长度

static final int BUFFERLEN =

//加密临时存储目录

static final String TRANSIT_DIR_ENC =

//解密临时存储目录

static final String TRANSIT_DIR_DEC =

/**

* 文件加密

* @param oldFile 待加密文件

* @param saveFileName 加密后文件保存路径

* @return

* @throws IOException

*/

public static boolean encryptFile(File oldFile String saveFileName) throws IOException{

//如果传入的文件不存在或者不是文件则直接返回

if (!oldFile exists() || !oldFile isFile()){

return false

}

FileInputStream in = new FileInputStream(oldFile)

//加密后存储的文件

File file = new File(saveFileName)

if (!file exists()){

return false

}

//读取待加密文件加密后写入加密存储文件中

FileOutputStream out = new FileOutputStream(file)

int c pos keylen

pos =

keylen = KEYVALUE length

byte buffer[] = new byte[BUFFERLEN]

while ((c = in read(buffer)) != ) {

for (int i = i <ci++) {

buffer[i] ^= KEYVALUE[pos]

out write(buffer[i])

pos++

if (pos == keylen){

pos =

}

}

}

in close()

out close()

return true

}

/**

* 文件加密

* @param oldFile:待加密文件

* @param saveFile 加密后的文件

* @return

* @throws IOException

*/

public static boolean encryptFile(File oldFile File saveFile) throws IOException{

//如果传入的文件不存在或者不是文件则直接返回

if (!oldFile exists() || !oldFile isFile() || !saveFile exists() || !saveFile isFile()){

return false

}

FileInputStream in = new FileInputStream(oldFile)

//读取待加密文件加密后写入加密存储文件中

FileOutputStream out = new FileOutputStream(saveFile)

int c pos keylen

pos =

keylen = KEYVALUE length

byte buffer[] = new byte[BUFFERLEN]

while ((c = in read(buffer)) != ) {

for (int i = i <ci++) {

buffer[i] ^= KEYVALUE[pos]

out write(buffer[i])

pos++

if (pos == keylen){

pos =

}

}

}

in close()

out close()

return true

}

/**

* 文件加密

* @param oldFile 待加密文件

* @return

* @throws IOException

*/

public static File encryptFile(File oldFile) throws IOException{

//如果传入的文件不存在或者不是文件则直接返回

if (!oldFile exists() || !oldFile isFile()){

return null

}

FileInputStream in = new FileInputStream(oldFile)

//临时加密文件存储目录

File dirFile = new File(TRANSIT_DIR_ENC)

//如果临时存储目录不存在或不是目录则直接返回

if (!dirFile exists() || !dirFile isDirectory()){

return null

}

//加密后存储的文件

File file = new File(dirFile enc_ + TimeHandler getInstance() getTimeInMillis() + _ + oldFile getName())

if (!file exists()){

file createNewFile()

}

//读取待加密文件加密后写入加密存储文件中

FileOutputStream out = new FileOutputStream(file)

int c pos keylen

pos =

keylen = KEYVALUE length

byte buffer[] = new byte[BUFFERLEN]

while ((c = in read(buffer)) != ) {

for (int i = i <ci++) {

buffer[i] ^= KEYVALUE[pos]

out write(buffer[i])

pos++

if (pos == keylen){

pos =

}

}

}

in close()

out close()

//返回加密后的文件

return file

}

/**

* 文件加密

* @param oldFileName 待加密文件路径

* @return

* @throws IOException

* @throws Exception

*/

public static File encryptFile(String oldFileName) throws IOException {

//如果待加密文件路径不正确则直接返回

if (oldFileName == null || oldFileName trim() equals( )){

return null

}

//待加密文件

File oldFile = new File(oldFileName)

//如果传入的文件不存在或者不是文件则直接返回

if (!oldFile exists() || !oldFile isFile()){

return null

}

//调用文件加密方法并返回结果

return encryptFile(oldFile)

}

/**

* 文件解密

* @param oldFile 待解密文件

* @return

* @throws IOException

*/

public static File decryptFile(File oldFile) throws IOException{

//如果待解密文件不存在或者不是文件则直接返回

if (!oldFile exists() || !oldFile isFile()){

return null

}

FileInputStream in = new FileInputStream(oldFile)

//临时解密文件存储目录

File dirFile = new File(TRANSIT_DIR_DEC)

//如果临时解密文件存储目录不存在或不是目录则返回

if (!dirFile exists() || !dirFile isDirectory()){

return null

}

//解密存储文件

File file = new File(dirFile dec_ + TimeHandler getInstance() getTimeInMillis() + _ + oldFile getName() substring(oldFile getName() lastIndexOf( )))

if (!file exists()){

file createNewFile()

}

//读取待解密文件并进行解密存储

FileOutputStream out = new FileOutputStream(file)

int c pos keylen

pos =

keylen = KEYVALUE length

byte buffer[] = new byte[BUFFERLEN]

while ((c = in read(buffer)) != ) {

for (int i = i <ci++) {

buffer[i] ^= KEYVALUE[pos]

out write(buffer[i])

pos++

if (pos == keylen){

pos =

}

}

}

in close()

out close()

//返回解密结果文件

return file

}

/**

* 文件解密

* @param oldFileName 待解密文件路径

* @return

* @throws Exception

*/

public static File decryptFile(String oldFileName) throws Exception {

//如果待解密文件路径不正确则直接返回

if (oldFileName == null || oldFileName trim() equals( )){

return null

}

//待解密文件

File oldFile = new File(oldFileName)

//如果待解密文件不存在或不是文件则直接返回

if (!oldFile exists() || !oldFile isFile()){

return null

}

//调用文件解密方法并返回结果

return decryptFile(oldFile)

}

lishixinzhi/Article/program/Java/hx/201311/26983

以下两个类可以很方便的完成字符串的加密和解密

加密 CryptHelper encrypt(password)

解密 CrypHelper decrypt(password)

代码如下

CryptUtils java

[java]

package gdie lab crypt

import java io IOException

import javax crypto Cipher

import javax crypto KeyGenerator

import javax crypto SecretKey

import apache xerces internal impl dv util Base

public class CryptUtils {

private static String Algorithm = DES

private static byte[] DEFAULT_KEY=new byte[] { }

private static String VALUE_ENCODING= UTF

/**

* 生成密钥

*

* @return byte[] 返回生成的密钥

* @throws exception

*             扔出异常

*/

public static byte[] getSecretKey() throws Exception {

KeyGenerator keygen = KeyGenerator getInstance(Algorithm)

SecretKey deskey = keygen generateKey()

// if (debug ) System out println ( 生成密钥 +byte hex (deskey getEncoded

// ()))

return deskey getEncoded()

}

/**

* 将指定的数据根据提供的密钥进行加密

*

* @param input

*            需要加密的数据

* @param key

*            密钥

* @return byte[] 加密后的数据

* @throws Exception

*/

public static byte[] encryptData(byte[] input byte[] key) throws Exception {

SecretKey deskey = new javax crypto spec SecretKeySpec(key Algorithm)

// if (debug )

// {

// System out println ( 加密前的二进串 +byte hex (input ))

// System out println ( 加密前的字符串 +new String (input ))

//

// }

Cipher c = Cipher getInstance(Algorithm)

c init(Cipher ENCRYPT_MODE deskey)

byte[] cipherByte = c doFinal(input)

// if (debug ) System out println ( 加密后的二进串 +byte hex (cipherByte ))

return cipherByte

}

public static byte[] encryptData(byte[] input) throws Exception {

return encryptData(input DEFAULT_KEY)

}

/**

* 将给定的已加密的数据通过指定的密钥进行解密

*

* @param input

*            待解密的数据

* @param key

*            密钥

* @return byte[] 解密后的数据

* @throws Exception

*/

public static byte[] decryptData(byte[] input byte[] key) throws Exception {

SecretKey deskey = new javax crypto spec SecretKeySpec(key Algorithm)

// if (debug ) System out println ( 解密前的信息 +byte hex (input ))

Cipher c = Cipher getInstance(Algorithm)

c init(Cipher DECRYPT_MODE deskey)

byte[] clearByte = c doFinal(input)

// if (debug )

// {

// System out println ( 解密后的二进串 +byte hex (clearByte ))

// System out println ( 解密后的字符串 +(new String (clearByte )))

//

// }

return clearByte

}

public static byte[] decryptData(byte[] input) throws Exception {

return decryptData(input DEFAULT_KEY)

}

/**

* 字节码转换成 进制字符串

*

* @param byte[] b 输入要转换的字节码

* @return String 返回转换后的 进制字符串

*/

public static String byte hex(byte[] bytes) {

StringBuilder hs = new StringBuilder()

for(byte b : bytes)

hs append(String format( % $ X b))

return hs toString()

}

public static byte[] hex byte(String content) {

int l=content length()》

byte[] result=new byte[l]

for(int i= i<li++) {

int j=i《

String s=content substring(j j+ )

result[i]=Integer valueOf(s ) byteValue()

}

return result

}

/**

* 将字节数组转换为base 编码字符串

* @param buffer

* @return

*/

public static String bytesToBase (byte[] buffer) {

//BASE Encoder en=new BASE Encoder()

return Base encode(buffer)

//      return encoder encode(buffer)

}

/**

* 将base 编码的字符串解码为字节数组

* @param value

* @return

* @throws IOException

*/

public static byte[] base ToBytes(String value) throws IOException {

//return Base decodeToByteArray(value)

//      System out println(decoder decodeBuffer(value))

//      return decoder decodeBuffer(value)

return Base decode(value)

}

/**

* 加密给定的字符串

* @param value

* @return 加密后的base 字符串

*/

public static String encryptString(String value) {

return encryptString(value DEFAULT_KEY)

}

/**

* 根据给定的密钥加密字符串

* @param value 待加密的字符串

* @param key 以BASE 形式存在的密钥

* @return 加密后的base 字符串

* @throws IOException

*/

public static String encryptString(String value String key) throws IOException {

return encryptString(value base ToBytes(key))

}

/**

* 根据给定的密钥加密字符串

* @param value 待加密的字符串

* @param key 字节数组形式的密钥

* @return 加密后的base 字符串

*/

public static String encryptString(String value byte[] key) {

try {

byte[] data=value getBytes(VALUE_ENCODING)

data=CryptUtils encryptData(data key)

return bytesToBase (data)

} catch (Exception e) {

// TODO Auto generated catch block

e printStackTrace()

return null

}

}

/**

* 解密字符串

* @param value base 形式存在的密文

* @return 明文

*/

public static String decryptString(String value) {

return decryptString(value DEFAULT_KEY)

}

/**

* 解密字符串

* @param value base 形式存在的密文

* @param key base 形式存在的密钥

* @return 明文

* @throws IOException

*/

public static String decryptString(String value String key) throws IOException {

String s=decryptString(value base ToBytes(key))

return s

}

/**

* 解密字符串

* @param value base 形式存在的密文

* @param key 字节数据形式存在的密钥

* @return 明文

*/

public static String decryptString(String value byte[] key) {

try {

byte[] data=base ToBytes(value)

data=CryptUtils decryptData(data key)

return new String(data VALUE_ENCODING)

}catch(Exception e) {

e printStackTrace()

return null

}

}

}

package gdie lab crypt

import java io IOException

import javax crypto Cipher

import javax crypto KeyGenerator

import javax crypto SecretKey

import apache xerces internal impl dv util Base

public class CryptUtils {

private static String Algorithm = DES

private static byte[] DEFAULT_KEY=new byte[] { }

private static String VALUE_ENCODING= UTF

/**

* 生成密钥

*

* @return byte[] 返回生成的密钥

* @throws exception

*             扔出异常

*/

public static byte[] getSecretKey() throws Exception {

KeyGenerator keygen = KeyGenerator getInstance(Algorithm)

SecretKey deskey = keygen generateKey()

// if (debug ) System out println ( 生成密钥 +byte hex (deskey getEncoded

// ()))

return deskey getEncoded()

}

/**

* 将指定的数据根据提供的密钥进行加密

*

* @param input

*            需要加密的数据

* @param key

*            密钥

* @return byte[] 加密后的数据

* @throws Exception

*/

public static byte[] encryptData(byte[] input byte[] key) throws Exception {

SecretKey deskey = new javax crypto spec SecretKeySpec(key Algorithm)

// if (debug )

// {

// System out println ( 加密前的二进串 +byte hex (input ))

// System out println ( 加密前的字符串 +new String (input ))

//

// }

Cipher c = Cipher getInstance(Algorithm)

c init(Cipher ENCRYPT_MODE deskey)

byte[] cipherByte = c doFinal(input)

// if (debug ) System out println ( 加密后的二进串 +byte hex (cipherByte ))

return cipherByte

}

public static byte[] encryptData(byte[] input) throws Exception {

return encryptData(input DEFAULT_KEY)

}

/**

* 将给定的已加密的数据通过指定的密钥进行解密

*

* @param input

*            待解密的数据

* @param key

*            密钥

* @return byte[] 解密后的数据

* @throws Exception

*/

public static byte[] decryptData(byte[] input byte[] key) throws Exception {

SecretKey deskey = new javax crypto spec SecretKeySpec(key Algorithm)

// if (debug ) System out println ( 解密前的信息 +byte hex (input ))

Cipher c = Cipher getInstance(Algorithm)

c init(Cipher DECRYPT_MODE deskey)

byte[] clearByte = c doFinal(input)

// if (debug )

// {

// System out println ( 解密后的二进串 +byte hex (clearByte ))

// System out println ( 解密后的字符串 +(new String (clearByte )))

//

// }

return clearByte

}

public static byte[] decryptData(byte[] input) throws Exception {

return decryptData(input DEFAULT_KEY)

}

/**

* 字节码转换成 进制字符串

*

* @param byte[] b 输入要转换的字节码

* @return String 返回转换后的 进制字符串

*/

public static String byte hex(byte[] bytes) {

StringBuilder hs = new StringBuilder()

for(byte b : bytes)

hs append(String format( % $ X b))

return hs toString()

}

public static byte[] hex byte(String content) {

int l=content length()》

byte[] result=new byte[l]

for(int i= i<li++) {

int j=i《

String s=content substring(j j+ )

result[i]=Integer valueOf(s ) byteValue()

}

return result

}

/**

* 将字节数组转换为base 编码字符串

* @param buffer

* @return

*/

public static String bytesToBase (byte[] buffer) {

//BASE Encoder en=new BASE Encoder()

return Base encode(buffer)

//  return encoder encode(buffer)

}

/**

* 将base 编码的字符串解码为字节数组

* @param value

* @return

* @throws IOException

*/

public static byte[] base ToBytes(String value) throws IOException {

//return Base decodeToByteArray(value)

//  System out println(decoder decodeBuffer(value))

//  return decoder decodeBuffer(value)

return Base decode(value)

}

/**

* 加密给定的字符串

* @param value

* @return 加密后的base 字符串

*/

public static String encryptString(String value) {

return encryptString(value DEFAULT_KEY)

}

/**

* 根据给定的密钥加密字符串

* @param value 待加密的字符串

* @param key 以BASE 形式存在的密钥

* @return 加密后的base 字符串

* @throws IOException

*/

public static String encryptString(String value String key) throws IOException {

return encryptString(value base ToBytes(key))

}

/**

* 根据给定的密钥加密字符串

* @param value 待加密的字符串

* @param key 字节数组形式的密钥

* @return 加密后的base 字符串

*/

public static String encryptString(String value byte[] key) {

try {

byte[] data=value getBytes(VALUE_ENCODING)

data=CryptUtils encryptData(data key)

return bytesToBase (data)

} catch (Exception e) {

// TODO Auto generated catch block

e printStackTrace()

return null

}

}

/**

* 解密字符串

* @param value base 形式存在的密文

* @return 明文

*/

public static String decryptString(String value) {

return decryptString(value DEFAULT_KEY)

}

/**

* 解密字符串

* @param value base 形式存在的密文

* @param key base 形式存在的密钥

* @return 明文

* @throws IOException

*/

public static String decryptString(String value String key) throws IOException {

String s=decryptString(value base ToBytes(key))

return s

}

/**

* 解密字符串

* @param value base 形式存在的密文

* @param key 字节数据形式存在的密钥

* @return 明文

*/

public static String decryptString(String value byte[] key) {

try {

byte[] data=base ToBytes(value)

data=CryptUtils decryptData(data key)

return new String(data VALUE_ENCODING)

}catch(Exception e) {

e printStackTrace()

return null

}

}

}

CryptHelper java

[java]

package gdie lab crypt

import javax crypto Cipher

import javax crypto SecretKey

import javax crypto SecretKeyFactory

import javax crypto spec DESKeySpec

import javax crypto spec IvParameterSpec

import springframework util DigestUtils

public class CryptHelper{

private static String CRYPT_KEY = zhongqian

//加密

private static Cipher ecip

//解密

private static Cipher dcip

static {

try {

String KEY = DigestUtils md DigestAsHex(CRYPT_KEY getBytes()) toUpperCase()

KEY = KEY substring( )

byte[] bytes = KEY getBytes()

DESKeySpec ks = new DESKeySpec(bytes)

SecretKeyFactory skf = SecretKeyFactory getInstance( DES )

SecretKey sk = skf generateSecret(ks)

IvParameterSpec iv = new IvParameterSpec(bytes)

ecip = Cipher getInstance( DES/CBC/PKCS Padding )

ecip init(Cipher ENCRYPT_MODE sk iv )

dcip = Cipher getInstance( DES/CBC/PKCS Padding )

dcip init(Cipher DECRYPT_MODE sk iv )

}catch(Exception ex) {

ex printStackTrace()

}

}

public static String encrypt(String content) throws Exception {

byte[] bytes = ecip doFinal(content getBytes( ascii ))

return CryptUtils byte hex(bytes)

}

public static String decrypt(String content) throws Exception {

byte[] bytes  = CryptUtils hex byte(content)

bytes = dcip doFinal(bytes)

return new String(bytes ascii )

}

//test

public static void main(String[] args) throws Exception {

String password = gly

String en = encrypt(password)

System out println(en)

System out println(decrypt(en))

}

}

package gdie lab crypt

import javax crypto Cipher

import javax crypto SecretKey

import javax crypto SecretKeyFactory

import javax crypto spec DESKeySpec

import javax crypto spec IvParameterSpec

import springframework util DigestUtils

public class CryptHelper{

private static String CRYPT_KEY = zhongqian

//加密

private static Cipher ecip

//解密

private static Cipher dcip

static {

try {

String KEY = DigestUtils md DigestAsHex(CRYPT_KEY getBytes()) toUpperCase()

KEY = KEY substring( )

byte[] bytes = KEY getBytes()

DESKeySpec ks = new DESKeySpec(bytes)

SecretKeyFactory skf = SecretKeyFactory getInstance( DES )

SecretKey sk = skf generateSecret(ks)

IvParameterSpec iv = new IvParameterSpec(bytes)

ecip = Cipher getInstance( DES/CBC/PKCS Padding )

ecip init(Cipher ENCRYPT_MODE sk iv )

dcip = Cipher getInstance( DES/CBC/PKCS Padding )

dcip init(Cipher DECRYPT_MODE sk iv )

}catch(Exception ex) {

ex printStackTrace()

}

}

public static String encrypt(String content) throws Exception {

byte[] bytes = ecip doFinal(content getBytes( ascii ))

return CryptUtils byte hex(bytes)

}

public static String decrypt(String content) throws Exception {

byte[] bytes  = CryptUtils hex byte(content)

bytes = dcip doFinal(bytes)

return new String(bytes ascii )

}

//test

public static void main(String[] args) throws Exception {

String password = gly

String en = encrypt(password)

System out println(en)

System out println(decrypt(en))

}

lishixinzhi/Article/program/Java/hx/201311/26449


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/11401739.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-15
下一篇 2023-05-15

发表评论

登录后才能评论

评论列表(0条)

保存