com.java.demo.RsaDemo.java Source code

Java tutorial

Introduction

Here is the source code for com.java.demo.RsaDemo.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.java.demo;

import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import org.apache.commons.codec.binary.Hex;

/**
 *
 * @author Administrator
 */
public class RsaDemo {

    static RSAPublicKey rSAPublicKey;
    static RSAPrivateKey rSAPrivateKey;

    public static void main(String[] args) {
        Init();
        String str = "123";
        byte[] result = Encrypt(str);
        System.out.println(Hex.encodeHexString(result));
        boolean verifyRet = Verify(str, result);
        System.out.println("com.Java.Demo.RsaDemo.main()" + verifyRet);
    }

    public static void Init() {
        try {
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(512);
            KeyPair kp = keyPairGenerator.generateKeyPair();
            rSAPublicKey = (RSAPublicKey) kp.getPublic();
            rSAPrivateKey = (RSAPrivateKey) kp.getPrivate();
        } catch (Exception ex) {
            System.out.println("com.Java.Demo.RsaDemo.Init()" + ex.getMessage());
        }
    }

    public static byte[] Encrypt(String str) {
        try {
            PKCS8EncodedKeySpec pKCS8EncodedKeySpec = new PKCS8EncodedKeySpec(rSAPrivateKey.getEncoded());
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PrivateKey privateKey = keyFactory.generatePrivate(pKCS8EncodedKeySpec);
            Signature signature = Signature.getInstance("MD5withRSA");
            signature.initSign(privateKey);
            signature.update(str.getBytes());
            byte[] result = signature.sign();
            return result;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return null;
        }
    }

    public static boolean Verify(String str, byte[] enstr) {
        try {
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(rSAPublicKey.getEncoded());
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
            Signature signature = Signature.getInstance("MD5withRSA");
            signature.initVerify(publicKey);
            signature.update(str.getBytes());
            boolean result = signature.verify(enstr);
            return result;
        } catch (Exception e) {
            System.out.println("com.Java.Demo.RsaDemo.Verify()" + e.getMessage());
            return false;
        }
    }
}