这个世界很精彩,这个世界很无奈。是的,在互联网时代,如何保护自己的数据,如何对数据进行加密和效验就变得非常的重要。这里总结一下Android平台使用Java语言,利用RSA算法对数据进行校验的经验。
先来看下如何RSA加密算法对数据进行校验的流程:
1、首先要用openssh之类的程序生成一个私钥
2、再根据私钥生成一个公钥
3、使用私钥和公钥,对数据进行签名,得到签名文件。
4、使用公钥和签名文件就可以对数据进行校验了。
再来看下如何实现:
1、生成2048位的私钥:
openssl genrsa -out private.pem 2048
2、生成公钥
使用openssh也可以生成公钥,但是在使用的过程中,发现由于格式的问题,使用openssh生成的公钥在Java中使用时总是提示异常,所以最后还是根据网上的相关资料,使用Java语言来写了程序,使用的公钥可以在Java中使用,代码如下:
GenPublic.java
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.PublicKey;
import java.security.Security;
import java.security.Signature;
import java.security.interfaces.DSAParams;
import java.security.interfaces.DSAPublicKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.security.spec.RSAPublicKeySpec;
import javax.xml.bind.DatatypeConverter;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMReader;
import org.bouncycastle.util.encoders.Base64;
public class GenPublic {
public static PrintStream out = System.out;
public static PrintStream err = System.err;
private static void genPublicKey(String privateFile,String pubFile) {
try {
PEMReader pemReader = new PEMReader(new FileReader(privateFile));
KeyPair pair = (KeyPair)pemReader.readObject();
PublicKey pubK