All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.jianggujin.codec.JMessageDigest Maven / Gradle / Ivy

The newest version!
/**
 * Copyright 2017-2018 jianggujin (www.jianggujin.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jianggujin.codec;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import com.jianggujin.codec.util.JCodecException;

/**
 * 摘要运算
 * 
 * @author jianggujin
 *
 */
public class JMessageDigest {

   /**
    * 摘要算法
    * 
    * @author jianggujin
    *
    */
   public static enum JMessageDigestAlgorithm {
      MD2("MD2"), MD5("MD5"), SHA_1("SHA-1"), SHA_224("SHA-224"), SHA_256("SHA-256"), SHA_384("SHA-384"), SHA_512(
            "SHA-512");
      private String name;

      private JMessageDigestAlgorithm(String name) {
         this.name = name;
      }

      public String getName() {
         return this.name;
      }
   }

   public static MessageDigest getMessageDigest(JMessageDigestAlgorithm algorithm) {
      return getMessageDigest(algorithm.getName());
   }

   public static MessageDigest getMessageDigest(String algorithm) {
      try {
         return MessageDigest.getInstance(algorithm);
      } catch (NoSuchAlgorithmException e) {
         throw new JCodecException(e);
      }
   }

   /**
    * 加密
    * 
    * @param data
    * @param algorithm
    * @return
    */
   public static byte[] encrypt(byte[] data, JMessageDigestAlgorithm algorithm) {
      return encrypt(data, algorithm.getName());
   }

   /**
    * 加密
    * 
    * @param data
    * @param algorithm
    * @return
    */
   public static byte[] encrypt(byte[] data, String algorithm) {
      return getMessageDigest(algorithm).digest(data);
   }

   /**
    * 加密
    * 
    * @param data
    * @param messageDigest
    * @return
    */
   public static byte[] encrypt(byte[] data, MessageDigest messageDigest) {
      return messageDigest.digest(data);
   }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy