栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

用Java加密和解密

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

用Java加密和解密

这是使用 javax.crypto 库和apache commons编解码器库在base64中进行编码和解码的解决方案,我正在寻找:

import java.security.spec.KeySpec;import javax.crypto.Cipher;import javax.crypto.SecretKey;import javax.crypto.SecretKeyFactory;import javax.crypto.spec.DESedeKeySpec;import org.apache.commons.prec.binary.base64;public class TrippleDes {    private static final String UNICODE_FORMAT = "UTF8";    public static final String DESEDE_ENCRYPTION_SCHEME = "DESede";    private KeySpec ks;    private SecretKeyFactory skf;    private Cipher cipher;    byte[] arrayBytes;    private String myEncryptionKey;    private String myEncryptionScheme;    SecretKey key;    public TrippleDes() throws Exception {        myEncryptionKey = "ThisIsSpartaThisIsSparta";        myEncryptionScheme = DESEDE_ENCRYPTION_SCHEME;        arrayBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);        ks = new DESedeKeySpec(arrayBytes);        skf = SecretKeyFactory.getInstance(myEncryptionScheme);        cipher = Cipher.getInstance(myEncryptionScheme);        key = skf.generateSecret(ks);    }    public String encrypt(String unencryptedString) {        String encryptedString = null;        try { cipher.init(Cipher.ENCRYPT_MODE, key); byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT); byte[] encryptedText = cipher.doFinal(plainText); encryptedString = new String(base64.enprebase64(encryptedText));        } catch (Exception e) { e.printStackTrace();        }        return encryptedString;    }    public String decrypt(String encryptedString) {        String decryptedText=null;        try { cipher.init(Cipher.DECRYPT_MODE, key); byte[] encryptedText = base64.deprebase64(encryptedString); byte[] plainText = cipher.doFinal(encryptedText); decryptedText= new String(plainText);        } catch (Exception e) { e.printStackTrace();        }        return decryptedText;    }    public static void main(String args []) throws Exception    {        TrippleDes td= new TrippleDes();        String target="imparator";        String encrypted=td.encrypt(target);        String decrypted=td.decrypt(encrypted);        System.out.println("String To Encrypt: "+ target);        System.out.println("Encrypted String:" + encrypted);        System.out.println("Decrypted String:" + decrypted);    }}

运行以上程序,结果如下:

String To Encrypt: imparatorEncrypted String:FdBNaYWfjpWN9eYghMpbRA==Decrypted String:imparator


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/449996.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号