资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

java代码中的密钥加密 java 密码加密解密

java密码加密与解密

以下两个类可以很方便的完成字符串的加密和解密

梁平网站建设公司成都创新互联公司,梁平网站设计制作,有大型网站制作公司丰富经验。已为梁平上千提供企业网站建设服务。企业网站搭建\成都外贸网站建设要多少钱,请找那个售后服务好的梁平做网站的公司定做!

加密 CryptHelper encrypt(password)

解密 CrypHelper decrypt(password)

代码如下

CryptUtils java

[java]

package gdie lab crypt;

import java io IOException;

import javax crypto Cipher;

import javax crypto KeyGenerator;

import javax crypto SecretKey;

import apache xerces internal impl dv util Base ;

public class CryptUtils {

private static String Algorithm = DES ;

private static byte[] DEFAULT_KEY=new byte[] { };

private static String VALUE_ENCODING= UTF ;

/**

* 生成密钥

*

* @return byte[] 返回生成的密钥

* @throws exception

*             扔出异常

*/

public static byte[] getSecretKey() throws Exception {

KeyGenerator keygen = KeyGenerator getInstance(Algorithm)

SecretKey deskey = keygen generateKey()

// if (debug ) System out println ( 生成密钥 +byte hex (deskey getEncoded

// ()))

return deskey getEncoded()

}

/**

* 将指定的数据根据提供的密钥进行加密

*

* @param input

*            需要加密的数据

* @param key

*            密钥

* @return byte[] 加密后的数据

* @throws Exception

*/

public static byte[] encryptData(byte[] input byte[] key) throws Exception {

SecretKey deskey = new javax crypto spec SecretKeySpec(key Algorithm)

// if (debug )

// {

// System out println ( 加密前的二进串 +byte hex (input ))

// System out println ( 加密前的字符串 +new String (input ))

//

// }

Cipher c = Cipher getInstance(Algorithm)

c init(Cipher ENCRYPT_MODE deskey)

byte[] cipherByte = c doFinal(input)

// if (debug ) System out println ( 加密后的二进串 +byte hex (cipherByte ))

return cipherByte;

}

public static byte[] encryptData(byte[] input) throws Exception {

return encryptData(input DEFAULT_KEY)

}

/**

* 将给定的已加密的数据通过指定的密钥进行解密

*

* @param input

*            待解密的数据

* @param key

*            密钥

* @return byte[] 解密后的数据

* @throws Exception

*/

public static byte[] decryptData(byte[] input byte[] key) throws Exception {

SecretKey deskey = new javax crypto spec SecretKeySpec(key Algorithm)

// if (debug ) System out println ( 解密前的信息 +byte hex (input ))

Cipher c = Cipher getInstance(Algorithm)

c init(Cipher DECRYPT_MODE deskey)

byte[] clearByte = c doFinal(input)

// if (debug )

// {

// System out println ( 解密后的二进串 +byte hex (clearByte ))

// System out println ( 解密后的字符串 +(new String (clearByte )))

//

// }

return clearByte;

}

public static byte[] decryptData(byte[] input) throws Exception {

return decryptData(input DEFAULT_KEY)

}

/**

* 字节码转换成 进制字符串

*

* @param byte[] b 输入要转换的字节码

* @return String 返回转换后的 进制字符串

*/

public static String byte hex(byte[] bytes) {

StringBuilder hs = new StringBuilder()

for(byte b : bytes)

hs append(String format( % $ X b))

return hs toString()

}

public static byte[] hex byte(String content) {

int l=content length()》 ;

byte[] result=new byte[l];

for(int i= ;il;i++) {

int j=i《 ;

String s=content substring(j j+ )

result[i]=Integer valueOf(s ) byteValue()

}

return result;

}

/**

* 将字节数组转换为base 编码字符串

* @param buffer

* @return

*/

public static String bytesToBase (byte[] buffer) {

//BASE Encoder en=new BASE Encoder()

return Base encode(buffer)

//      return encoder encode(buffer)

}

/**

* 将base 编码的字符串解码为字节数组

* @param value

* @return

* @throws IOException

*/

public static byte[] base ToBytes(String value) throws IOException {

//return Base decodeToByteArray(value)

//      System out println(decoder decodeBuffer(value))

//      return decoder decodeBuffer(value)

return Base decode(value)

}

/**

* 加密给定的字符串

* @param value

* @return 加密后的base 字符串

*/

public static String encryptString(String value) {

return encryptString(value DEFAULT_KEY)

}

/**

* 根据给定的密钥加密字符串

* @param value 待加密的字符串

* @param key 以BASE 形式存在的密钥

* @return 加密后的base 字符串

* @throws IOException

*/

public static String encryptString(String value String key) throws IOException {

return encryptString(value base ToBytes(key))

}

/**

* 根据给定的密钥加密字符串

* @param value 待加密的字符串

* @param key 字节数组形式的密钥

* @return 加密后的base 字符串

*/

public static String encryptString(String value byte[] key) {

try {

byte[] data=value getBytes(VALUE_ENCODING)

data=CryptUtils encryptData(data key)

return bytesToBase (data)

} catch (Exception e) {

// TODO Auto generated catch block

e printStackTrace()

return null;

}

}

/**

* 解密字符串

* @param value base 形式存在的密文

* @return 明文

*/

public static String decryptString(String value) {

return decryptString(value DEFAULT_KEY)

}

/**

* 解密字符串

* @param value base 形式存在的密文

* @param key base 形式存在的密钥

* @return 明文

* @throws IOException

*/

public static String decryptString(String value String key) throws IOException {

String s=decryptString(value base ToBytes(key))

return s;

}

/**

* 解密字符串

* @param value base 形式存在的密文

* @param key 字节数据形式存在的密钥

* @return 明文

*/

public static String decryptString(String value byte[] key) {

try {

byte[] data=base ToBytes(value)

data=CryptUtils decryptData(data key)

return new String(data VALUE_ENCODING)

}catch(Exception e) {

e printStackTrace()

return null;

}

}

}

