在我的应用程序中,我正在编码一个字符串,然后生成一个MAC ID(使用javax.crypto.Mac)。但我试图将其解码回来,但我不能。可以请你帮帮我。可以你指出我做错了什么?
代码
String userid = "AmilaI";
String time = gmtFormat.format(now)+ "Z";
String algorithmKey = time + userid;
SecretKeySpec sks = new SecretKeySpec(algorithmKey.getBytes("UTF-8"), "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(sks);
byte[] hashBytes = mac.doFinal(route.getBytes("UTF-8"));
String hmac = Base64.encodeBase64String(hashBytes);
hmac = hmac.replaceAll("\r\n", "");
System.out.println("Encrypted "+ hmac );
byte[] decoded = Base64.decodeBase64(hmac);
System.out.println("Decrypted " + new String(decoded, "UTF-8") + "\n");
如何反转路径并获取alogorithmKey,以便通过解密获取用户ID?
答案 0 :(得分:5)
HmacSHA1是一个哈希,所以它意味着它只能以一种方式工作,你无法从中获取原始值。您需要使用可逆的算法。
答案 1 :(得分:1)
试试这个
public class Crypto {
private static final String engine = "AES";
private static final String crypto = "AES/CBC/PKCS5Padding";
private static Context ctx;
public Crypto(Context cntx) {
ctx = cntx;
}
public byte[] cipher(byte[] data, int mode)
throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, IllegalBlockSizeException,
BadPaddingException, InvalidAlgorithmParameterException {
KeyManager km = new KeyManager(ctx);
SecretKeySpec sks = new SecretKeySpec(km.getId(), engine);
IvParameterSpec iv = new IvParameterSpec(km.getIv());
Cipher c = Cipher.getInstance(crypto);
c.init(mode, sks, iv);
return c.doFinal(data);
}
public byte[] encrypt(byte[] data) throws InvalidKeyException,
NoSuchAlgorithmException, NoSuchPaddingException,
IllegalBlockSizeException, BadPaddingException,
InvalidAlgorithmParameterException {
return cipher(data, Cipher.ENCRYPT_MODE);
}
public byte[] decrypt(byte[] data) throws InvalidKeyException,
NoSuchAlgorithmException, NoSuchPaddingException,
IllegalBlockSizeException, BadPaddingException,
InvalidAlgorithmParameterException {
return cipher(data, Cipher.DECRYPT_MODE);
}
public String armorEncrypt(byte[] data) throws InvalidKeyException,
NoSuchAlgorithmException, NoSuchPaddingException,
IllegalBlockSizeException, BadPaddingException,
InvalidAlgorithmParameterException {
return Base64.encodeToString(encrypt(data), Base64.DEFAULT);
}
public String armorDecrypt(String data) throws InvalidKeyException,
NoSuchAlgorithmException, NoSuchPaddingException,
IllegalBlockSizeException, BadPaddingException,
InvalidAlgorithmParameterException {
return new String(decrypt(Base64.decode(data, Base64.DEFAULT)));
}
}