
接你代码后面
String algorithm = publickeygetAlgorithm(); // 获取算法KeyFactory keyFact = KeyFactorygetInstance(algorithm);
BigInteger prime = null;
if ("RSA"equals(algorithm)) { // 如果是RSA加密
RSAPublicKeySpec keySpec = (RSAPublicKeySpec)keyFactgetKeySpec(publickey, RSAPublicKeySpecclass);
prime = keySpecgetModulus();
} else if ("DSA"equals(algorithm)) { // 如果是DSA加密
DSAPublicKeySpec keySpec = (DSAPublicKeySpec)keyFactgetKeySpec(publickey, DSAPublicKeySpecclass);
prime = keySpecgetP();
}
int len = primetoString(2)length(); // 转换为二进制,获取公钥长度
好像是,这个你可以将公钥私钥放到一个MAP中 在这个MAP中初始化随即产生器然后生成密钥对 我也刚接触 还没看懂 //生成密钥
public static Map<String,Object> initKey(String seed) throws Exception{
KeyPairGenerator keygen = KeyPairGeneratorgetInstance(ALGORITHM);
//初始化随机产生器
SecureRandom sr = new SecureRandom();
srsetSeed(seedgetBytes());
keygeninitialize(KEY_SIZE,sr);
KeyPair keys = keygengenKeyPair();
DSAPublicKey publicKey = (DSAPublicKey) keysgetPublic();
DSAPrivateKey privateKey = (DSAPrivateKey) keysgetPrivate();
Map<String,Object> map = new HashMap<String,Object>(2);
mapput(PUBLIC_KEY, publicKey);
mapput(PRIVATE_KEY, privateKey);
return map;
}
import javasecurityKeyPair;
import javasecurityKeyPairGenerator;
import javasecurityPrivateKey;
import javasecurityPublicKey;
import javasecuritySecureRandom;
import javaxcryptoCipher;
public class RSACrypto
{
private final static String RSA = "RSA";
public static PublicKey uk;
public static PrivateKey rk;
public static void generateKey() throws Exception
{
KeyPairGenerator gen = KeyPairGeneratorgetInstance(RSA);
geninitialize(512, new SecureRandom());
KeyPair keyPair = gengenerateKeyPair();
uk = keyPairgetPublic();
rk = keyPairgetPrivate();
}
private static byte[] encrypt(String text, PublicKey pubRSA) throws Exception
{
Cipher cipher = CiphergetInstance(RSA);
cipherinit(CipherENCRYPT_MODE, pubRSA);
return cipherdoFinal(textgetBytes());
}
public final static String encrypt(String text)
{
try {
return byte2hex(encrypt(text, uk));
}
catch(Exception e)
{
eprintStackTrace();
}
return null;
}
public final static String decrypt(String data)
{
try{
return new String(decrypt(hex2byte(datagetBytes())));
}
catch (Exception e)
{
eprintStackTrace();
}
return null;
}
private static byte[] decrypt(byte[] src) throws Exception
{
Cipher cipher = CiphergetInstance(RSA);
cipherinit(CipherDECRYPT_MODE, rk);
return cipherdoFinal(src);
}
public static String byte2hex(byte[] b)
{
String hs = "";
String stmp = "";
for (int n = 0; n < blength; n ++)
{
stmp = IntegertoHexString(b[n] & 0xFF);
if (stmplength() == 1)
hs += ("0" + stmp);
else
hs += stmp;
}
return hstoUpperCase();
}
public static byte[] hex2byte(byte[] b)
{
if ((blength % 2) != 0)
throw new IllegalArgumentException("长度不是偶数");
byte[] b2 = new byte[blength / 2];
for (int n = 0; n < blength; n += 2)
{
String item = new String(b, n, 2);
b2[n/2] = (byte)IntegerparseInt(item, 16);
}
return b2;
}
//just for test
public static void main(String args[])
{
try
{
RSACryptogenerateKey();
String cipherText = RSACryptoencrypt("asdfghjh");
Systemoutprintln(cipherText);
String plainText = RSACryptodecrypt(cipherText);
Systemoutprintln(plainText);
}
catch(Exception e)
{
eprintStackTrace();
}
}
}
服务端生成公钥与私钥,保存。
客户端在请求到登录页面后,随机生成一字符串。
后此随机字符串作为密钥加密密码,再用从服务端获取到的公钥加密生成的随机字符串
将此两段密文传入服务端,服务端用私钥解出随机字符串,再用此私钥解出加密的密文。这其中有一个关键是解决服务端的公钥,传入客户端,客户端用此公钥加密字符串后,后又能在服务端用私钥解出。
步骤:
服务端的RSA Java实现:
/
/
package comsunsoftstrutsutil;
import javaioByteArrayOutputStream;
import javaioFileInputStream;
import javaioFileOutputStream;
import javaioObjectInputStream;
import javaioObjectOutputStream;
import javamathBigInteger;
import javasecurityKeyFactory;
import javasecurityKeyPair;
import javasecurityKeyPairGenerator;
import javasecurityNoSuchAlgorithmException;
import javasecurityPrivateKey;
import javasecurityPublicKey;
import javasecuritySecureRandom;
import javasecurityinterfacesRSAPrivateKey;
import javasecurityinterfacesRSAPublicKey;
import javasecurityspecInvalidKeySpecException;
import javasecurityspecRSAPrivateKeySpec;
import javasecurityspecRSAPublicKeySpec;
import javaxcryptoCipher;
/
RSA 工具类。提供加密,解密,生成密钥对等方法。
需要到
下载bcprov-jdk14-123jar。
/
public class RSAUtil {
/
生成密钥对
@return KeyPair
@throws EncryptException
/
public static KeyPair generateKeyPair() throws Exception {
try {
KeyPairGenerator keyPairGen = KeyPairGeneratorgetInstance("RSA",
new orgbouncycastlejceproviderBouncyCastleProvider());
final int KEY_SIZE = 1024;// 没什么好说的了,这个值关系到块加密的大小,可以更改,但是不要太大,否则效率会低
keyPairGeninitialize(KEY_SIZE, new SecureRandom());
KeyPair keyPair = keyPairGengenerateKeyPair();
saveKeyPair(keyPair);
return keyPair;
} catch (Exception e) {
throw new Exception(egetMessage());
}
}
public static KeyPair getKeyPair()throws Exception{
FileInputStream fis = new FileInputStream("C:/RSAKeytxt");
ObjectInputStream oos = new ObjectInputStream(fis);
KeyPair kp= (KeyPair) oosreadObject();
oosclose();
fisclose();
return kp;
}
public static void saveKeyPair(KeyPair kp)throws Exception{
FileOutputStream fos = new FileOutputStream("C:/RSAKeytxt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
//生成密钥
ooswriteObject(kp);
oosclose();
fosclose();
}
/
生成公钥
@param modulus
@param publicExponent
@return RSAPublicKey
@throws Exception
/
public static RSAPublicKey generateRSAPublicKey(byte[] modulus,
byte[] publicExponent) throws Exception {
KeyFactory keyFac = null;
try {
keyFac = KeyFactorygetInstance("RSA",
new orgbouncycastlejceproviderBouncyCastleProvider());
} catch (NoSuchAlgorithmException ex) {
throw new Exception(exgetMessage());
}
RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(
modulus), new BigInteger(publicExponent));
try {
return (RSAPublicKey) keyFacgeneratePublic(pubKeySpec);
} catch (InvalidKeySpecException ex) {
throw new Exception(exgetMessage());
}
}
/
生成私钥
@param modulus
@param privateExponent
@return RSAPrivateKey
@throws Exception
/
public static RSAPrivateKey generateRSAPrivateKey(byte[] modulus,
byte[] privateExponent) throws Exception {
KeyFactory keyFac = null;
try {
keyFac = KeyFactorygetInstance("RSA",
new orgbouncycastlejceproviderBouncyCastleProvider());
} catch (NoSuchAlgorithmException ex) {
throw new Exception(exgetMessage());
}
RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(new BigInteger(
modulus), new BigInteger(privateExponent));
try {
return (RSAPrivateKey) keyFacgeneratePrivate(priKeySpec);
} catch (InvalidKeySpecException ex) {
throw new Exception(exgetMessage());
}
}
/
加密
@param key
加密的密钥
@param data
待加密的明文数据
@return 加密后的数据
@throws Exception
/
public static byte[] encrypt(PublicKey pk, byte[] data) throws Exception {
try {
Cipher cipher = CiphergetInstance("RSA",
new orgbouncycastlejceproviderBouncyCastleProvider());
cipherinit(CipherENCRYPT_MODE, pk);
int blockSize = ciphergetBlockSize();// 获得加密块大小,如:加密前数据为128个byte,而key_size=1024
// 加密块大小为127
// byte,加密后为128个byte;因此共有2个加密块,第一个127
// byte第二个为1个byte
int outputSize = ciphergetOutputSize(datalength);// 获得加密块加密后块大小
int leavedSize = datalength % blockSize;
int blocksSize = leavedSize != 0 datalength / blockSize + 1
: datalength / blockSize;
byte[] raw = new byte[outputSize blocksSize];
int i = 0;
while (datalength - i blockSize > 0) {
if (datalength - i blockSize > blockSize)
cipherdoFinal(data, i blockSize, blockSize, raw, i
outputSize);
else
cipherdoFinal(data, i blockSize, datalength - i
blockSize, raw, i outputSize);
// 这里面doUpdate方法不可用,查看源代码后发现每次doUpdate后并没有什么实际动作除了把byte[]放到
// ByteArrayOutputStream中,而最后doFinal的时候才将所有的byte[]进行加密,可是到了此时加密块大小很可能已经超出了
// OutputSize所以只好用dofinal方法。
i++;
}
return raw;
} catch (Exception e) {
throw new Exception(egetMessage());
}
}
/
解密
@param key
解密的密钥
@param raw
已经加密的数据
@return 解密后的明文
@throws Exception
/
public static byte[] decrypt(PrivateKey pk, byte[] raw) throws Exception {
try {
Cipher cipher = CiphergetInstance("RSA",
new orgbouncycastlejceproviderBouncyCastleProvider());
cipherinit(cipherDECRYPT_MODE, pk);
int blockSize = ciphergetBlockSize();
ByteArrayOutputStream bout = new ByteArrayOutputStream(64);
int j = 0;
while (rawlength - j blockSize > 0) {
boutwrite(cipherdoFinal(raw, j blockSize, blockSize));
j++;
}
return bouttoByteArray();
} catch (Exception e) {
throw new Exception(egetMessage());
}
}
/
@param args
@throws Exception
/
public static void main(String[] args) throws Exception {
RSAPublicKey rsap = (RSAPublicKey) RSAUtilgenerateKeyPair()getPublic();
String test = "hello world";
byte[] en_test = encrypt(getKeyPair()getPublic(),testgetBytes());
byte[] de_test = decrypt(getKeyPair()getPrivate(),en_test);
Systemoutprintln(new String(de_test));
}
}
测试页面IndexActionjava:
/Generated by MyEclipse Struts
Template path: templates/java/JavaClassvtl
/
package comsunsoftstrutsaction;
import javasecurityinterfacesRSAPrivateKey;
import javasecurityinterfacesRSAPublicKey;
import javaxservlet>}
通过此action进入登录页面,并传入公钥的 Modulus 与PublicExponent的hex编码形式。
在AE中这叫点选查询,其中你可以用你自己的坐标来替换 下面的
IMap pMap = axMapControl1Map;
IActiveView pActiveView = pMap as IActiveView;
IFeatureLayer pFeatureLayer = pMapget_Layer(0) as IFeatureLayer;
IFeatureClass pFeatureClass = pFeatureLayerFeatureClass;
//设置点击点的位置
IPoint point = pActiveViewScreenDisplayDisplayTransformationToMapPoint(ex, ey);
ITopologicalOperator pTOpo = point as ITopologicalOperator;
double length;
length = ConvertPixelsToMapUnits(pActiveView, 4);
IGeometry pBuffer = pTOpoBuffer(length);
IGeometry pGeomentry = pBufferEnvelope;
//空间滤过器
ISpatialFilter pSpatialFilter = new SpatialFilter();
pSpatialFilterGeometry = pGeomentry;
//根据被选择要素的不同,设置不同的空间滤过关系
switch (pFeatureClassShapeType)
{
case esriGeometryTypeesriGeometryPoint:
pSpatialFilterSpatialRel = esriSpatialRelEnumesriSpatialRelContains;
break;
case esriGeometryTypeesriGeometryPolyline:
pSpatialFilterSpatialRel = esriSpatialRelEnumesriSpatialRelCrosses;
break;
case esriGeometryTypeesriGeometryPolygon:
pSpatialFilterSpatialRel = esriSpatialRelEnumesriSpatialRelIntersects;
break;
}
IFeatureSelection pFSelection = pFeatureLayer as IFeatureSelection;
pFSelectionSelectFeatures(pSpatialFilter, esriSelectionResultEnumesriSelectionResultNew, false);
ISelectionSet pSelectionset = pFSelectionSelectionSet;
ICursor pCursor;
pSelectionsetSearch(null, true, out pCursor);
IFeatureCursor pFeatCursor = pCursor as IFeatureCursor;
IFeature pFeature = pFeatCursorNextFeature();
while (pFeature != null)
{
pMapSelectFeature(pFeatureLayer, pFeature);
pFeature = pFeatCursorNextFeature();
pFetureget_value("");//在这里你可以写上想要获取的属性的字段
}
pActiveViewPartialRefresh(esriViewDrawPhaseesriViewGraphicSelection, null, null);
上述的自定义函数是将距离的转换
private double ConvertPixelsToMapUnits(IActiveView pActiveView, double pixelUnits)
{
// Uses the ratio of the size of the map in pixels to map units to do the conversion
IPoint p1 = pActiveViewScreenDisplayDisplayTransformationVisibleBoundsUpperLeft;
IPoint p2 = pActiveViewScreenDisplayDisplayTransformationVisibleBoundsUpperRight;
int x1, x2, y1, y2;
pActiveViewScreenDisplayDisplayTransformationFromMapPoint(p1, out x1, out y1);
pActiveViewScreenDisplayDisplayTransformationFromMapPoint(p2, out x2, out y2);
double pixelExtent = x2 - x1;
double realWorldDisplayExtent = pActiveViewScreenDisplayDisplayTransformationVisibleBoundsWidth;
double sizeOfOnePixel = realWorldDisplayExtent / pixelExtent;
return pixelUnits sizeOfOnePixel;
}
以上就是关于java中如何得到公钥的key size全部的内容,包括:java中如何得到公钥的key size、java 如果随机生成秘钥对并获取、请教RSA和AES加密的算法,JAVA,C#,C++可以做交互通用组件!等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)