cjavades的简单介绍

博主:adminadmin 2022-11-25 17:39:10 49

本篇文章给大家谈谈cjavades,以及对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

des解密算法,利用C语言解密JAVA语言加密的密码。。密钥为12345678,加密后的密文为:26d086be3a3a62fc

// C 语言 DES用的是 ECB模式, 没有填充

// 因此Java端要对应, 你的明文是 liubiao 吗?

// 另外 DES已经不安全了, 如果可以改为 3DES或者 AES吧。

public class LearnDes {

public static void main(String[] args) {

try {

System.out.println(encrypt("liubiao", "12345678"));

System.out.println(decrypt("26d086be3a3a62fc", "12345678"));

} catch (Exception e) {

e.printStackTrace();

}

}

public static String encrypt(String message, String key) throws Exception {

//Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

Cipher cipher = Cipher.getInstance("DES/ECB/NOPADDING");

DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));

SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");

SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));

//cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);

cipher.init(Cipher.ENCRYPT_MODE, secretKey );

return toHexString(cipher.doFinal(message.getBytes("UTF-8")));

}

public static String decrypt(String message, String key) throws Exception {

byte[] bytesrc = convertHexString(message);

//Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

Cipher cipher = Cipher.getInstance("DES/ECB/NOPADDING");

DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));

SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");

SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));

//cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);

cipher.init(Cipher.DECRYPT_MODE, secretKey );

byte[] retByte = cipher.doFinal(bytesrc);

return new String(retByte);

}

public static byte[] convertHexString(String ss) {

byte digest[] = new byte[ss.length() / 2];

for (int i = 0; i digest.length; i++) {

String byteString = ss.substring(2 * i, 2 * i + 2);

int byteValue = Integer.parseInt(byteString, 16);

digest[i] = (byte) byteValue;

}

return digest;

}

public static String toHexString(byte b[]) {

StringBuffer hexString = new StringBuffer();

for (int i = 0; i b.length; i++) {

String plainText = Integer.toHexString(0xff b[i]);

if (plainText.length() 2)

plainText = "0" + plainText;

hexString.append(plainText);

}

return hexString.toString();

}

}

Java用des加密后用 linux c语言解密 怎么互通

同样的数据 用java和c分别加密看看输出是否一样

如果一样再分别解密 看看输出是否一样

就可以判断是哪里出问题了

java中DES、MD5加密算法在哪个包中?如何分别调用这两个方法实现对输入数据的加密、解密?

java.security.MessageDigest

/*

 * MD5 算法

*/

public class MD5 {

    

    // 全局数组

    private final static String[] strDigits = { "0", "1", "2", "3", "4", "5",

            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

    public MD5() {

    }

    // 返回形式为数字跟字符串

    private static String byteToArrayString(byte bByte) {

        int iRet = bByte;

        // System.out.println("iRet="+iRet);

        if (iRet  0) {

            iRet += 256;

        }

        int iD1 = iRet / 16;

        int iD2 = iRet % 16;

        return strDigits[iD1] + strDigits[iD2];

    }

    // 返回形式只为数字

    private static String byteToNum(byte bByte) {

        int iRet = bByte;

        System.out.println("iRet1=" + iRet);

        if (iRet  0) {

            iRet += 256;

        }

        return String.valueOf(iRet);

    }

    // 转换字节数组为16进制字串

    private static String byteToString(byte[] bByte) {

        StringBuffer sBuffer = new StringBuffer();

        for (int i = 0; i  bByte.length; i++) {

            sBuffer.append(byteToArrayString(bByte[i]));

        }

        return sBuffer.toString();

    }

    public static String GetMD5Code(String strObj) {

        String resultString = null;

        try {

            resultString = new String(strObj);

            MessageDigest md = MessageDigest.getInstance("MD5");

            // md.digest() 该函数返回值为存放哈希值结果的byte数组

            resultString = byteToString(md.digest(strObj.getBytes()));

        } catch (NoSuchAlgorithmException ex) {

            ex.printStackTrace();

        }

        return resultString;

    }

    public static void main(String[] args) {

        MD5 getMD5 = new MD5();

        System.out.println(getMD5.GetMD5Code("000000"));

    }

}

谁能帮我将java中的DES算法改成用C#来实现?

C#也有DES加密。

using System;

using System.IO;

using System.Security.Cryptography;

using System.Text;

using System.Text.RegularExpressions;

/// summary

/// DES加密解密

/// /summary

public static class DES

{

//默认密钥向量

private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };

/// summary

/// DES加密字符串

/// /summary

/// param name="encryptString"待加密的字符串/param

/// param name="encryptKey"加密密钥,要求为8位/param

/// returns加密成功返回加密后的字符串,失败返回源串/returns

public static string Encode(string encryptString, string encryptKey)

{

encryptKey = StringHelper.GetSubString(encryptKey, 8, "");

encryptKey = encryptKey.PadRight(8, ' ');

byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));

