包含java加解密3的词条

发布时间:2022-11-22

本文目录一览:

  1. 如何用JAVA实现字符串简单加密解密?
  2. 如何用java实现加密与解密???
  3. 如何利用JAVA对文档进行加密和解密处理,完整的java类
  4. [java中如何实现对文件和字符串加密. 解密?](#java中如何实现对文件和字符串加密. 解密?)
  5. [Java 加密解密的方法都有哪些](#Java 加密解密的方法都有哪些)
  6. 如何用Java进行3DES加密解密

如何用JAVA实现字符串简单加密解密?

java加密字符串可以使用des加密算法,实例如下:

package test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.*;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
/**
 * 加密解密
 *
 * @author shy.qiu
 * @since
 */
public class CryptTest {
    /**
     * 进行MD5加密
     *
     * @param info 要加密的信息
     * @return String 加密后的字符串
     */
    public String encryptToMD5(String info) {
        byte[] digesta = null;
        try {
            // 得到一个md5的消息摘要
            MessageDigest alga = MessageDigest.getInstance("MD5");
            // 添加要进行计算摘要的信息
            alga.update(info.getBytes());
            // 得到该摘要
            digesta = alga.digest();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        // 将摘要转为字符串
        String rs = byte2hex(digesta);
        return rs;
    }
    /**
     * 进行SHA加密
     *
     * @param info 要加密的信息
     * @return String 加密后的字符串
     */
    public String encryptToSHA(String info) {
        byte[] digesta = null;
        try {
            // 得到一个SHA-1的消息摘要
            MessageDigest alga = MessageDigest.getInstance("SHA-1");
            // 添加要进行计算摘要的信息
            alga.update(info.getBytes());
            // 得到该摘要
            digesta = alga.digest();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        // 将摘要转为字符串
        String rs = byte2hex(digesta);
        return rs;
    }
    // //////////////////////////////////////////////////////////////////////////
    /**
     * 创建密匙
     *
     * @param algorithm 加密算法,可用 DES,DESede,Blowfish
     * @return SecretKey 秘密(对称)密钥
     */
    public SecretKey createSecretKey(String algorithm) {
        // 声明KeyGenerator对象
        KeyGenerator keygen;
        // 声明 密钥对象
        SecretKey deskey = null;
        try {
            // 返回生成指定算法的秘密密钥的 KeyGenerator 对象
            keygen = KeyGenerator.getInstance(algorithm);
            // 生成一个密钥
            deskey = keygen.generateKey();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        // 返回密匙
        return deskey;
    }
    /**
     * 根据密匙进行DES加密
     *
     * @param key  密匙
     * @param info 要加密的信息
     * @return String 加密后的信息
     */
    public String encryptToDES(SecretKey key, String info) {
        // 定义 加密算法,可用 DES,DESede,Blowfish
        String Algorithm = "DES";
        // 加密随机数生成器 (RNG),(可以不写)
        SecureRandom sr = new SecureRandom();
        // 定义要生成的密文
        byte[] cipherByte = null;
        try {
            // 得到加密/解密器
            Cipher c1 = Cipher.getInstance(Algorithm);
            // 用指定的密钥和模式初始化Cipher对象
            // 参数:(ENCRYPT_MODE, DECRYPT_MODE, WRAP_MODE,UNWRAP_MODE)
            c1.init(Cipher.ENCRYPT_MODE, key, sr);
            // 对要加密的内容进行编码处理,
            cipherByte = c1.doFinal(info.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 返回密文的十六进制形式
        return byte2hex(cipherByte);
    }
    /**
     * 根据密匙进行DES解密
     *
     * @param key   密匙
     * @param sInfo 要解密的密文
     * @return String 返回解密后信息
     */
    public String decryptByDES(SecretKey key, String sInfo) {
        // 定义 加密算法,
        String Algorithm = "DES";
        // 加密随机数生成器 (RNG)
        SecureRandom sr = new SecureRandom();
        byte[] cipherByte = null;
        try {
            // 得到加密/解密器
            Cipher c1 = Cipher.getInstance(Algorithm);
            // 用指定的密钥和模式初始化Cipher对象
            c1.init(Cipher.DECRYPT_MODE, key, sr);
            // 对要解密的内容进行编码处理
            cipherByte = c1.doFinal(hex2byte(sInfo));
        } catch (Exception e) {
            e.printStackTrace();
        }
        // return byte2hex(cipherByte);
        return new String(cipherByte);
    }
    // /////////////////////////////////////////////////////////////////////////////
    /**
     * 创建密匙组,并将公匙,私匙放入到指定文件中
     *
     * 默认放入mykeys.bat文件中
     */
    public void createPairKey() {
        try {
            // 根据特定的算法一个密钥对生成器
            KeyPairGenerator keygen = KeyPairGenerator.getInstance("DSA");
            // 加密随机数生成器 (RNG)
            SecureRandom random = new SecureRandom();
            // 重新设置此随机对象的种子
            random.setSeed(1000);
            // 使用给定的随机源(和默认的参数集合)初始化确定密钥大小的密钥对生成器
            keygen.initialize(512, random); // keygen.initialize(512);
            // 生成密钥组
            KeyPair keys = keygen.generateKeyPair();
            // 得到公匙
            PublicKey pubkey = keys.getPublic();
            // 得到私匙
            PrivateKey prikey = keys.getPrivate();
            // 将公匙私匙写入到文件当中
            doObjToFile("mykeys.bat", new Object[] { prikey, pubkey });
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
    /**
     * 利用私匙对信息进行签名 把签名后的信息放入到指定的文件中
     *
     * @param info   要签名的信息
     * @param signfile 存入的文件
     */
    public void signToInfo(String info, String signfile) {
        // 从文件当中读取私匙
        PrivateKey myprikey = (PrivateKey) getObjFromFile("mykeys.bat", 1);
        // 从文件中读取公匙
        PublicKey mypubkey = (PublicKey) getObjFromFile("mykeys.bat", 2);
        try {
            // Signature 对象可用来生成和验证数字签名
            Signature signet = Signature.getInstance("DSA");
            // 初始化签署签名的私钥
            signet.initSign(myprikey);
            // 更新要由字节签名或验证的数据
            signet.update(info.getBytes());
            // 签署或验证所有更新字节的签名,返回签名
            byte[] signed = signet.sign();
            // 将数字签名,公匙,信息放入文件中
            doObjToFile(signfile, new Object[] { signed, mypubkey, info });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 读取数字签名文件 根据公匙,签名,信息验证信息的合法性
     *
     * @return true 验证成功 false 验证失败
     */
    public boolean validateSign(String signfile) {
        // 读取公匙
        PublicKey mypubkey = (PublicKey) getObjFromFile(signfile, 2);
        // 读取签名
        byte[] signed = (byte[]) getObjFromFile(signfile, 1);
        // 读取信息
        String info = (String) getObjFromFile(signfile, 3);
        try {
            // 初始一个Signature对象,并用公钥和签名进行验证
            Signature signetcheck = Signature.getInstance("DSA");
            // 初始化验证签名的公钥
            signetcheck.initVerify(mypubkey);
            // 使用指定的 byte 数组更新要签名或验证的数据
            signetcheck.update(info.getBytes());
            System.out.println(info);
            // 验证传入的签名
            return signetcheck.verify(signed);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 将二进制转化为16进制字符串
     *
     * @param b 二进制字节数组
     * @return String
     */
    public String byte2hex(byte[] b) {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1) {
                hs = hs + "0" + stmp;
            } else {
                hs = hs + stmp;
            }
        }
        return hs.toUpperCase();
    }
    /**
     * 十六进制字符串转化为2进制
     *
     * @param hex
     * @return
     */
    public byte[] hex2byte(String hex) {
        byte[] ret = new byte[8];
        byte[] tmp = hex.getBytes();
        for (int i = 0; i < 8; i++) {
            ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);
        }
        return ret;
    }
    /**
     * 将两个ASCII字符合成一个字节; 如:"EF"-- 0xEF
     *
     * @param src0 byte
     * @param src1 byte
     * @return byte
     */
    public static byte uniteBytes(byte src0, byte src1) {
        byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 }))
                .byteValue();
        _b0 = (byte) (_b0 << 4);
        byte _b1 = Byte.decode("0x" + new String(new byte[] { src1 }))
                .byteValue();
        byte ret = (byte) (_b0 ^ _b1);
        return ret;
    }
    /**
     * 将指定的对象写入指定的文件
     *
     * @param file 指定写入的文件
     * @param objs 要写入的对象
     */
    public void doObjToFile(String file, Object[] objs) {
        ObjectOutputStream oos = null;
        try {
            FileOutputStream fos = new FileOutputStream(file);
            oos = new ObjectOutputStream(fos);
            for (int i = 0; i < objs.length; i++) {
                oos.writeObject(objs[i]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                oos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 返回在文件中指定位置的对象
     *
     * @param file 指定的文件
     * @param i    从1开始
     * @return
     */
    public Object getObjFromFile(String file, int i) {
        ObjectInputStream ois = null;
        Object obj = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            ois = new ObjectInputStream(fis);
            for (int j = 0; j < i; j++) {
                obj = ois.readObject();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return obj;
    }
    /**
     * 测试
     *
     * @param args
     */
    public static void main(String[] args) {
        CryptTest jiami = new CryptTest();
        // 执行MD5加密"Hello world!"
        System.out.println("Hello经过MD5:" + jiami.encryptToMD5("Hello"));
        // 生成一个DES算法的密匙
        SecretKey key = jiami.createSecretKey("DES");
        // 用密匙加密信息"Hello world!"
        String str1 = jiami.encryptToDES(key, "Hello");
        System.out.println("使用des加密信息Hello为:" + str1);
        // 使用这个密匙解密
        String str2 = jiami.decryptByDES(key, str1);
        System.out.println("解密后为:" + str2);
        // 创建公匙和私匙
        jiami.createPairKey();
        // 对Hello world!使用私匙进行签名
        jiami.signToInfo("Hello", "mysign.bat");
        // 利用公匙对签名进行验证。
        if (jiami.validateSign("mysign.bat")) {
            System.out.println("Success!");
        } else {
            System.out.println("Fail!");
        }
    }
}

如何用java实现加密与解密???

通常比较简单的加密方法就是你把文本文件加载读取以后,得到的每一个char加上一个固定的整数,然后再保存,这样内容就看不懂了。 再读取以后,把每一个char减去固定的整数,然后保存,就还原回来了。 这种方法是最最简单的加密方式,不需要使用任何的加密算法。

如何利用JAVA对文档进行加密和解密处理,完整的java类

我以前上密码学课写过一个DES加解密的程序,是自己实现的,不是通过调用java库函数,代码有点长,带有用户界面。需要的话联系我。

java中如何实现对文件和字符串加密. 解密?

DES 密钥生成,加解密方法,,你可以看一下

//DES 密钥生成工具
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
public class GenKey {
    private static final String DES = "DES";
    public static final String SKEY_NAME = "key.des";
    public static void genKey1(String path) {
        // 密钥
        SecretKey skey = null;
        // 密钥随机数生成
        SecureRandom sr = new SecureRandom();
        //生成密钥文件
        File file = genFile(path);
        try {
            // 获取密钥生成实例
            KeyGenerator gen = KeyGenerator.getInstance(DES);
            // 初始化密钥生成器
            gen.init(sr);
            // 生成密钥
            skey = gen.generateKey();
            ObjectOutputStream oos = new ObjectOutputStream(
                    new FileOutputStream(file));
            oos.writeObject(skey);
            oos.close();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * @param file : 生成密钥的路径
     * SecretKeyFactory 方式生成des密钥
     */
    public static void genKey2(String path) {
        // 密钥随机数生成
        SecureRandom sr = new SecureRandom();
        byte[] bytes = sr.generateSeed(20);
        // 密钥
        SecretKey skey = null;
        //生成密钥文件路径
        File file = genFile(path);
        try {
            //创建deskeyspec对象
            DESKeySpec desKeySpec = new DESKeySpec(bytes,9);
            //实例化des密钥工厂
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
            //生成密钥对象
            skey = keyFactory.generateSecret(desKeySpec);
            //写出密钥对象
            ObjectOutputStream oos = new ObjectOutputStream(
                    new FileOutputStream(file));
            oos.writeObject(skey);
            oos.close();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private static File genFile(String path) {
        String temp = null;
        File newFile = null;
        if (path.endsWith("/") || path.endsWith("\\")) {
            temp = path;
        } else {
            temp = path + "/";
        }
        File pathFile = new File(temp);
        if (!pathFile.exists())
            pathFile.mkdirs();
        newFile = new File(temp+SKEY_NAME);
        return newFile;
    }
    public static void main(String[] args) {
        genKey2("E:/a/aa/");
    }
}
//DES加解密方法
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.SecretKey;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
 *制卡文件加/解密 加密方式DES
 */
public class SecUtil {
    public static final Log log = LogFactory.getLog(SecUtil.class);
    /**
     * 解密
     *
     * @param keyPath 密钥路径
     * @param source 解密前文件
     * @param dest 解密后文件
     */
    public static void decrypt(String keyPath, String source, String dest) {
        SecretKey key = null;
        try {
            ObjectInputStream keyFile = new ObjectInputStream(
                    // 读取加密密钥
                    new FileInputStream(keyPath));
            key = (SecretKey) keyFile.readObject();
            keyFile.close();
        } catch (FileNotFoundException ey1) {
            log.info("Error when read keyFile");
            throw new RuntimeException(ey1);
        } catch (Exception ey2) {
            log.info("error when read the keyFile");
            throw new RuntimeException(ey2);
        }
        // 用key产生Cipher
        Cipher cipher = null;
        try {
            // 设置算法,应该与加密时的设置一样
            cipher = Cipher.getInstance("DES");
            // 设置解密模式
            cipher.init(Cipher.DECRYPT_MODE, key);
        } catch (Exception ey3) {
            log.info("Error when create the cipher");
            throw new RuntimeException(ey3);
        }
        // 取得要解密的文件并解密
        File file = new File(source);
        String filename = file.getName();
        try {
            // 输出流,请注意文件名称的获取
            BufferedOutputStream out = new BufferedOutputStream(
                    new FileOutputStream(dest));
            // 输入流
            CipherInputStream in = new CipherInputStream(
                    new BufferedInputStream(new FileInputStream(file)), cipher);
            int thebyte = 0;
            while ((thebyte = in.read()) != -1) {
                out.write(thebyte);
            }
            in.close();
            out.close();
        } catch (Exception ey5) {
            log.info("Error when encrypt the file");
            throw new RuntimeException(ey5);
        }
    }
    /**
     * 加密
     * @param keyPath 密钥路径
     * @param source 加密前文件
     * @param dest 加密后文件
     */
    public static void encrypt(String keyPath, String source, String dest) {
        SecretKey key = null;
        try {
            ObjectInputStream keyFile = new ObjectInputStream(
                    // 读取加密密钥
                    new FileInputStream(keyPath));
            key = (SecretKey) keyFile.readObject();
            keyFile.close();
        } catch (FileNotFoundException ey1) {
            log.info("Error when read keyFile");
            throw new RuntimeException(ey1);
        } catch (Exception ey2) {
            log.info("error when read the keyFile");
            throw new RuntimeException(ey2);
        }
        // 用key产生Cipher
        Cipher cipher = null;
        try {
            // 设置算法,应该与加密时的设置一样
            cipher = Cipher.getInstance("DES");
            // 设置解密模式
            cipher.init(Cipher.ENCRYPT_MODE, key);
        } catch (Exception ey3) {
            log.info("Error when create the cipher");
            throw new RuntimeException(ey3);
        }
        // 取得要解密的文件并解密
        File file = new File(source);
        String filename = file.getName();
        try {
            // 输出流,请注意文件名称的获取
            BufferedOutputStream out = new BufferedOutputStream(
                    new FileOutputStream(dest));
            // 输入流
            CipherInputStream in = new CipherInputStream(
                    new BufferedInputStream(new FileInputStream(file)), cipher);
            int thebyte = 0;
            while ((thebyte = in.read()) != -1) {
                out.write(thebyte);
            }
            in.close();
            out.close();
        } catch (Exception ey5) {
            log.info("Error when encrypt the file");
            throw new RuntimeException(ey5);
        }
    }
}

Java 加密解密的方法都有哪些

加密解密并非java才有的,所有编程语言都有加密和解密。 目前的加密解密主要可分为以下2大类: 对称秘钥加密:如DES算法,3DES算法,TDEA算法,Blowfish算法,RC5算法,IDEA算法等。其主要特点是加密方和解密方都有同一个密码,加密方和解密方可以使用秘钥任意加密解密。 非对称密码加密:这种加密方式加密方仅有加密秘钥,对加密后的密文无法反向解密,解密方仅有解密秘钥,无法对明文进行加密。 另外还有一些摘要算法,比如MD5和HASH此类算法不可逆,但经常用来作为确认字段或者对一些重要匹配信息签名防止明文内容被修改。

如何用Java进行3DES加密解密

这里是例子,直接拿来用就可以了。

package com.nnff.des;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/*字符串 DESede(3DES) 加密
 * ECB模式/使用PKCS7方式填充不足位,目前给的密钥是192位
 * 3DES(即Triple DES)是DES向AES过渡的加密算法(1999年,NIST将3-DES指定为过渡的
 * 加密标准),是DES的一个更安全的变形。它以DES为基本模块,通过组合分组方法设计出分组加
 * 密算法,其具体实现如下:设Ek()和Dk()代表DES算法的加密和解密过程,K代表DES算法使用的
 * 密钥,P代表明文,C代表密表,这样,
 * 3DES加密过程为:C=Ek3(Dk2(Ek1(P)))
 * 3DES解密过程为:P=Dk1((EK2(Dk3(C)))
 */
public class ThreeDes {
    /** 
     * @param args在java中调用sun公司提供的3DES加密解密算法时,需要使
     * 用到$JAVA_HOME/jre/lib/目录下如下的4个jar包:
     *jce.jar
     *security/US_export_policy.jar
     *security/local_policy.jar
     *ext/sunjce_provider.jar
     */
    private static final String Algorithm = "DESede"; //定义加密算法,可用 DES,DESede,Blowfish
    //keybyte为加密密钥,长度为24字节
    //src为被加密的数据缓冲区(源)
    public static byte[] encryptMode(byte[] keybyte,byte[] src){
        try {
            //生成密钥
            SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
            //加密
            Cipher c1 = Cipher.getInstance(Algorithm);
            c1.init(Cipher.ENCRYPT_MODE, deskey);
            return c1.doFinal(src);//在单一方面的加密或解密
        } catch (java.security.NoSuchAlgorithmException e1) {
            // TODO: handle exception
            e1.printStackTrace();
        }catch(javax.crypto.NoSuchPaddingException e2){
            e2.printStackTrace();
        }catch(java.lang.Exception e3){
            e3.printStackTrace();
        }
        return null;
    }
    //keybyte为加密密钥,长度为24字节
    //src为加密后的缓冲区
    public static byte[] decryptMode(byte[] keybyte,byte[] src){
        try {
            //生成密钥
            SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
            //解密
            Cipher c1 = Cipher.getInstance(Algorithm);
            c1.init(Cipher.DECRYPT_MODE, deskey);
            return c1.doFinal(src);
        } catch (java.security.NoSuchAlgorithmException e1) {
            // TODO: handle exception
            e1.printStackTrace();
        }catch(javax.crypto.NoSuchPaddingException e2){
            e2.printStackTrace();
        }catch(java.lang.Exception e3){
            e3.printStackTrace();
        }
        return null;
    }
    //转换成十六进制字符串
    public static String byte2Hex(byte[] b){
        String hs="";
        String stmp="";
        for(int n=0; n < b.length; n++){
            stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
            if(stmp.length()==1){
                hs = hs + "0" + stmp;
            }else{
                hs = hs + stmp;
            }
            if(n < b.length-1)hs=hs+":";
        }
        return hs.toUpperCase();
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //添加新安全算法,如果用JCE就要把它添加进去
        Security.addProvider(new com.sun.crypto.provider.SunJCE());
        final byte[] keyBytes = {0x11, 0x22, 0x4F, 0x58,
                (byte)0x88, 0x10, 0x40, 0x38, 0x28, 0x25, 0x79, 0x51,
                (byte)0xCB,
                (byte)0xDD, 0x55, 0x66, 0x77, 0x29, 0x74,
                (byte)0x98, 0x30, 0x40, 0x36,
                (byte)0xE2
        }; //24字节的密钥
        String szSrc = "This is a 3DES test. 测试";
        System.out.println("加密前的字符串:" + szSrc);
        byte[] encoded = encryptMode(keyBytes,szSrc.getBytes());
        System.out.println("加密后的字符串:" + new String(encoded));
        byte[] srcBytes = decryptMode(keyBytes,encoded);
        System.out.println("解密后的字符串:" + (new String(srcBytes)));
    }
}