国密SM —— SM3单向散列、SM3案例实现、SM4分组密码标准、Go语言实现SM4加密

func main() {
	hash := sm3.New()

	hash.Write([]byte("i am wek $$ The_Reader !"))

	result := hash.Sum(nil)

	println("sm3 hash = ",hex.EncodeToString(result))

	hash2 := sm3.Sm3Sum([]byte("i am wek $$ The_Reader !"))
	println("sm3 hash2 = ",hex.EncodeToString(hash2))
}

结果为:

 

SM4分组密码标准

它将明文分成多个等长的模块(block),使用确定的算法和对称密钥对每组分别加密解密。分组加密是极其重要的加密协议组成,SM4的密钥长度及分组长度均为128bit。

SM4加密解密案例:

 



func SM4Encrypt(src []byte, key []byte) []byte {

	block, e := sm4.NewCipher(key)
	if e != nil {
		fmt.Println("newCrypther faild !")
	}
	a := block.BlockSize() - len(src)%block.BlockSize()
	repeat := bytes.Repeat([]byte{byte(a)},a)
	newsrc := append(src, repeat...)

	dst := make([]byte, len(newsrc))
	blockMode := cipher.NewCBCEncrypter(block, key[:block.BlockSize()])
	blockMode.CryptBlocks(dst,newsrc)
	return dst

}




func SM4Decrypto(dst,key []byte)[]byte{

	block, e := sm4.NewCipher(key)
	if e!=nil{
		fmt.Println("newcipher faild! ")
	}
	blockMode := cipher.NewCBCDecrypter(block, key[:block.BlockSize()])

	src := make([]byte, len(dst))
	blockMode.CryptBlocks(src,dst)

	num := int(src[len(src)-1])
	newsrc := src[:len(src)-num]
	return newsrc
}

func main() {
	 a := []byte("erl1233312")
	key := []byte("aabbccddaabbccdd")
	decrypto := SM4Encrypt(a,key)
	fmt.Println("sm4加密后:",hex.EncodeToString(decrypto))
	i := SM4Decrypto(decrypto, key)
	fmt.Println("sm4解密后:",string(i))

}

结果为:

 

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java 中实现国密算法 SM2、SM3SM4 可以使用 Bouncy Castle 密码库。Bouncy Castle 是一个流行的密码库,支持多种密码算法,包括国密算法。 以下是一个简单的示例,说明如何在 Java 中使用 Bouncy Castle 实现 SM2、SM3SM4: 1. 添加 Bouncy Castle 依赖 在 Maven 项目中,可以在 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcprov-jdk15to18</artifactId> <version>1.68</version> </dependency> ``` 2. SM2 加密和解密示例 ```java import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.generators.ECKeyPairGenerator; import org.bouncycastle.crypto.params.*; import org.bouncycastle.crypto.signers.SM2Signer; import org.bouncycastle.crypto.util.PrivateKeyFactory; import org.bouncycastle.crypto.util.PublicKeyFactory; import java.security.SecureRandom; public class SM2Example { public static void main(String[] args) throws Exception { // 生成密钥对 ECKeyPairGenerator ecKeyPairGenerator = new ECKeyPairGenerator(); SecureRandom secureRandom = new SecureRandom(); X9ECParameters ecParams = SECNamedCurves.getByName("sm2p256v1"); ECDomainParameters ecDomainParameters = new ECDomainParameters(ecParams.getCurve(), ecParams.getG(), ecParams.getN(), ecParams.getH(), ecParams.getSeed()); ECKeyGenerationParameters keyParams = new ECKeyGenerationParameters(ecDomainParameters, secureRandom); ecKeyPairGenerator.init(keyParams); AsymmetricCipherKeyPair keyPair = ecKeyPairGenerator.generateKeyPair(); // 加密 SM2Engine sm2Engine = new SM2Engine(); CipherParameters publicKeyParameters = PublicKeyFactory.createKey(keyPair.getPublic().getEncoded()); CipherParameters privateKeyParameters = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded()); sm2Engine.init(true, new ParametersWithRandom(publicKeyParameters, secureRandom)); byte[] plainText = "hello world".getBytes(); byte[] cipherText = sm2Engine.processBlock(plainText, 0, plainText.length); // 解密 sm2Engine.init(false, privateKeyParameters); byte[] decryptedText = sm2Engine.processBlock(cipherText, 0, cipherText.length); System.out.println(new String(decryptedText)); } } ``` 3. SM3 摘要示例 ```java import org.bouncycastle.crypto.digests.SM3Digest; public class SM3Example { public static void main(String[] args) { // 计算摘要 byte[] input = "hello world".getBytes(); SM3Digest digest = new SM3Digest(); digest.update(input, 0, input.length); byte[] result = new byte[digest.getDigestSize()]; digest.doFinal(result, 0); // 输出摘要 System.out.println(bytesToHex(result)); } private static final char[] HEX_ARRAY = "0123456789abcdef".toCharArray(); public static String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for (int i = 0; i < bytes.length; i++) { int v = bytes[i] & 0xFF; hexChars[i * 2] = HEX_ARRAY[v >>> 4]; hexChars[i * 2 + 1] = HEX_ARRAY[v & 0x0F]; } return new String(hexChars); } } ``` 4. SM4 加密和解密示例 ```java import org.bouncycastle.crypto.engines.SM4Engine; import org.bouncycastle.crypto.params.KeyParameter; import java.security.SecureRandom; public class SM4Example { public static void main(String[] args) { // 生成密钥 SecureRandom secureRandom = new SecureRandom(); byte[] key = new byte[16]; secureRandom.nextBytes(key); KeyParameter keyParameter = new KeyParameter(key); // 加密 SM4Engine sm4Engine = new SM4Engine(); sm4Engine.init(true, keyParameter); byte[] plainText = "hello world".getBytes(); byte[] cipherText = new byte[sm4Engine.getOutputSize(plainText.length)]; int length = sm4Engine.processBytes(plainText, 0, plainText.length, cipherText, 0); sm4Engine.doFinal(cipherText, length); // 解密 sm4Engine.init(false, keyParameter); byte[] decryptedText = new byte[sm4Engine.getOutputSize(cipherText.length)]; length = sm4Engine.processBytes(cipherText, 0, cipherText.length, decryptedText, 0); sm4Engine.doFinal(decryptedText, length); System.out.println(new String(decryptedText)); } } ``` 以上是实现 SM2、SM3SM4 的简单示例,具体实现可以根据具体需求进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值