基于Java的SM4(ECB模式,CBC模式)对称加解密实现
warning:
这篇文章距离上次修改已过185天,其中的内容可能已经有所变动。
import org.bouncycastle.crypto.BlockCipher;
import org.bouncycastle.crypto.BufferedBlockCipher;
import org.bouncycastle.crypto.engines.SM4Engine;
import org.bouncycastle.crypto.modes.ECBBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.paddings.ZeroBytePadding;
import org.bouncycastle.crypto.params.ParametersWithIV;
public class SM4Util {
// ECB模式加密
public static byte[] encryptECB(byte[] keyBytes, byte[] data) {
KeyParameter key = new KeyParameter(keyBytes);
BlockCipher engine = new ECBBlockCipher(new SM4Engine());
BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(engine);
cipher.init(true, key);
byte[] result = new byte[cipher.getOutputSize(data.length)];
int length = cipher.processBytes(data, 0, data.length, result, 0);
cipher.doFinal(result, length);
return result;
}
// ECB模式解密
public static byte[] decryptECB(byte[] keyBytes, byte[] data) {
KeyParameter key = new KeyParameter(keyBytes);
BlockCipher engine = new ECBBlockCipher(new SM4Engine());
BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(engine);
cipher.init(false, key);
byte[] result = new byte[cipher.getOutputSize(data.length)];
int length = cipher.processBytes(data, 0, data.length, result, 0);
cipher.doFinal(result, length);
return result;
}
// CBC模式加密
public static byte[] encryptCBC(byte[] keyBytes, byte[] ivBytes, byte[] data) {
KeyParameter key = new KeyParameter(keyBytes);
ParametersWithIV params = new ParametersWithIV(key, ivBytes);
BlockCipher engine = new SM4Engine();
BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(engine), new ZeroBytePadding());
cipher.init(true, params);
byte[] result = new byte[cipher.getOutputSize(data.length)];
int length = cipher.processBytes(data, 0, data.length, result, 0);
cipher.doFinal(result, length);
return result;
}
// CBC模式解密
public static byte[] decryptCBC(byte[] keyBytes, byte[] ivBytes, byte[] data) {
KeyParameter key = new KeyParameter(keyBytes);
ParametersWithIV params = new ParametersWithIV(key, ivBytes);
BlockCipher engine = new S
评论已关闭