加密解密DES

來源:互聯網
上載者:User

package test;</p><p>import java.security.SecureRandom;</p><p>import javax.crypto.Cipher;<br />import javax.crypto.SecretKey;<br />import javax.crypto.SecretKeyFactory;<br />import javax.crypto.spec.DESKeySpec;</p><p>public class Encrypt {</p><p> /**<br /> * 方法名:Encrypt.java<br /> * 日 期:Aug 18, 2009<br /> *<br /> * @param args<br /> */<br /> public Encrypt() {<br /> } </p><p> public byte[] getKey() throws Exception {<br /> return "1234567890".getBytes();<br /> } </p><p> public byte[] encryptData(String encryptdata)<br /> throws Exception {<br /> SecureRandom sr = new SecureRandom();<br /> byte[] rawKeyData = getKey(); </p><p> DESKeySpec dks = new DESKeySpec(rawKeyData); </p><p> SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");<br /> SecretKey key = keyFactory.generateSecret(dks);<br /> Cipher cipher = Cipher.getInstance("DES");<br /> cipher.init(Cipher.ENCRYPT_MODE, key, sr);<br /> byte[] data = encryptdata.getBytes();<br /> byte[] encryptedData = cipher.doFinal(data); </p><p> return encryptedData;<br /> } </p><p> public String decryptData(byte[] decryptdata)<br /> throws Exception { </p><p> SecureRandom sr = new SecureRandom(); </p><p> byte[] rawKeyData = getKey();<br /> DESKeySpec dks = new DESKeySpec(rawKeyData); </p><p> SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");<br /> SecretKey key = keyFactory.generateSecret(dks); </p><p> Cipher cipher = Cipher.getInstance("DES");<br /> cipher.init(Cipher.DECRYPT_MODE, key, sr); </p><p> byte[] encryptedData = decryptdata;<br /> byte[] decryptedData = cipher.doFinal(encryptedData);<br /> return new String(decryptedData);<br /> } </p><p> public static void main(String[] args) {<br /> try {<br /> Encrypt encrypt = new Encrypt();<br /> byte[] enpasswd = encrypt.encryptData("333333");<br /> String depasswd = encrypt.decryptData( enpasswd );<br /> System.out.println("enpasswd==="+enpasswd);<br /> System.out.println("depasswd==="+depasswd);</p><p> } catch (Exception e) {<br /> e.printStackTrace();<br /> }<br /> } </p><p>}<br />

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.