`
sillycat
  • 浏览: 2551945 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

bouncycastle(2)Learn from others BASE64 MD5 SHA HMAC

    博客分类:
  • JAVA
 
阅读更多
bouncycastle(2)Learn from others BASE64 MD5 SHA HMAC

I read the blog written by others. They summarize the encryption and decryption things in java. So I start to read their blog and learn from them about JCE.

Single Side Encryption
BASE64              encoding method, not encryption
MD5(Message Digest algorithm 5)
SHA(Secure Hash Algorithm)
HMAC(Hash Message Authentication Code)

Symmetry Side Encryption
DES(Data Encryption Standard)
PBE(Password-based encryption)
RSA(The authors are as follow: Ron Rivest, AdiShamir, Leonard Adleman)
DH(Diffie-Hellman)
DSA(Digital Signature Algorithm)
ECC(Elliptic Curves Cryptography)

BASE64
The Base64 Content-Transfer-Encoding is designed to represent arbitrary sequences of octets in a form that need not be humanly readable.

A can encrypt the data, and send to B. B will decrypt the data directly.
This is the tool class as follow:
/**
* BASE64 decryption
*
* @param source
* @return
* @throws Exception
*/
publicstatic String decryptBASE64(String source) throws Exception {
byte[] return_source = (new BASE64Decoder()).decodeBuffer(source);
returnnew String(return_source);
}

/**
* BASE64 encryption
*
* @param source
* @return
* @throws Exception
*/
publicstatic String encryptBASE64(String source) throws Exception {
byte[] key = source.getBytes();
return (new BASE64Encoder()).encodeBuffer(key);
}

And the test class named Base64UtilTest will be as follow:
@Test
publicvoid encryptAndDecryptBASE64() throws Exception{
    String source = "hello,sillycat";
    String return_str = Base64Util.encryptBASE64(source);
    Assert.assertTrue(!source.equals(return_str));
    String source_str = Base64Util.decryptBASE64(return_str);
    Assert.assertEquals(source, source_str);
}

Base64 encode the data into 8 * n bytes, if some empty blanks are there, we will use =, for example, aGVsbG8sc2lsbHljYXQ=.

MD5
MD5--- message-digest algorithm 5. It is used to verify if the file is completed downloaded.

A will share the algorithm to B, for example, MD5, SHA, SHA1, SHA-1. And A will share the encrypt data to B. But B will get the algorithm first, and then, B will decrypt the data with algorithm.

The implementation is as follow:
// MD5, SHA, SHA1, SHA-1
privatestaticfinal String KEY_MD5 = "MD5";

publicstatic String encryptMD5(String source) throws Exception {
  byte[] data = source.getBytes();
  MessageDigest md5 = MessageDigest.getInstance(KEY_MD5);
  md5.update(data);
  byte[] return_data = md5.digest();
  returnnew String(return_data);
}

The test implementation will be as follow:
@Test
publicvoid encryptMD5() throws Exception{
  String source = "welcome to this world.";
  String return_str = MD5Util.encryptMD5(source);
  Assert.assertTrue(!source.equals(return_str));

  System.out.println(return_str);
}

SHA
The process and flows are mostly like the MD5, so does the implementation.

HMAC
Hash Message Authentication Code.
A will generate the key first, share the key with B. A will encrypt the data with key, send the data to B.
B will validate the data with key.

The tool implementation will be as follow:
//HMACSHA1,HmacMD5
privatefinalstatic String KEY_MAC = "HMACSHA1";

/**
* HMAC key
*
* @return
* @throws Exception
*/
publicstatic String initMacKey() throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_MAC);

SecretKey secretKey = keyGenerator.generateKey();
return Base64Util.encryptBASE64(new String(secretKey.getEncoded()));
}

/**
* HMAC encrypt
*
* @param data
* @param key
* @return
* @throws Exception
*/
publicstatic String encryptHMAC(String source, String key) throws Exception {
byte[] data = source.getBytes();
SecretKey secretKey = new SecretKeySpec(Base64Util.decryptBASE64(key)
.getBytes(), KEY_MAC);
Mac mac = Mac.getInstance(secretKey.getAlgorithm());
mac.init(secretKey);

byte[] return_data = mac.doFinal(data);
returnnew String(return_data);
}

The test implementation will be as follow:
@Test
publicvoid encryptHMAC() throws Exception{
String key = HMACUtil.initMacKey();
System.out.println("key will be: " + key);

String return_str = HMACUtil.encryptHMAC("hello world", key);
System.out.println("return string will be: " + return_str);
}

From the blog written by others, the class coder will be as follow
package com.sillycat.easycastle.encryption;

import java.security.MessageDigest;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

publicabstractclass Coder {

publicstaticfinal String KEY_SHA = "SHA";
publicstaticfinal String KEY_MD5 = "MD5";

/**
* MAC算法可选以下多种算法
*
* <pre>
* HmacMD5 
* HmacSHA1 
* HmacSHA256 
* HmacSHA384 
* HmacSHA512
* </pre>
*/
publicstaticfinal String KEY_MAC = "HmacMD5";

/**
* BASE64解密
*
* @param key
* @return
* @throws Exception
*/
publicstaticbyte[] decryptBASE64(String key) throws Exception {
return (new BASE64Decoder()).decodeBuffer(key);
}

/**
* BASE64加密
*
* @param key
* @return
* @throws Exception
*/
publicstatic String encryptBASE64(byte[] key) throws Exception {
return (new BASE64Encoder()).encodeBuffer(key);
}

/**
* MD5加密
*
* @param data
* @return
* @throws Exception
*/
publicstaticbyte[] encryptMD5(byte[] data) throws Exception {

MessageDigest md5 = MessageDigest.getInstance(KEY_MD5);
md5.update(data);

return md5.digest();

}

/**
* SHA加密
*
* @param data
* @return
* @throws Exception
*/
publicstaticbyte[] encryptSHA(byte[] data) throws Exception {

MessageDigest sha = MessageDigest.getInstance(KEY_SHA);
sha.update(data);

return sha.digest();

}

/**
* 初始化HMAC密钥
*
* @return
* @throws Exception
*/
publicstatic String initMacKey() throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_MAC);

SecretKey secretKey = keyGenerator.generateKey();
return encryptBASE64(secretKey.getEncoded());
}

/**
* HMAC加密
*
* @param data
* @param key
* @return
* @throws Exception
*/
publicstaticbyte[] encryptHMAC(byte[] data, String key) throws Exception {

SecretKey secretKey = new SecretKeySpec(decryptBASE64(key), KEY_MAC);
Mac mac = Mac.getInstance(secretKey.getAlgorithm());
mac.init(secretKey);

return mac.doFinal(data);

}

}

And his test class will be as follow:
package com.sillycat.easycastle.encryption;

importstatic org.junit.Assert.*;

import java.math.BigInteger;

import org.junit.Test;

publicclass CoderTest {

@Test
publicvoid test() throws Exception {
String inputStr = "简单加密";
System.out.println("原文:" + inputStr);

byte[] inputData = inputStr.getBytes();
String code = Coder.encryptBASE64(inputData);
System.out.println("BASE64加密后:" + code);

byte[] output = Coder.decryptBASE64(code);
String outputStr = new String(output);
System.out.println("BASE64解密后:" + outputStr);

// 验证BASE64加密解密一致性
assertEquals(inputStr, outputStr);

// 验证MD5对于同一内容加密是否一致
assertArrayEquals(Coder.encryptMD5(inputData),
Coder.encryptMD5(inputData));

// 验证SHA对于同一内容加密是否一致
assertArrayEquals(Coder.encryptSHA(inputData),
Coder.encryptSHA(inputData));

String key = Coder.initMacKey();
System.out.println("Mac密钥:" + key);

// 验证HMAC对于同一内容,同一密钥加密是否一致
assertArrayEquals(Coder.encryptHMAC(inputData, key),
Coder.encryptHMAC(inputData, key));

BigInteger md5 = new BigInteger(Coder.encryptMD5(inputData));
System.out.println("MD5:" + md5.toString(16));

BigInteger sha = new BigInteger(Coder.encryptSHA(inputData));
System.out.println("SHA:" + sha.toString(32));

BigInteger mac = new BigInteger(Coder.encryptHMAC(inputData, inputStr));
System.out.println("HMAC:" + mac.toString(16));
}

}

references:
http://snowolf.iteye.com/blog/379860

分享到:
评论

相关推荐

    bouncycastle jar包

    此外,Bouncy Castle还提供了数据压缩和各种编码方式的实现,如Base64、Hex编码等。 **使用Bouncy Castle** 在项目中引入Bouncy Castle jar包后,可以通过以下方式使用: 1. 添加依赖到项目类路径,例如在Maven...

    BouncyCastle依赖.zip

    1. **bcprov-jdk15on-1.62.jar**:这是BouncyCastle的主要加密提供者包,提供了广泛的加密算法实现,如RSA、AES、DES、SHA等。它支持Java 1.5及更高版本,因此名称中的"jdk15on"表示这个版本适用于Java 1.5及以上。...

    BouncyCastle.dll C#依赖工具,用作数据的加解密辅助类

    Bouncy Castle提供了多种哈希算法,如MD5、SHA-1和SHA-2系列,其中SHA-256具有更高的安全性。 5. **消息认证码(MAC)**:MAC结合了哈希函数和密钥,提供了一种验证数据完整性的方法。Bouncy Castle支持HMAC(基于...

    Bouncy Castle 1.64 API及制作工具

    Bouncy Castle 支持多种加密算法,包括对称加密(如 AES、DES、3DES)、非对称加密(RSA、DSA、ECDSA)、哈希函数(MD5、SHA-1、SHA-256 及以上)、消息认证码(MAC)等。这些算法的实现使得开发人员能够灵活选择...

    BouncyCastle.Crypto

    哈希函数如MD5和SHA系列,可以将任意长度的消息转换为固定长度的摘要,用于数据完整性检查。而MAC,如HMAC(基于哈希的消息认证码),结合密钥提供更高级别的数据完整性与来源验证。 4. **数字签名**: Bouncy...

    Python兼容Java bouncycastle包的国密sm2加解密方法

    5. 如果你需要与Java bouncycastle保持兼容,确保在编码和解码时使用相同的格式,例如Base64编码: ```python import base64 # 加密前将明文转换为Base64 plain_text_base64 = base64.b64encode(plain_text.encode...

    org.bouncycastle完整资源包

    6. **签名与哈希**:支持多种签名算法(如RSA、DSA、ECDSA)和哈希算法(如SHA-1、SHA-256、MD5等),可用于数字签名、消息认证码(MAC)等场景。 7. **TLS/SSL协议实现**:`bcprov`模块提供了轻量级的TLS/SSL协议...

    BouncyCastle.Crypto.dll 版本1.8.6 C#语言

    这个库是BouncyCastle项目的一部分,它是一个开源的密码学API,支持多种加密算法和标准,如RSA、AES、DES、SHA、HMAC等。BouncyCastle库分为两个部分:轻量级加密API(Lightweight Cryptography API)和PKCS(Public...

    C# BouncyCastle实现带原文数据PKCS#7 签名、验签

    5. **序列化PKCS#7结构**:将封装好的PKCS#7结构转换为字节数组或Base64字符串,以便在网络上传输或存储。 6. **验证签名**: - 接收到PKCS#7签名后,首先将其反序列化为`Pkcs7SignedData`对象。 - 使用`...

    BouncyCastle.Crypto.dll 版本1.8.1

    2. **广泛的密码学算法**:BouncyCastle 支持众多加密算法,如AES、DES、3DES、Blowfish、RSA、DSA、ECDSA等,还包括哈希函数如SHA-1、SHA-256、MD5等,以及消息认证码(MAC)和伪随机数生成器(PRNG)。 3. **PKCS...

    org.bouncycastle 加密算法包 最新1.69版

    Bouncy Castle 提供了包括 SHA-1、SHA-256、SHA-512 等在内的多种哈希函数,以及 DSA、RSA 等签名算法的实现。 4. **证书和证书路径验证**: 在 PKI 中,X.509 证书用于存储公钥和身份信息。Bouncy Castle 提供了...

    BouncyCastle.Crypto.rar

    BouncyCastle.Crypto.dll是.NET版本的核心组件,包含了大量加密算法的实现,如对称加密(如AES、DES、3DES)、非对称加密(RSA、DSA、ECC)、哈希算法(MD5、SHA-1、SHA-256等)以及消息认证码(MAC)等。...

    BouncyCastle,SM2、SM3、SM4 证书加解密应用例子

    BouncyCastle是一个广泛使用的开源加密库,支持多种加密算法,包括非对称加密、对称加密、哈希函数等。这个例子主要关注的是在中国广泛采用的国密标准——SM2、SM3和SM4算法的应用。 首先,让我们深入理解一下这些...

    bouncycastle集合包

    2. **lcrypto-j2me-138.jar**:这个文件是BouncyCastle针对Java ME(Micro Edition)的版本。"lcrypto"可能代表“Lightweight Crypto”,强调了该版本适用于资源有限的设备。"j2me"表明它是Java 2 Micro Edition的...

    BouncyCastle.Crypto.dll

    《BouncyCastle.Crypto.dll:理解.NET平台的加密利器》 在网络安全日益重要的今天,加密技术扮演了至关重要的角色。BouncyCastle库是Java和.NET平台上广泛使用的加密库之一,而"BouncyCastle.Crypto.dll"正是.NET...

    齐全的Bouncycastle--jar文件

    3. **Crypto**:Bouncy Castle的Crypto模块包含了许多加密和哈希算法,如椭圆曲线加密(ECC)、DSA(Digital Signature Algorithm)、MD5、SHA-1、SHA-256等。此外,它还支持PKCS#7、PKCS#8、OpenPGP等相关标准,...

Global site tag (gtag.js) - Google Analytics