myblog_article_code
myblog_article_code copied to clipboard
Can you help me to look at the how to change this java encrypt code to go?
Recently, I have to rewrite a project from java to go(I have no java experience).By coincidence,it has a encrypt/decrypt module troubled to me.I have read your code detailedly.But some troubles there. The java code:
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import crypto.ByteUtils;
import sun.misc.BASE64Encoder;
public class DES {
private DESKeySpec desKeySpec;
private IvParameterSpec ivSpec;
private String Key = "11111111";
private final static String DES = "DES";
public DES() {
try {
this.desKeySpec = new DESKeySpec(this.Key.getBytes());
this.ivSpec = new IvParameterSpec(this.Key.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
}
private static byte[] encrypt(byte[] data, byte[] key)
{
byte[] result = data;
SecureRandom sr = new SecureRandom();
try
{
DESKeySpec dks = new DESKeySpec(key);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
SecretKey securekey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
result = cipher.doFinal(data);
} catch (Exception e)
{
e.printStackTrace();
}
System.out.println(result);
return result;
}
public byte[] decrypt(byte[] crypted) {
try {
SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
SecretKey key = factory.generateSecret(this.desKeySpec);
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, this.ivSpec);
return cipher.doFinal(crypted);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) throws Exception {
DES des = new DES();
String data = "hello world !";
byte[] crypted = des.encrypt(data.getBytes(),des.Key.getBytes());
BASE64Encoder encoder = new BASE64Encoder();
System.out.println(encoder.encode(crypted));
}
}
As I see that the key should be 8 bytes.but It can work normally and the Iv calculate strangely. Thank you If you give me a hand ...
public DESKeySpec(byte[] key)
throws InvalidKeyException
Creates a DESKeySpec object using the first 8 bytes in key as the key material for the DES key.
The bytes that constitute the DES key are those between key[0] and key[7] inclusive.
These is declared DESKeySpec. The key is not 8 bytes in your code, but DESKeySpec only used the first 8 bytes in the key.