V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
cnbattle
V2EX  ›  问与答

一段 Java des 加密代码,求 PHP 实现

  •  
  •   cnbattle · 2021-05-26 17:18:20 +08:00 · 413 次点击
    这是一个创建于 1081 天前的主题,其中的信息可能已经有所发展或是发生改变。

    代码如下

    import java.security.Key;
    import java.security.MessageDigest;
    import java.security.spec.AlgorithmParameterSpec;
    
    import javax.crypto.Cipher;
    import javax.crypto.SecretKeyFactory;
    import javax.crypto.spec.DESKeySpec;
    import javax.crypto.spec.IvParameterSpec;
    
    /**
     * @Description
     */
    
    public class DesUtils12306 {
    
      private final byte[]           DESkey = "L82V6ZVD6J".getBytes(); // 设置密钥,略去
    
      // 设置向量,略去
    
      private AlgorithmParameterSpec iv     = null;                   // 加密算法的参数接口,IvParameterSpec 是它的一个实现
      private Key                    key    = null;
    
      public DesUtils12306() throws Exception {
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        byte[] digest = md.digest(DESkey);
        byte[] keyBytes = new byte[8];
        byte[] ivBytes = new byte[8];
        for (int i = 0; i < 8; i++) {
          keyBytes[i] = digest[i];
        }
        for (int i = 8; i < 16; i++) {
          ivBytes[i - 8] = digest[i];
        }
        DESKeySpec keySpec = new DESKeySpec(keyBytes);// 设置密钥参数
        iv = new IvParameterSpec(ivBytes);// 设置向量
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 获得密钥工厂
        key = keyFactory.generateSecret(keySpec);// 得到密钥对象
      }
    
      public String encode(String data) throws Exception {
        Cipher enCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");// 得到加密对象 Cipher
        enCipher.init(Cipher.ENCRYPT_MODE, key, iv);// 设置工作模式为加密模式,给出密钥和向量
        byte[] pasByte = enCipher.doFinal(data.getBytes());
        return toHexString(pasByte).toUpperCase();
      }
    
    
      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();
      }
    
      public static void main(String[] args) throws Exception {
        DesUtils12306 util = new DesUtils12306();
        String encode = util.encode("123");
        System.out.println(encode);
      }
    }
    
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2749 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 06:19 · PVG 14:19 · LAX 23:19 · JFK 02:19
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.