package qeeka.test.qeeka.test;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
/*
* 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.
*/
/**
*
* @author Neil
*
* To provide a wrapper class for RSA operations,including key
* generation,encryption,decryption,signing and signature verification. RSA can
* be used in the several ways: Encrypt the content using .
*/
public class RSAHelper {
/**
* Key algorithm to be used in this class.
*/
public static final String KEY_ALGORITHM = "RSA";
/**
* Default key length. The value shall be in the range of 512-65536.
*/
private static final int KEY_LENGTH = 1024;
/**
* Identifier of pubic key in the Map.
*/
public static final String PUBLIC_KEY = "PublicKey";
/**
* Identifier of private key in the Map.
*/
public static final String PRIVATE_KEY = "PrivateKey";
/**
* Algorithm to be used for signature and verification.
*/
private static final String SIGNATURE_ALGORITHM = "MD5withRSA";
/**
* Generate a RSA key pair with public key and private key.
*
* @param keyMap to save the key pair, the public key is indicated by
* "PublicKey" and private key is indicated by "PrivateKey".
* @return
*/
public static Result generateKeyPair(Map<String, Object> keyMap) {
Result result = new Result();
//Get one instance of KeyPairGenerator with RSA.
KeyPairGenerator keyPairGenerator = null;
try {
keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);
result.setFailure();
}
if (result.isSuccess()) {
//Get a random seed.
SecureRandom secureRandom = new SecureRandom();
//Use current datetime as random seed.
String currentDateTime = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
secureRandom.setSeed(currentDateTime.getBytes());
//Initialze the key generator with the random number provider. We need to call initialze everytime to get a NEW key pair.
keyPairGenerator.initialize(KEY_LENGTH, secureRandom);
//Ready to generate a key pair.
KeyPair keyPair = keyPairGenerator.genKeyPair();
//Get public and private key.
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
keyMap.put(PUBLIC_KEY, publicKey.getEncoded());
keyMap.put(PRIVATE_KEY, privateKey.getEncoded());
}
return result;
}
/**
* Save the keys into the key file.
*
* @param keyPair key pair to be saved into the file.
* @param publicKeyFileName file to save public key.
* @param privateKeyFileName file to save private key.
*/
public static void saveKeyPair(Map<String, Object> keyPair, String publicKeyFileName, String privateKeyFileName) {
//Write public key into the key file.
try {
FileOutputStream fileOutputStream = new FileOutputStream(publicKeyFileName);
byte[] publicKey = (byte[]) keyPair.get(PUBLIC_KEY);
fileOutputStream.write(publicKey);
fileOutputStream.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);
}
//Write private key into the key file.
try {
FileOutputStream fileOutputStream = new FileOutputStream(privateKeyFileName);
byte[] privateKey = (byte[]) keyPair.get(PRIVATE_KEY);
fileOutputStream.write(privateKey);
fileOutputStream.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Get the key from local file.
*
* @param keyFileName file containing the key.
*
* @return byte array containing the key.
*/
public static byte[] getKey(String keyFileName) {
byte[] keyBytes = null;
//Get key from file.
try {
File file = new File(keyFileName);
FileInputStream fileInputStream = new FileInputStream(file);
DataInputStream dataInputStream = new DataInputStream(fileInputStream);
//Allocate the buffer.
keyBytes = new byte[(int) file.length()];
//Read them all.
dataInputStream.readFully(keyBytes);
dataInputStream.close();
fileInputStream.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);
}
return keyBytes;
}
/**
* Encrypt the data with the public key.
*
* @param data data to be encrypted.
* @param offset offset of data to be encrypted.
* @param length length of data to be encrypted.
* @param publicKeyBytes public key in binary format.
* @return encrypted data.
*/
public static byte[] encryptWithPublicKey(byte[] data, int offset, int length, byte[] publicKeyBytes) {
byte[] encryptedData = null;
try {
//Create a new X509EncodedKeySpec with the given encoded key.
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKeyBytes);
//RSA key factory.
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
//Get the public key from the provided key specification.
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
//Init the ciper.
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
//Encrypt mode!
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
//Do the encryption now !!!!
encryptedData = cipher.doFinal(data, offset, length);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return encryptedData;
}
/**
* Encrypt the data with private key.
*
* @param data data to be encrypted.
* @param offset offset of data to be encrypted.
* @param length length of data to be encrypted.
* @param privateKeyBytes private key in binary format.
* @return encrypted data.
*/
public static byte[] encryptWithPrivateKey(byte[] data, int offset, int length, byte[] privateKeyBytes) {
byte[] encryptedData = null;
try {
// Create a new PKCS8EncodedKeySpec with the given encoded key.
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
//RSA key factory.
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
//Get the private key from the provided key specification.
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
//Init the ciper.
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
//Encrypt mode!
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
//Do the encryption now !!!!
encryptedData = cipher.doFinal(data, offset, length);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return encryptedData;
}
/**
* Decrypt data with public key.
*
* @param data data to be decrypted.
* @param offset offset of data to be decrypted.
* @param length length of data to be decrypted.
* @param publicKeyBytes public key in binary format.
* @return decrypted data.
*/
public static byte[] decryptWithPublicKey(byte[] data, int offset, int length, byte[] publicKeyBytes) {
byte[] encryptedData = null;
try {
//Create a new X509EncodedKeySpec with the given encoded key.
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKeyBytes);
//RSA key factory.
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
//Get the public key from the provided key specification.
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
//Init the ciper.
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
//Decrypt mode!
cipher.init(Cipher.DECRYPT_MODE, publicKey);
//Do the decryption now !!!!
encryptedData = cipher.doFinal(data, offset, length);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return encryptedData;
}
/**
* Decrypt the data with private key bytes.
*
* @param data data to be decrypted.
* @param offset offset of data to be decrypted.
* @param length length of data to be decrypted.
* @param privateKeyBytes private key in binary format.
* @return decrypted data.
*/
public static byte[] decryptWithPrivateKey(byte[] data, int offset, int length, byte[] privateKeyBytes) {
byte[] encryptedData = null;
try {
// Create a new PKCS8EncodedKeySpec with the given encoded key.
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
//RSA key factory.
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
//Get the private key from the provided key specification.
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
//Init the ciper.
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
//Decrypt mode!
cipher.init(Cipher.DECRYPT_MODE, privateKey);
//Do the decryption now !!!!
encryptedData = cipher.doFinal(data, offset, length);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return encryptedData;
}
/**
* Decrypt the data with private key.
*
* @param data data to be decrypted.
* @param offset offset of data to be decrypted.
* @param length length of data to be decrypted.
* @param privateKey private key.
* @return decrypted data.
*/
public static byte[] decryptWithPrivateKey(byte[] data, int offset, int length, PrivateKey privateKey) {
byte[] encryptedData = null;
try {
//RSA key factory.
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
//Init the ciper.
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
//Decrypt mode!
cipher.init(Cipher.DECRYPT_MODE, privateKey);
//Do the decryption now !!!!
encryptedData = cipher.doFinal(data, offset, length);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return encryptedData;
}
/**
* Sign the data with the private key.
*
* @param data data to be signed.
* @param offset offset of data to be signed.
* @param length length of data to be signed.
* @param privateKeyBytes private key in binary format.
* @return signed data.
*/
public static byte[] sign(byte[] data, int offset, int length, byte[] privateKeyBytes) {
byte[] signedData = null;
try {
// Create a new PKCS8EncodedKeySpec with the given encoded key.
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
//RSA key factory.
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
//Get the private key from the provided key specification.
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
//Create the Signature instance with RSA MD5.
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
//Use private key to do the signature.
signature.initSign(privateKey);
//Updates the data to be signed or verified, using the specified array of bytes.
signature.update(data, offset, length);
//Sign it now.
signedData = signature.sign();
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SignatureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return signedData;
}
/**
* Verify the signature.
*
* @param data data signed.
* @param offset offset of data to be verified.
* @param length length of data to be verified.
* @param publicKeyBytes public key in binary format.
* @param dataSignature signature for the data.
* @return Whether the signature is fine.
*/
public static boolean verify(byte[] data, int offset, int length, byte[] publicKeyBytes, byte[] dataSignature) {
boolean result = false;
try {
//Create a new X509EncodedKeySpec with the given encoded key.
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKeyBytes);
//RSA key factory.
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
//Get the public key from the provided key specification.
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
//Create the Signature instance with RSA MD5.
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
//Use pubic key to verify the signature.
signature.initVerify(publicKey);
//Updates the data to be signed or verified, using the specified array of bytes.
signature.update(data, offset, length);
//Verifies the passed-in signature.
result = signature.verify(dataSignature);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SignatureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public static void main(String args[]) throws UnsupportedEncodingException{
Map<String, Object> putKey = new HashMap<String, Object>();
generateKeyPair(putKey);
System.out.println(putKey.get(PUBLIC_KEY));
System.out.println(putKey.get(PRIVATE_KEY));
byte[] encryByte = encryptWithPublicKey("念数成金".getBytes("UTF-8"), 0, "念数成金".getBytes("UTF-8").length, (byte[])putKey.get(PUBLIC_KEY));
System.out.println(new String(decryptWithPrivateKey(encryByte, 0,
encryByte.length, (byte[]) putKey.get(PRIVATE_KEY)),"UTF-8"));
}
}
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
/*
* 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.
*/
/**
*
* @author Neil
*
* To provide a wrapper class for RSA operations,including key
* generation,encryption,decryption,signing and signature verification. RSA can
* be used in the several ways: Encrypt the content using .
*/
public class RSAHelper {
/**
* Key algorithm to be used in this class.
*/
public static final String KEY_ALGORITHM = "RSA";
/**
* Default key length. The value shall be in the range of 512-65536.
*/
private static final int KEY_LENGTH = 1024;
/**
* Identifier of pubic key in the Map.
*/
public static final String PUBLIC_KEY = "PublicKey";
/**
* Identifier of private key in the Map.
*/
public static final String PRIVATE_KEY = "PrivateKey";
/**
* Algorithm to be used for signature and verification.
*/
private static final String SIGNATURE_ALGORITHM = "MD5withRSA";
/**
* Generate a RSA key pair with public key and private key.
*
* @param keyMap to save the key pair, the public key is indicated by
* "PublicKey" and private key is indicated by "PrivateKey".
* @return
*/
public static Result generateKeyPair(Map<String, Object> keyMap) {
Result result = new Result();
//Get one instance of KeyPairGenerator with RSA.
KeyPairGenerator keyPairGenerator = null;
try {
keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);
result.setFailure();
}
if (result.isSuccess()) {
//Get a random seed.
SecureRandom secureRandom = new SecureRandom();
//Use current datetime as random seed.
String currentDateTime = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
secureRandom.setSeed(currentDateTime.getBytes());
//Initialze the key generator with the random number provider. We need to call initialze everytime to get a NEW key pair.
keyPairGenerator.initialize(KEY_LENGTH, secureRandom);
//Ready to generate a key pair.
KeyPair keyPair = keyPairGenerator.genKeyPair();
//Get public and private key.
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
keyMap.put(PUBLIC_KEY, publicKey.getEncoded());
keyMap.put(PRIVATE_KEY, privateKey.getEncoded());
}
return result;
}
/**
* Save the keys into the key file.
*
* @param keyPair key pair to be saved into the file.
* @param publicKeyFileName file to save public key.
* @param privateKeyFileName file to save private key.
*/
public static void saveKeyPair(Map<String, Object> keyPair, String publicKeyFileName, String privateKeyFileName) {
//Write public key into the key file.
try {
FileOutputStream fileOutputStream = new FileOutputStream(publicKeyFileName);
byte[] publicKey = (byte[]) keyPair.get(PUBLIC_KEY);
fileOutputStream.write(publicKey);
fileOutputStream.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);
}
//Write private key into the key file.
try {
FileOutputStream fileOutputStream = new FileOutputStream(privateKeyFileName);
byte[] privateKey = (byte[]) keyPair.get(PRIVATE_KEY);
fileOutputStream.write(privateKey);
fileOutputStream.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Get the key from local file.
*
* @param keyFileName file containing the key.
*
* @return byte array containing the key.
*/
public static byte[] getKey(String keyFileName) {
byte[] keyBytes = null;
//Get key from file.
try {
File file = new File(keyFileName);
FileInputStream fileInputStream = new FileInputStream(file);
DataInputStream dataInputStream = new DataInputStream(fileInputStream);
//Allocate the buffer.
keyBytes = new byte[(int) file.length()];
//Read them all.
dataInputStream.readFully(keyBytes);
dataInputStream.close();
fileInputStream.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);
}
return keyBytes;
}
/**
* Encrypt the data with the public key.
*
* @param data data to be encrypted.
* @param offset offset of data to be encrypted.
* @param length length of data to be encrypted.
* @param publicKeyBytes public key in binary format.
* @return encrypted data.
*/
public static byte[] encryptWithPublicKey(byte[] data, int offset, int length, byte[] publicKeyBytes) {
byte[] encryptedData = null;
try {
//Create a new X509EncodedKeySpec with the given encoded key.
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKeyBytes);
//RSA key factory.
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
//Get the public key from the provided key specification.
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
//Init the ciper.
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
//Encrypt mode!
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
//Do the encryption now !!!!
encryptedData = cipher.doFinal(data, offset, length);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return encryptedData;
}
/**
* Encrypt the data with private key.
*
* @param data data to be encrypted.
* @param offset offset of data to be encrypted.
* @param length length of data to be encrypted.
* @param privateKeyBytes private key in binary format.
* @return encrypted data.
*/
public static byte[] encryptWithPrivateKey(byte[] data, int offset, int length, byte[] privateKeyBytes) {
byte[] encryptedData = null;
try {
// Create a new PKCS8EncodedKeySpec with the given encoded key.
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
//RSA key factory.
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
//Get the private key from the provided key specification.
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
//Init the ciper.
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
//Encrypt mode!
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
//Do the encryption now !!!!
encryptedData = cipher.doFinal(data, offset, length);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return encryptedData;
}
/**
* Decrypt data with public key.
*
* @param data data to be decrypted.
* @param offset offset of data to be decrypted.
* @param length length of data to be decrypted.
* @param publicKeyBytes public key in binary format.
* @return decrypted data.
*/
public static byte[] decryptWithPublicKey(byte[] data, int offset, int length, byte[] publicKeyBytes) {
byte[] encryptedData = null;
try {
//Create a new X509EncodedKeySpec with the given encoded key.
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKeyBytes);
//RSA key factory.
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
//Get the public key from the provided key specification.
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
//Init the ciper.
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
//Decrypt mode!
cipher.init(Cipher.DECRYPT_MODE, publicKey);
//Do the decryption now !!!!
encryptedData = cipher.doFinal(data, offset, length);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return encryptedData;
}
/**
* Decrypt the data with private key bytes.
*
* @param data data to be decrypted.
* @param offset offset of data to be decrypted.
* @param length length of data to be decrypted.
* @param privateKeyBytes private key in binary format.
* @return decrypted data.
*/
public static byte[] decryptWithPrivateKey(byte[] data, int offset, int length, byte[] privateKeyBytes) {
byte[] encryptedData = null;
try {
// Create a new PKCS8EncodedKeySpec with the given encoded key.
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
//RSA key factory.
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
//Get the private key from the provided key specification.
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
//Init the ciper.
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
//Decrypt mode!
cipher.init(Cipher.DECRYPT_MODE, privateKey);
//Do the decryption now !!!!
encryptedData = cipher.doFinal(data, offset, length);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return encryptedData;
}
/**
* Decrypt the data with private key.
*
* @param data data to be decrypted.
* @param offset offset of data to be decrypted.
* @param length length of data to be decrypted.
* @param privateKey private key.
* @return decrypted data.
*/
public static byte[] decryptWithPrivateKey(byte[] data, int offset, int length, PrivateKey privateKey) {
byte[] encryptedData = null;
try {
//RSA key factory.
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
//Init the ciper.
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
//Decrypt mode!
cipher.init(Cipher.DECRYPT_MODE, privateKey);
//Do the decryption now !!!!
encryptedData = cipher.doFinal(data, offset, length);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return encryptedData;
}
/**
* Sign the data with the private key.
*
* @param data data to be signed.
* @param offset offset of data to be signed.
* @param length length of data to be signed.
* @param privateKeyBytes private key in binary format.
* @return signed data.
*/
public static byte[] sign(byte[] data, int offset, int length, byte[] privateKeyBytes) {
byte[] signedData = null;
try {
// Create a new PKCS8EncodedKeySpec with the given encoded key.
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
//RSA key factory.
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
//Get the private key from the provided key specification.
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
//Create the Signature instance with RSA MD5.
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
//Use private key to do the signature.
signature.initSign(privateKey);
//Updates the data to be signed or verified, using the specified array of bytes.
signature.update(data, offset, length);
//Sign it now.
signedData = signature.sign();
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SignatureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return signedData;
}
/**
* Verify the signature.
*
* @param data data signed.
* @param offset offset of data to be verified.
* @param length length of data to be verified.
* @param publicKeyBytes public key in binary format.
* @param dataSignature signature for the data.
* @return Whether the signature is fine.
*/
public static boolean verify(byte[] data, int offset, int length, byte[] publicKeyBytes, byte[] dataSignature) {
boolean result = false;
try {
//Create a new X509EncodedKeySpec with the given encoded key.
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKeyBytes);
//RSA key factory.
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
//Get the public key from the provided key specification.
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
//Create the Signature instance with RSA MD5.
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
//Use pubic key to verify the signature.
signature.initVerify(publicKey);
//Updates the data to be signed or verified, using the specified array of bytes.
signature.update(data, offset, length);
//Verifies the passed-in signature.
result = signature.verify(dataSignature);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SignatureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public static void main(String args[]) throws UnsupportedEncodingException{
Map<String, Object> putKey = new HashMap<String, Object>();
generateKeyPair(putKey);
System.out.println(putKey.get(PUBLIC_KEY));
System.out.println(putKey.get(PRIVATE_KEY));
byte[] encryByte = encryptWithPublicKey("念数成金".getBytes("UTF-8"), 0, "念数成金".getBytes("UTF-8").length, (byte[])putKey.get(PUBLIC_KEY));
System.out.println(new String(decryptWithPrivateKey(encryByte, 0,
encryByte.length, (byte[]) putKey.get(PRIVATE_KEY)),"UTF-8"));
}
}
package qeeka.test.qeeka.test;
public class Result {
private Boolean operateFlag= true;
public void setFailure(){
operateFlag = false;
}
public Boolean isSuccess(){
return operateFlag;
}
public Boolean getOperateFlag() {
return operateFlag;
}
public void setOperateFlag(Boolean operateFlag) {
this. operateFlag = operateFlag;
}
}
相关推荐
RSA算法是一种非对称加密算法,由Ron Rivest、Adi Shamir和Leonard Adleman在1977年提出,因其发明者的名字首字母而得名。在VC++中实现RSA算法需要理解其核心原理,包括大整数运算、素数检测、欧拉函数以及模逆运算...
RSA算法是一种非对称加密算法,由Ron Rivest、Adi Shamir和Leonard Adleman在1977年提出,是目前最广泛使用的公钥加密算法。它结合了大整数因子分解的数学难题,为数据传输提供了强大的安全保护。在此RAR压缩包中,...
RSA算法是一种非对称加密算法,由Ron Rivest、Adi Shamir和Leonard Adleman在1977年提出,因此得名RSA。这种算法在信息安全领域扮演着重要角色,广泛应用于数据加密、数字签名和密钥交换等领域。 在RSA算法中,主要...
### RSA算法实现报告 #### 实验环境 - **硬件配置**:处理器:Intel(R) Core(TM) i5-2430M CPU @ 2.40GHz (4CPUs), ~2.4GHz;内存:2048MB RAM - **软件工具**: - 操作系统:Windows 7 旗舰版 - 开发工具:...
RSA算法加解密 RSA算法是第一个既能用于数据加密也能用于数字签名的算法。它易于理解和操作,也很流行。算法的名字以发明者的名字命名:Ron Rivest, Adi Shamir 和 Leonard Adleman。但RSA 的安全性一直未能得到...
RSA算法基于一个十分简单的数论事实:将两个大素数相乘十分容易,但是想要对其乘积进行因式分解却极其困难,因此可以将乘积公开作为加密密钥。RSA算法是第一个能同时用于加密和数字签名的算法,也易于理解和操作。...
RSA算法的纯Python实现,压缩包内共4个文件,分别是 1、大整数的运算库(当然不是算加减乘除的,这个python本身就有)。这个库是计算乘模运算,幂模运算(蒙哥马利算法),最大公约数算法及扩展最大公约数算法(扩展...
RSA算法是一种非对称加密算法,由Ron Rivest、Adi Shamir和Leonard Adleman在1977年提出,是现代密码学的基石之一。它的主要特点是使用一对密钥,即公钥和私钥,来进行加密和解密。在C语言中实现RSA算法需要理解其...
RSA算法是一种非对称加密算法,它在信息安全领域扮演着重要的角色,特别是在数据加密和数字签名方面。由Ron Rivest、Adi Shamir和Leonard Adleman在1977年提出,因此得名RSA。这个算法基于两个数学难题:大整数因子...
RSA算法是一种非对称加密算法,它在信息安全领域扮演着重要的角色,特别是在数据加密和数字签名方面。由Ron Rivest、Adi Shamir和Leonard Adleman在1977年提出,RSA的名字就是他们三人姓氏的首字母组合。 实验目的...
RSA算法是一种非对称加密算法,由Ron Rivest、Adi Shamir和Leonard Adleman在1977年提出,因此得名RSA。这种算法基于大整数因子分解的困难性,是现代密码学的基石之一。在C语言中实现RSA算法,可以帮助我们理解其...
在提供的压缩文件"20073132040295"中,可能包含了一个实现读取硬盘序列号的程序或脚本,以及一个使用RSA算法加密或解密的示例代码。通过学习这些内容,开发者可以更好地理解和掌握这两个重要的IT概念,并在实际项目...
**Delphi中的经典RSA算法源码示例** RSA(Rivest-Shamir-Adleman)是一种非对称加密算法,广泛应用于信息安全领域,包括数据加密、数字签名等。在Delphi编程环境中,理解并实现RSA算法对于开发安全相关的应用至关...
RSA算法是一种著名的非对称加密技术,由Ron Rivest、Adi Shamir和Leonard Adleman在1977年提出,因此得名RSA。它基于大整数因子分解的困难性,使得只有拥有正确密钥的人才能解密信息。在本文中,我们将深入探讨如何...
这里我们聚焦于一个基于RSA算法的数字签名系统,该系统已用C#编程语言实现。RSA算法是公钥密码学中的基石,而数字签名则是其在确保网络安全中的应用之一。 RSA算法是由Ron Rivest、Adi Shamir和Leonard Adleman三位...
### RSA算法试验报告知识点概述 #### 一、引言与背景 随着信息技术的快速发展和互联网应用的日益广泛,数据安全和个人隐私保护变得尤为重要。在这一背景下,加密技术成为了确保信息在网络上传输过程中不被非法窃取...
第四章的实验主要聚焦在基于RSA算法的加密聊天程序上,这是非对称加密技术的一种典型应用。RSA算法,以其三位发明者Ron Rivest、Adi Shamir和Leonard Adleman的名字首字母命名,是一种公钥加密算法,它利用大整数...
PKCS(Public-Key Cryptography Standards)是由RSA安全公司制定的一系列标准,其中PKCS#1是关于RSA算法的标准,详细定义了RSA算法的使用方式和数据格式。 在PKCS#1 v2.1版本中,主要涵盖了RSA算法的实现细节,包括...
RSA算法是一种非对称加密算法,由Ron Rivest、Adi Shamir和Leonard Adleman在1977年提出,因此得名RSA。这种算法在信息安全领域有着广泛的应用,如数字签名、数据加密和密钥交换等。在本演示中,我们将深入探讨RSA...
加密时把明文分成块,块的大小可变,但不能超过密钥的长度,RSA算法把每一块明文转化为与密钥长度相同的密文块。RSA算法利用了陷门单向函数的一种可逆模指数运算。 本文提出的混合密码系统,通过结合DES算法和RSA...