package gdie lab crypt;

import java io IOException;

import javax crypto Cipher;

import javax crypto KeyGenerator;

import javax crypto SecretKey;

import apache xerces internal impl dv util Base ;

public class CryptUtils {

private static String Algorithm = DES ;

private static byte[] DEFAULT_KEY=new byte[] { };

private static String VALUE_ENCODING= UTF ;

/**

* 生成密钥

*

* @return byte[] 返回生成的密钥

* @throws exception

*             扔出异常

*/

public static byte[] getSecretKey() throws Exception {

KeyGenerator keygen = KeyGenerator getInstance(Algorithm)

SecretKey deskey = keygen generateKey()

// if (debug ) System out println ( 生成密钥 +byte hex (deskey getEncoded

// ()))

return deskey getEncoded()

}

/**

* 将指定的数据根据提供的密钥进行加密

*

* @param input

*            需要加密的数据

* @param key

*            密钥

* @return byte[] 加密后的数据

* @throws Exception

*/

public static byte[] encryptData(byte[] input byte[] key) throws Exception {

SecretKey deskey = new javax crypto spec SecretKeySpec(key Algorithm)

// if (debug )

// {

// System out println ( 加密前的二进串 +byte hex (input ))

// System out println ( 加密前的字符串 +new String (input ))

//

// }

Cipher c = Cipher getInstance(Algorithm)

c init(Cipher ENCRYPT_MODE deskey)

byte[] cipherByte = c doFinal(input)

// if (debug ) System out println ( 加密后的二进串 +byte hex (cipherByte ))

return cipherByte;

}

public static byte[] encryptData(byte[] input) throws Exception {

return encryptData(input DEFAULT_KEY)

}

/**

* 将给定的已加密的数据通过指定的密钥进行解密

*

* @param input

*            待解密的数据

* @param key

*            密钥

* @return byte[] 解密后的数据

* @throws Exception

*/

public static byte[] decryptData(byte[] input byte[] key) throws Exception {

SecretKey deskey = new javax crypto spec SecretKeySpec(key Algorithm)

// if (debug ) System out println ( 解密前的信息 +byte hex (input ))

Cipher c = Cipher getInstance(Algorithm)

c init(Cipher DECRYPT_MODE deskey)

byte[] clearByte = c doFinal(input)

// if (debug )

// {

// System out println ( 解密后的二进串 +byte hex (clearByte ))

// System out println ( 解密后的字符串 +(new String (clearByte )))

//

// }

return clearByte;

}

public static byte[] decryptData(byte[] input) throws Exception {

return decryptData(input DEFAULT_KEY)

}

/**

* 字节码转换成 进制字符串

*

* @param byte[] b 输入要转换的字节码

* @return String 返回转换后的 进制字符串

*/

public static String byte hex(byte[] bytes) {

StringBuilder hs = new StringBuilder()

for(byte b : bytes)

hs append(String format( % $ X b))

return hs toString()

}

public static byte[] hex byte(String content) {

int l=content length()》 ;

byte[] result=new byte[l];

for(int i= ;il;i++) {

int j=i《 ;

String s=content substring(j j+ )

result[i]=Integer valueOf(s ) byteValue()

}

return result;

}

/**

* 将字节数组转换为base 编码字符串

* @param buffer

* @return

*/

public static String bytesToBase (byte[] buffer) {

//BASE Encoder en=new BASE Encoder()

return Base encode(buffer)

//  return encoder encode(buffer)

}

/**

* 将base 编码的字符串解码为字节数组

* @param value

* @return

* @throws IOException

*/

public static byte[] base ToBytes(String value) throws IOException {

//return Base decodeToByteArray(value)

//  System out println(decoder decodeBuffer(value))

//  return decoder decodeBuffer(value)

return Base decode(value)

}

/**

* 加密给定的字符串

* @param value

* @return 加密后的base 字符串

*/

public static String encryptString(String value) {

return encryptString(value DEFAULT_KEY)

}

/**

* 根据给定的密钥加密字符串

* @param value 待加密的字符串

* @param key 以BASE 形式存在的密钥

* @return 加密后的base 字符串

* @throws IOException

*/

public static String encryptString(String value String key) throws IOException {

return encryptString(value base ToBytes(key))

}

/**

* 根据给定的密钥加密字符串

* @param value 待加密的字符串

* @param key 字节数组形式的密钥

* @return 加密后的base 字符串

*/

public static String encryptString(String value byte[] key) {

try {

byte[] data=value getBytes(VALUE_ENCODING)

data=CryptUtils encryptData(data key)

return bytesToBase (data)

} catch (Exception e) {

// TODO Auto generated catch block

e printStackTrace()

return null;

}

}

/**

* 解密字符串

* @param value base 形式存在的密文

* @return 明文

*/

public static String decryptString(String value) {

return decryptString(value DEFAULT_KEY)

}

/**

* 解密字符串

* @param value base 形式存在的密文

* @param key base 形式存在的密钥

* @return 明文

* @throws IOException

*/

public static String decryptString(String value String key) throws IOException {

String s=decryptString(value base ToBytes(key))

return s;

}

/**

* 解密字符串

* @param value base 形式存在的密文

* @param key 字节数据形式存在的密钥

* @return 明文

*/

public static String decryptString(String value byte[] key) {

try {

byte[] data=base ToBytes(value)

data=CryptUtils decryptData(data key)

return new String(data VALUE_ENCODING)

}catch(Exception e) {

e printStackTrace()

return null;

}

}

}

