2015年4月18日 星期六

[C#][JAVA] 3DES─C# 加密,JAVA 解密

C# 3DES 加密,JAVA 解密程式碼筆記

C#
  /// <summary>  
     /// 加密  
     /// </summary>  
     /// <param name="source">欲加密的字串</param>  
     /// <returns>加密後的字串</returns>  
     private static string desEncryptBase64(string source,string key, string iv)  
     {  
       DESCryptoServiceProvider des = new DESCryptoServiceProvider();  
       byte[] dataByteArray = Encoding.UTF8.GetBytes(source);  
       byte[] key = Encoding.ASCII.GetBytes(key);  
       byte[] iv = Encoding.ASCII.GetBytes(iv);  
       des.Key = key;  
       des.IV = iv;  
       string encrypt = "";  
       using (MemoryStream ms = new MemoryStream())  
       using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))  
       {  
         cs.Write(dataByteArray, 0, dataByteArray.Length);  
         cs.FlushFinalBlock();  
         encrypt = Convert.ToBase64String(ms.ToArray());  
       }  
       return encrypt;  
     }  


Java

 
 //解密
public String decryptDES(String decryptString, String decryptKey, String IV) {

String text = null;
try {
    //byte[] byteMi = new BASE64Decoder().decodeBuffer(decryptString);
    byte[] byteMi = Base64.decodeBase64(decryptString);
    IvParameterSpec zeroIv = new IvParameterSpec(IV.getBytes());
    SecretKeySpec key = new SecretKeySpec(decryptKey.getBytes(), "DES");
    Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
    byte decryptedData[] = cipher.doFinal(byteMi);

    text = new String(decryptedData, "UTF8");
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(Func.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchPaddingException ex) {
        Logger.getLogger(Func.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalBlockSizeException ex) {
        Logger.getLogger(Func.class.getName()).log(Level.SEVERE, null, ex);
    } catch (BadPaddingException ex) {
        Logger.getLogger(Func.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeyException ex) {
        Logger.getLogger(Func.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidAlgorithmParameterException ex) {
        Logger.getLogger(Func.class.getName()).log(Level.SEVERE, null, ex);
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(Func.class.getName()).log(Level.SEVERE, null, ex);
    }
    return text;
   }

沒有留言:

張貼留言