2016-02-25 333 views
-3

这是我的java代码,它使用密钥加密字符串值并正确工作,但我不知道如何将该ecrypted值解密为我的原始值..?如何使用密钥字符串解密SHA-256加密的字符串?

 package com.password; 

     import java.security.InvalidKeyException; 
     import java.security.Key; 
     import java.security.NoSuchAlgorithmException; 
     import java.security.SignatureException; 
     import java.util.Formatter; 
     import javax.crypto.Mac; 
     import javax.crypto.spec.SecretKeySpec; 

     public class Sha256 { 

    //Main Method that have the String values and key 
      public static void main(String s[]) { 
       try { 

        String str ="HelloWorld"; //String Values 
        String key = "[email protected]"; //Secret Key 

        String encry = hashMac(str, key); 
//call the hashMac Method that encrypt the String using key and return the encrypted values.... 
        System.out.println("Encryption : " + encry); 
       } catch (SignatureException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
      } 
    //hashMac Method that encrypt the data and convert into hex values...  
      public static String hashMac(String text, String secretKey) 
        throws SignatureException { 

       try { 
        Key sk = new SecretKeySpec(secretKey.getBytes(), HASH_ALGORITHM); 
        Mac mac = Mac.getInstance(sk.getAlgorithm()); 
        mac.init(sk); 
        final byte[] hmac = mac.doFinal(text.getBytes()); 
        return toHexString(hmac);//call toHexString Methods.... 
       } catch (NoSuchAlgorithmException e1) { 
        // throw an exception or pick a different encryption method 
        throw new SignatureException(
          "error building signature, no such algorithm in device " 
            + HASH_ALGORITHM); 
       } catch (InvalidKeyException e) { 
        throw new SignatureException(
          "error building signature, invalid key " + HASH_ALGORITHM); 
       } 
      } 

      private static final String HASH_ALGORITHM = "HmacSHA256"; 
    //toHexString Method... 
      public static String toHexString(byte[] bytes) { 
       StringBuilder sb = new StringBuilder(bytes.length * 2); 

       Formatter formatter = new Formatter(sb); 
       for (byte b : bytes) { 
        formatter.format("%02x", b); 
       } 

       return sb.toString(); 

      } 
     } 

如何解密加密字符串....?

+3

SHA是___cure_H_ ash_A_算法。散列是不可逆转的。您无法从哈希码获取原始文本。顺便说一句,这被称为_hashing_,而不是_encryption_。 – Seelenvirtuose

回答

1

这是使用加密字符串值的密钥

不,它不是我的Java代码。这是您的Java代码,它使用SHA-256安全哈希算法,使用字符串值的安全哈希创建消息验证代码

及其正常工作,但我不知道如何解密那些ecrypted值到我原来的价值..?

这里没有加密值。

如何解密加密的字符串....?

这里没有加密String这里。有一个安全散列String,安全散列的主要特性是它不可逆。

你的问题没有意义。

可能您正在寻找的是检查HMAC的方法吗?在这种情况下,您需要使用相同的密钥从相同的消息重新创建HMAC,然后进行比较。

+0

,加密值:2bd9fe68764035e7758813695abbe1beb7a62abce6b9cc8a81a610e89ad6242f这是加密值。 –

+0

@ user3911776对于第三次或第四次,这些是* not * encrypted值。这是HMAC的价值。这不是一个加密过程,它是不可逆的。为什么你发布价值,你期望我做什么,这是更多的奥秘。 – EJP