CryptHelper java

[java]

package gdie lab crypt;

import javax crypto Cipher;

import javax crypto SecretKey;

import javax crypto SecretKeyFactory;

import javax crypto spec DESKeySpec;

import javax crypto spec IvParameterSpec;

import springframework util DigestUtils;

public class CryptHelper{

private static String CRYPT_KEY = zhongqian ;

//加密

private static Cipher ecip;

//解密

private static Cipher dcip;

static {

try {

String KEY = DigestUtils md DigestAsHex(CRYPT_KEY getBytes()) toUpperCase()

KEY = KEY substring( )

byte[] bytes = KEY getBytes()

DESKeySpec ks = new DESKeySpec(bytes)

SecretKeyFactory skf = SecretKeyFactory getInstance( DES )

SecretKey sk = skf generateSecret(ks)

IvParameterSpec iv = new IvParameterSpec(bytes)

ecip = Cipher getInstance( DES/CBC/PKCS Padding )

ecip init(Cipher ENCRYPT_MODE sk iv )

dcip = Cipher getInstance( DES/CBC/PKCS Padding )

dcip init(Cipher DECRYPT_MODE sk iv )

}catch(Exception ex) {

ex printStackTrace()

}

}

public static String encrypt(String content) throws Exception {

byte[] bytes = ecip doFinal(content getBytes( ascii ))

return CryptUtils byte hex(bytes)

}

public static String decrypt(String content) throws Exception {

byte[] bytes  = CryptUtils hex byte(content)

bytes = dcip doFinal(bytes)

return new String(bytes ascii )

}

//test

public static void main(String[] args) throws Exception {

String password = gly ;

String en = encrypt(password)

System out println(en)

System out println(decrypt(en))

}

}

