java中使用DES加密解密

在前面介绍了一些加密解密类的使用,这里综合起来做一个简单的测试,代码如下:

MainActivity:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

package com.home.testdes;

 

import android.os.Bundle;

import android.util.Log;

import android.app.Activity;

 

public class MainActivity extends Activity {

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        DESUtil u = new DESUtil();

        String mi = u.getEnc("I love you");

        Log.i("加密后", mi);

        String ming = u.getDec(mi);

        Log.i("解密后", ming);

    }

}

加密解密工具类:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

package com.home.testdes;

 

import java.security.Key;

import java.security.spec.AlgorithmParameterSpec;

 

import javax.crypto.Cipher;

import javax.crypto.SecretKeyFactory;

import javax.crypto.spec.DESKeySpec;

import javax.crypto.spec.IvParameterSpec;

 

import android.util.Base64;

 

/**

 * 使用DES加密和解密工具类

 *

 * @author Administrator

 *

 */

public class DESUtil {

 

    private Key key;// 密钥的key值

    private byte[] DESkey;

    private byte[] DESIV = { 0x12, 0x34, 0x56, 0x78, (byte) 0x90, (byte) 0xAB,

            (byte) 0xCD, (byte) 0xEF };

    private AlgorithmParameterSpec iv = null;// 加密算法的参数接口

 

    public DESUtil() {

        try {

            this.DESkey = "abcdefghijk".getBytes("UTF-8");// 设置密钥

            DESKeySpec keySpec = new DESKeySpec(DESkey);// 设置密钥参数

            iv = new IvParameterSpec(DESIV);// 设置向量

            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 获得密钥工厂

            key = keyFactory.generateSecret(keySpec);// 得到密钥对象

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

 

    /**

     * 加密String 明文输入密文输出

     *

     * @param inputString

     *            待加密的明文

     * @return 加密后的字符串

     */

    public String getEnc(String inputString) {

        byte[] byteMi = null;

        byte[] byteMing = null;

        String outputString = "";

        try {

            byteMing = inputString.getBytes("UTF-8");

            byteMi = this.getEncCode(byteMing);

            byte[] temp = Base64.encode(byteMi, Base64.DEFAULT);

            outputString = new String(temp);

        } catch (Exception e) {

        } finally {

            byteMing = null;

            byteMi = null;

        }

        return outputString;

    }

 

    /**

     * 解密String 以密文输入明文输出

     *

     * @param inputString

     *            需要解密的字符串

     * @return 解密后的字符串

     */

    public String getDec(String inputString) {

        byte[] byteMing = null;

        byte[] byteMi = null;

        String strMing = "";

        try {

            byteMi = Base64.decode(inputString.getBytes(), Base64.DEFAULT);

            byteMing = this.getDesCode(byteMi);

            strMing = new String(byteMing, "UTF8");

        } catch (Exception e) {

        } finally {

            byteMing = null;

            byteMi = null;

        }

        return strMing;

    }

 

    /**

     * 加密以byte[]明文输入,byte[]密文输出

     *

     * @param bt

     *            待加密的字节码

     * @return 加密后的字节码

     */

    private byte[] getEncCode(byte[] bt) {

        byte[] byteFina = null;

        Cipher cipher;

        try {

            // 得到Cipher实例

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

            cipher.init(Cipher.ENCRYPT_MODE, key, iv);

            byteFina = cipher.doFinal(bt);

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            cipher = null;

        }

        return byteFina;

    }

 

    /**

     * 解密以byte[]密文输入,以byte[]明文输出

     *

     * @param bt

     *            待解密的字节码

     * @return 解密后的字节码

     */

    private byte[] getDesCode(byte[] bt) {

        Cipher cipher;

        byte[] byteFina = null;

        try {

            // 得到Cipher实例

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

            cipher.init(Cipher.DECRYPT_MODE, key, iv);

            byteFina = cipher.doFinal(bt);

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            cipher = null;

        }

        return byteFina;

    }

}

在C#,你可以使用System.Security.Cryptography命名空间下的`DESCryptoServiceProvider`类来进行DES(Data Encryption Standard)加密和解密操作。这里是一个简单的示例: ```csharp using System; using System.IO; using System.Security.Cryptography; public class DESExample { public static void Encrypt(string plainText, string key) { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] salt = new byte[8]; using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider()) { rng.GetBytes(salt); } ICryptoTransform encryptor = des.CreateEncryptor(key, salt); using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write)) { using (StreamWriter sw = new StreamWriter(cs)) { sw.Write(plainText); } byte[] encryptedBytes = ms.ToArray(); // 将盐和加密后的数据组合在一起 byte[] combined = Combine(salt, encryptedBytes); Console.WriteLine("Encrypted data: " + Convert.ToBase64String(combined)); } } des.Clear(); // 清理资源 } public static void Decrypt(byte[] combinedData, string key) { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] salt = ExtractSalt(combinedData); // 提取盐值 ICryptoTransform decryptor = des.CreateDecryptor(key, salt); using (MemoryStream ms = new MemoryStream(combinedData)) { using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read)) { using (StreamReader sr = new StreamReader(cs)) { string decryptedText = sr.ReadToEnd(); Console.WriteLine("Decrypted text: " + decryptedText); } } des.Clear(); } } private static byte[] Combine(byte[] salt, byte[] encryptedBytes) { return salt.Concat(encryptedBytes).ToArray(); } private static byte[] ExtractSalt(byte[] combinedData) { int saltLength = salt.Length; return combinedData.Skip(combinedData.Length - saltLength).Take(saltLength).ToArray(); } } // 调用示例 string plainText = "Hello, DES!"; string key = "YourKey123"; // 16字节的密钥 DESExample.Encrypt(plainText, key); ``` 在这个例子,我们首先创建了一个`DESCryptoServiceProvider`实例,并生成一个随机的盐值。然后分别用于加密和解密过程。请注意,在实际应用你需要妥善保管密钥,因为它是加密过程的关键。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值