byte[] rgbIV = Keys;

byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);

DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();

MemoryStream mStream = new MemoryStream();

CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);

cStream.Write(inputByteArray, 0, inputByteArray.Length);

cStream.FlushFinalBlock();

return Convert.ToBase64String(mStream.ToArray());

}

/// summary

/// DES解密字符串

/// /summary

/// param name="decryptString"待解密的字符串/param

/// param name="decryptKey"解密密钥,要求为8位,和加密密钥相同/param

/// returns解密成功返回解密后的字符串,失败返源串/returns

public static string Decode(string decryptString, string decryptKey)

{

try

{

decryptKey = StringHelper.GetSubString(decryptKey, 8, "");

decryptKey = decryptKey.PadRight(8, ' ');

byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);

byte[] rgbIV = Keys;

byte[] inputByteArray = Convert.FromBase64String(decryptString);

DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();

MemoryStream mStream = new MemoryStream();

CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);

cStream.Write(inputByteArray, 0, inputByteArray.Length);

cStream.FlushFinalBlock();

return Encoding.UTF8.GetString(mStream.ToArray());

}

catch

{

return "";

}

}

}

如何使用JAVA实现对字符串的DES加密和解密

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!");

}

}

}

DES加密解密问题 java与C 通讯

经测试应该是如下问题:

1.注意取字符串bytes是编码保持一致,c的和java的保存一直,问一下c开发用的是那个。

2.key和Iv保持一致

3.加密模式和填充方式保持一致----------------------------这点的可能性比较大

比如C#里

algo.Mode=CipherMode.ECB;

algo.Padding=PaddingMode.None;

则java里对应的为

final Cipher algo=Cipher.getInstance("DES/ECB/NoPadding");

import java.io.IOException;

import java.security.SecureRandom;

import javax.crypto.Cipher;

import javax.crypto.SecretKey;

import javax.crypto.SecretKeyFactory;

import javax.crypto.spec.DESKeySpec;

import sun.misc.BASE64Decoder;

import sun.misc.BASE64Encoder;

public class DesUtil {

private final static String DES = "DES";

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

String data = "fff";//原字符

String key = "80825cf7fedff723";//加密key

System.err.println(encrypt(data, key));

System.err.println(decrypt("FAQXWvLnsSA=", key));//进行解密“FAQXWvLnsSA=”

}

/**

* Description 根据键值进行加密

* @param data

* @param key 加密键byte数组

* @return

* @throws Exception

*/

public static String encrypt(String data, String key) throws Exception {

byte[] bt = encrypt(data.getBytes(), key.getBytes());

String strs = new BASE64Encoder().encode(bt);

return strs;

}

/**

* Description 根据键值进行解密

* @param data

* @param key 加密键byte数组

* @return

* @throws IOException

* @throws Exception

*/

public static String decrypt(String data, String key) throws IOException,

Exception {

if (data == null)

return null;

BASE64Decoder decoder = new BASE64Decoder();

byte[] buf = decoder.decodeBuffer(data);

byte[] bt = decrypt(buf,key.getBytes());

return new String(bt);

}

/**

* Description 根据键值进行加密

* @param data

* @param key 加密键byte数组

* @return

* @throws Exception

*/

private static byte[] encrypt(byte[] data, byte[] key) throws Exception {

// 生成一个可信任的随机数源

SecureRandom sr = new SecureRandom();

// 从原始密钥数据创建DESKeySpec对象

DESKeySpec dks = new DESKeySpec(key);

// 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象

SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);

SecretKey securekey = keyFactory.generateSecret(dks);

// Cipher对象实际完成加密操作

Cipher cipher = Cipher.getInstance(DES);

// 用密钥初始化Cipher对象

cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);

return cipher.doFinal(data);

}

/**

* Description 根据键值进行解密

* @param data

* @param key 加密键byte数组

* @return

* @throws Exception

*/

private static byte[] decrypt(byte[] data, byte[] key) throws Exception {

// 生成一个可信任的随机数源

SecureRandom sr = new SecureRandom();

// 从原始密钥数据创建DESKeySpec对象

DESKeySpec dks = new DESKeySpec(key);

// 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象

SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);

SecretKey securekey = keyFactory.generateSecret(dks);

// Cipher对象实际完成解密操作

Cipher cipher = Cipher.getInstance(DES);

// 用密钥初始化Cipher对象

cipher.init(Cipher.DECRYPT_MODE, securekey, sr);

return cipher.doFinal(data);

}

}

关于cjavades和的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。

The End

发布于:2022-11-25,除非注明,否则均为首码项目网原创文章,转载请注明出处。