代码之家  ›  专栏  ›  技术社区  ›  Joe

DESede ECB加密解密

  •  0
  • Joe  · 技术社区  · 5 年前

    我正在尝试使用以下代码在java中加密和解密字符串:

    public byte[] encrypt(String message) throws Exception {
        final MessageDigest md = MessageDigest.getInstance("md5");
        final byte[] digestOfPassword = md.digest("MYKEY12345"
                .getBytes("utf-8"));
        final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
        for (int j = 0, k = 16; j < 8;) {
            keyBytes[k++] = keyBytes[j++];
        }
    
        final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
    //        final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
        final Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key);
    
        final byte[] plainTextBytes = message.getBytes("utf-8");
        final byte[] cipherText = cipher.doFinal(plainTextBytes);
        // final String encodedCipherText = new sun.misc.BASE64Encoder()
        // .encode(cipherText);
    
    
    
        Log.d("base64", Base64.getEncoder().encodeToString(cipherText));
    
        return cipherText;
    }
    
    
    public String decrypt(byte[] message) throws Exception {
        final MessageDigest md = MessageDigest.getInstance("md5");
        final byte[] digestOfPassword = md.digest("MYKEY12345"
                .getBytes("utf-8"));
        final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
        for (int j = 0, k = 16; j < 8;) {
            keyBytes[k++] = keyBytes[j++];
        }
    
        final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
    //    final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
        final Cipher decipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
        decipher.init(Cipher.DECRYPT_MODE, key);
    
        // final byte[] encData = new
        // sun.misc.BASE64Decoder().decodeBuffer(message);
        final byte[] plainText = decipher.doFinal(message);
    
        return new String(plainText, "UTF-8");
    }
    

    用法:

    byte[] codedtext = new Common().encrypt("HELLOWORLD!"); // Function to get the Encrption
    

    输出:

     base64: Ya9zBTukyOmdOh5/5vCaGA== // encrypted string converted to base64
     Encrypted : [B@d41c149 
    

    要解密:

     String decodedtext = new Common().decrypt(codedtext); // To decrypt String
    

    输出:

    Decrypted : HELLOWORLD!  // from Encrypted string
    

    现在,如果我使用相同的密钥和字符串在线获取加密密钥,我会得到不同的值。

    Using this link 验证我的加密/解密。

    我才刚刚开始加密/解密,所以对于我在这里做错的任何事情,我们都非常感谢您的帮助。

    0 回复  |  直到 5 年前
        1
  •  0
  •   g00se    5 年前

    你需要

    final byte[] plainText = decipher.doFinal(Base64.getDecoder().decode(message));