package gdie lab crypt;

import javax crypto Cipher;

import javax crypto SecretKey;

import javax crypto SecretKeyFactory;

import javax crypto spec DESKeySpec;

import javax crypto spec IvParameterSpec;

import springframework util DigestUtils;

public class CryptHelper{

private static String CRYPT_KEY = zhongqian ;

//加密

private static Cipher ecip;

//解密

private static Cipher dcip;

static {

try {

String KEY = DigestUtils md DigestAsHex(CRYPT_KEY getBytes()) toUpperCase()

KEY = KEY substring( )

byte[] bytes = KEY getBytes()

DESKeySpec ks = new DESKeySpec(bytes)

SecretKeyFactory skf = SecretKeyFactory getInstance( DES )

SecretKey sk = skf generateSecret(ks)

IvParameterSpec iv = new IvParameterSpec(bytes)

ecip = Cipher getInstance( DES/CBC/PKCS Padding )

ecip init(Cipher ENCRYPT_MODE sk iv )

dcip = Cipher getInstance( DES/CBC/PKCS Padding )

dcip init(Cipher DECRYPT_MODE sk iv )

}catch(Exception ex) {

ex printStackTrace()

}

}

public static String encrypt(String content) throws Exception {

byte[] bytes = ecip doFinal(content getBytes( ascii ))

return CryptUtils byte hex(bytes)

}

public static String decrypt(String content) throws Exception {

byte[] bytes  = CryptUtils hex byte(content)

bytes = dcip doFinal(bytes)

return new String(bytes ascii )

}

//test

public static void main(String[] args) throws Exception {

String password = gly ;

String en = encrypt(password)

System out println(en)

System out println(decrypt(en))

}

lishixinzhi/Article/program/Java/hx/201311/26449

Java加密和数字签名

Java加密和数字签名本文主要谈一下密码学中的加密和数字签名 以及其在java中如何进行使用 对密码学有兴趣的伙伴 推荐看 Bruce Schneier的著作 Applied Crypotography 在jdk 的发行版本中安全性方面有了很大的改进 也提供了对RSA算法的直接支持 现在我们从实例入手解决问题(本文仅是作为简单介绍)

一 密码学上常用的概念 

)消息摘要

这是一种与消息认证码结合使用以确保消息完整性的技术 主要使用单向散列函数算法 可用于检验消息的完整性 和通过散列密码直接以文本形式保存等 目前广泛使用的算法有MD MD SHA jdk 对上面都提供了支持 在java中进行消息摘要很简单 java security MessageDigest提供了一个简易的操作方法

