备忘录 - Java Cryptograp Architecture (JCA Java加密架构 )

本文详细介绍了Java加密架构(JCA)的相关概念和服务提供者,包括Sun、BouncyCastle等,以及加密引擎如MessageDigest、Cipher等。同时,还探讨了如何安装和注册这些提供者,并提供了具体的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://docs.oracle.com/javase/8/docs/technotes/guides/security/crypto/CryptoSpec.html

加密架构 JCA
	架构
		加密服务提供者
			Sun、 SunJSSE、 SunJCE、 SunRsaSign
			Bouncy Castle
		加密引擎
			MessageDigest
			Signature
			Cipher
			SecureRandom
			Message Authentication Codes (MAC)
			 KeyFactory
			 SecretKeyFactory
			 KeyPairGenerator
			KeyGenerator
			KeyAgreement
				DH
			AlgorithmParameters
			AlgorithmParameterGenerator 
			KeyStore
			CertificateFactory
			CertPathBuilder
			CertPathValidator
			CertStore
		算法
			SHA1WITHRSA
			SHA256WITHRSA
			...
		java.sercutiry.*
	高级类
		Provider
			不指定提供者时的提供程序的搜寻机制
				按注册优先级,按顺序查找
			安装提供者程序
				安装在classpath路径中
				安装在标准扩展目录:jre/lib/ext
			注册提供者程序
				静态注册
					jre/lib/security/java.security 文件
				动态注册
					Security.addProvider(Provider);
					Security.insertProviderAt(Provider,position);
		Security
			管理提供程序
				查询,添加,删除提供程序
			安全属性设置
		SecureRandom
			强随机数
		MessageDigest
			MD算法
				MD5
			SHA算法:安全哈希算法(Secure Hash Algorithm)
				SHA1
				SHA256
			MAC算法
				HmacMD5
		Signature
			DSA
			RSAwithMD5
			签名/验证
		Cipher
			加密解密
				块加密
					数据加密前需要填充字节满足输入块长度,解密后剥离
						填充类型
							PKCS5PADDING
				流加密
					处理任意长度数据,无需填充
		Mac
		KeyAgreement
			Diffie-Hellman
		密钥生成器
			KeyGenerator
			KeyPairGenerator
		密钥管理
			KeyStore
				读取PKCS12 和 JKS 格式的密钥库信息

package inaction.jca;

import inaction.Log;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.Test;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Arrays;
import java.util.Base64;

/**
 * @author oniong
 * on 2018/4/29.
 */
public class JCATest {

    public static void main(String[] args) throws Exception{

        /*Security.addProvider(Provider);
        Security.insertProviderAt(Provider,position);*/
    }

    @Test
    public void mac()throws Exception{
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(128);
        Key key = keyGen.generateKey();
        Mac mac = Mac.getInstance("HMACMD5");
        mac.init(key);
        Log.println(Base64.getEncoder().encodeToString(mac.doFinal("123456".getBytes())));

    }

    @Test
    public void cipher()throws Exception{
        Provider provider = new BouncyCastleProvider();
        Log.println(provider.getName());
        Security.addProvider(provider);
        String alg = "AES/ECB/PKCS5Padding";
        KeyGenerator keyGen = KeyGenerator.getInstance("AES","BC");
        keyGen.init(128);
        Key key = keyGen.generateKey();
        Log.println(new String(key.getEncoded()));
        Cipher cipher = Cipher.getInstance(alg);
//        cipher.init(Cipher.ENCRYPT_MODE,key);
        cipher.init(Cipher.ENCRYPT_MODE,new SecretKeySpec("abcdefghijklmnop".getBytes(),"AES"));
        Log.println(Base64.getEncoder().encodeToString(cipher.doFinal("123456789".getBytes())));

        ByteArrayInputStream input = new ByteArrayInputStream("123456789".getBytes());
        CipherInputStream cipherInputStream = new CipherInputStream(input,cipher);
        ByteArrayOutputStream output = new ByteArrayOutputStream(1024);
        byte[] data = new byte[8];
        for(;;){
            int len = cipherInputStream.read(data);
            if(len>0){
                output.write(data,0,len);
            }else{
                break;
            }
        }

        Log.println(Base64.getEncoder().encodeToString(output.toByteArray()));

        Cipher cipher2 = Cipher.getInstance(alg);
        cipher2.init(Cipher.DECRYPT_MODE,key);
        cipher2.update(output.toByteArray());
        byte[] v = cipher2.doFinal();
        System.out.println(new String(v));
        ByteArrayInputStream input2 = new ByteArrayInputStream(output.toByteArray());
        CipherInputStream cipherInputStream2 = new CipherInputStream(input2,cipher2);
        ByteArrayOutputStream output2 = new ByteArrayOutputStream(1024);
        byte[] data2 = new byte[8];
        for(;;){
            int len = cipherInputStream2.read(data2);
            if(len>0){
                output2.write(data2,0,len);
            }else{
                break;
            }
        }
        Log.println(new String(output2.toByteArray()));
    }

    @Test
    public void signature()throws Exception{
        KeyPairBuilder keyPairBuilder = new KeyPairBuilder("RSA",1024).build();
        Log.println(keyPairBuilder.getPrivateKey().getFormat());
        Log.println(keyPairBuilder.privateKey());
        Log.println(keyPairBuilder.getPublicKey().getFormat());
        Log.println(keyPairBuilder.publicKey());

        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyPairBuilder.privateKey().getBytes());
        Log.println(pkcs8EncodedKeySpec.getFormat());

        Signature signature = Signature.getInstance("SHA1WITHRSA");
        signature.initSign(keyPairBuilder.getPrivateKey());
        byte[] src = "123456".getBytes();
        signature.update(src);
        byte[] out = signature.sign();
        Log.println(Base64.getEncoder().encodeToString(out));
    }

    @Test
    public void sr()throws Exception{
        byte[] seed = new byte[]{27, -31, 44, -111, -67, -18, 31, 66, 88, 120};
        Log.println(Arrays.toString(seed));
        SecureRandom secureRandom = SecureRandom.getInstanceStrong();
        secureRandom.setSeed(seed);
        Log.println(secureRandom.getAlgorithm());
        secureRandom.ints(2,0,Integer.MAX_VALUE).forEach(value -> Log.println(value));
        secureRandom.longs(2,0,Long.MAX_VALUE).forEach(value -> Log.println(value));
        secureRandom.doubles(2,1,Long.MAX_VALUE).forEach(value -> Log.println(value));
        byte[] data = new byte[128];
        secureRandom.nextBytes(data);
        Log.println(Base64.getEncoder().encodeToString(data));

    }

    @Test
    public void md()throws Exception{

        MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
        messageDigest.getProvider().entrySet().forEach(entry->{
            Log.println(entry.getValue(),":",entry.getKey());
        });
        Log.println("Provider:",messageDigest.getProvider());
        Log.println("Algorithm:",messageDigest.getAlgorithm());
        String input = "123456";
        Log.println("Input:",input);
        byte[] output = messageDigest.digest(input.getBytes());
        Log.println("Output Base64:",Base64.getEncoder().encodeToString(output));
    }

}

转载于:https://my.oschina.net/congwei/blog/1803264

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值