/**    *MessageDigestExample java    *Copyright     */    import java security MessageDigest;    /**    *单一的消息摘要算法 不使用密码 可以用来对明文消息(如 密码)隐藏保存    */    public class MessageDigestExample{     public static void main(String[] args) throws Exception{    if(args length!= ){     System err println( Usage:java MessageDigestExample text );     System exit( );    }

byte[] plainText=args[ ] getBytes( UTF );

//使用getInstance( 算法 )来获得消息摘要 这里使用SHA 的 位算法    MessageDigest messageDigest=MessageDigest getInstance( SHA );

System out println( \n +messageDigest getProvider() getInfo());    //开始使用算法    messageDigest update(plainText);    System out println( \nDigest: );    //输出算法运算结果    System out println(new String(messageDigest digest() UTF ));     }    }    还可以通过消息认证码来进行加密实现 javax crypto Mac提供了一个解决方案 有兴趣者可以参考相关API文档 本文只是简单介绍什么是摘要算法

这里补充另一个运用消息摘要的方式加密的例子:    public class TestEncrypt {

public TestEncrypt() {        }

/**         * @param strSrc :strSrc is a string will be encrypted          * @param encName : encName is the algorithm name will be used          *                encName dafault to MD          * @return String         */        public String Encrypt(String strSrc String encName) {

MessageDigest md = null;            String strDes = null;

byte[] bt = strSrc getBytes();            try {                if (encName == null || encName equals( )) {                    encName = MD ;                }                md = MessageDigest getInstance(encName);                md update(bt);                strDes = bytes Hex(md digest()); //to HexString            }            catch (NoSuchAlgorithmException e) {                System out println( Invalid algorithm );                return null;            }            return strDes;        }

public String bytes Hex(byte[] bts) {            String des = ;            String tmp = null;            for (int i = ; i bts length; i++) {                tmp = (Integer toHexString(bts[i] xFF));                if (tmp length() == ) {                    des += ;                }                des += tmp;            }            return des;        }

public static void main(String[]args) {            TestEncrypt te = new TestEncrypt();            String strSrc = 可以加密汉字 Oh and english ;            System out println( Source String: + strSrc);            System out println( Encrypted String: );            System out println( Use Def: + te Encrypt(strSrc null));            System out println( Use MD : + te Encrypt(strSrc MD ));            System out println( Use SHA: + te Encrypt(strSrc SHA ));            System out println( Use SHA : + te Encrypt(strSrc SHA ));        }    }

另外 在javawebparts中的 RequestHelpers里的generateGUID方法也涉及到了MD 的方法 代码如下:    public static String generateGUID(HttpServletRequest request) {

String out = ;        try {          // Construct a string that is prised of:          // Remote IP Address + Host IP Address + Date (yyyyMMdd) +          // Time (hhmmssSSa) + Requested Path + Session ID +          // HashCode Of ParameterMap          StringBuffer *** = new StringBuffer( );          *** append(request getRemoteAddr());          InetAddress ia = InetAddress getLocalHost();          *** append(ia getHostAddress());          *** append(new SimpleDateFormat( yyyyMMddhhmmssSSa ) format(new Date()));          String path = request getServletPath();          String pathInfo = request getPathInfo();          if (pathInfo != null) {            path += pathInfo;          }          *** append(path);          *** append(request getSession(false));          *** append(request getParameterMap() hashCode());          String str = *** toString();          // Now encode the string using an MD encryption algorithm           MessageDigest md = MessageDigest getInstance( md );          md update(str getBytes());          byte[] digest = md digest();          StringBuffer hexStr = new StringBuffer( );          for (int i = ; i digest length; i++) {            str = Integer toHexString( xFF digest[i]);            if (str length() ) {              str = + str;            }            hexStr append(str);          }          out = hexStr toString();        } catch (NoSuchAlgorithmException nsae) {          log error(nsae);        } catch (UnknownHostException uhe) {          log error(uhe);        }        // Return the encrypted string It should be unique based on the        // ponents that prise the plain text string and should always be        // characters thanks to the MD algorithm         return out;

} // End generateGUID()

)私钥加密

消息摘要只能检查消息的完整性 但是单向的 对明文消息并不能加密 要加密明文的消息的话 就要使用其他的算法 要确保机密性 我们需要使用私钥密码术来交换私有消息

这种最好理解 使用对称算法 比如 A用一个密钥对一个文件加密 而B读取这个文件的话 则需要和A一样的密钥 双方共享一个私钥(而在web环境下 私钥在传递时容易被侦听)

使用私钥加密的话 首先需要一个密钥 可用javax crypto KeyGenerator产生一个密钥(java security Key) 然后传递给一个加密工具(javax crypto Cipher) 该工具再使用相应的算法来进行加密 主要对称算法有 DES(实际密钥只用到 位) AES(支持三种密钥长度 位) 通常首先 位 其他的还有DESede等 jdk 种也提供了对对称算法的支持 以下例子使用AES算法来加密

/**    *PrivateExmaple java    *Copyright     */    import javax crypto Cipher;    import javax crypto KeyGenerator;    import java security Key;

/**    *私鈅加密 保证消息机密性    */    public class PrivateExample{     public static void main(String[] args) throws Exception{    if(args length!= ){     System err println( Usage:java PrivateExample text );     System exit( );    }    byte[] plainText=args[ ] getBytes( UTF );

//通过KeyGenerator形成一个key    System out println( \nStart generate AES key );    KeyGenerator keyGen=KeyGenerator getInstance( AES );    keyGen init( );    Key key=keyGen generateKey();    System out println( Finish generating DES key );

//获得一个私鈅加密类Cipher ECB是加密方式 PKCS Padding是填充方法    Cipher cipher=Cipher getInstance( AES/ECB/PKCS Padding );    System out println( \n +cipher getProvider() getInfo());

//使用私鈅加密    System out println( \nStart encryption: );    cipher init(Cipher ENCRYPT_MODE key);    byte[] cipherText=cipher doFinal(plainText);    System out println( Finish encryption: );    System out println(new String(cipherText UTF ));

System out println( \nStart decryption: );    cipher init(Cipher DECRYPT_MODE key);    byte[] newPlainText=cipher doFinal(cipherText);    System out println( Finish decryption: );

System out println(new String(newPlainText UTF ));

}    }

)公钥加密

上面提到 私钥加密需要一个共享的密钥 那么如何传递密钥呢?web环境下 直接传递的话很容易被侦听到 幸好有了公钥加密的出现 公钥加密也叫不对称加密 不对称算法使用一对密钥对 一个公钥 一个私钥 使用公钥加密的数据 只有私钥能解开(可用于加密) 同时 使用私钥加密的数据 只有公钥能解开(签名) 但是速度很慢(比私钥加密慢 到 倍) 公钥的主要算法有RSA 还包括Blowfish Diffie Helman等 jdk 种提供了对RSA的支持 是一个改进的地方

/**    *PublicExample java    *Copyright     */    import java security Key;    import javax crypto Cipher;    import java security KeyPairGenerator;    import java security KeyPair;    /**    *一个简单的公鈅加密例子 Cipher类使用KeyPairGenerator生成的公鈅和私鈅    */    public class PublicExample{     public static void main(String[] args) throws Exception{    if(args length!= ){     System err println( Usage:java PublicExample text );     System exit( );    }

byte[] plainText=args[ ] getBytes( UTF );    //构成一个RSA密钥    System out println( \nStart generating RSA key );    KeyPairGenerator keyGen=KeyPairGenerator getInstance( RSA );    keyGen initialize( );    KeyPair key=keyGen generateKeyPair();    System out println( Finish generating RSA key );

//获得一个RSA的Cipher类 使用公鈅加密    Cipher cipher=Cipher getInstance( RSA/ECB/PKCS Padding );    System out println( \n +cipher getProvider() getInfo());

System out println( \nStart encryption );    cipher init(Cipher ENCRYPT_MODE key getPublic());    byte[] cipherText=cipher doFinal(plainText);    System out println( Finish encryption: );    System out println(new String(cipherText UTF ));

lishixinzhi/Article/program/Java/hx/201311/26898

java加密的几种方式

基本的单向加密算法:

BASE64 严格地说,属于编码格式,而非加密算法

MD5(Message Digest algorithm 5,信息摘要算法)

SHA(Secure Hash Algorithm,安全散列算法)

HMAC(Hash Message Authentication Code,散列消息鉴别码)

复杂的对称加密(DES、PBE)、非对称加密算法:

DES(Data Encryption Standard,数据加密算法)

PBE(Password-based encryption,基于密码验证)

RSA(算法的名字以发明者的名字命名:Ron Rivest, AdiShamir 和Leonard Adleman)

DH(Diffie-Hellman算法,密钥一致协议)

DSA(Digital Signature Algorithm,数字签名)

ECC(Elliptic Curves Cryptography,椭圆曲线密码编码学)

代码参考:

/**

* BASE64加密

*

* @param key

* @return

* @throws Exception

*/

public static String encryptBASE64(byte[] key) throws Exception {

return (new BASE64Encoder()).encodeBuffer(key);

}

/**

* MD5加密

*

* @param data

* @return

* @throws Exception

*/

public static byte[] encryptMD5(byte[] data) throws Exception {

MessageDigest md5 = MessageDigest.getInstance(KEY_MD5);

md5.update(data);

return md5.digest();

}

/**

* SHA加密

*

* @param data

* @return

* @throws Exception

*/

public static byte[] encryptSHA(byte[] data) throws Exception {

MessageDigest sha = MessageDigest.getInstance(KEY_SHA);

sha.update(data);

return sha.digest();

}

}

/**

* 初始化HMAC密钥

*

* @return

* @throws Exception

*/

public static String initMacKey() throws Exception {

KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_MAC);

SecretKey secretKey = keyGenerator.generateKey();

return encryptBASE64(secretKey.getEncoded());

}

/**

* HMAC加密

*

* @param data

* @param key

* @return

* @throws Exception

*/

public static byte[] encryptHMAC(byte[] data, String key) throws Exception {

SecretKey secretKey = new SecretKeySpec(decryptBASE64(key), KEY_MAC);

Mac mac = Mac.getInstance(secretKey.getAlgorithm());

mac.init(secretKey);

return mac.doFinal(data);

}


网站题目:java代码中的密钥加密 java 密码加密解密
链接URL:http://cdkjz.cn/article/hgsdch.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220