问题如标题,我试过了,能得到加密的内容,但是每次都不一样,我看到public key的algorithm是RSA,所以我觉得每次不一样是正常的。但是我调用对方API,一直过不去。所以请高手帮我看看代码,有什么问题!或者给我一个标准的方法。
public class EncryptPasswordUtil {
private static LogService log = LogService
.getInstance(EncryptPasswordUtil.class);
private static final String ENCRPTY_FILE_NAME = "test.cer";
public static String generateTCSRSAPassword(String password) {
PublicKey tcsPublicKey = null;
try {
tcsPublicKey = getPublicKeyFromX509(ENCRPTY_FILE_NAME);
if (tcsPublicKey != null) {
log.debug("Load the file: " + ENCRPTY_FILE_NAME);
Cipher tcsCipher = Cipher.getInstance(tcsPublicKey
.getAlgorithm());
tcsCipher.init(Cipher.ENCRYPT_MODE, tcsPublicKey);
String tcsEncryptPassword = Base64.encodeBase64String(tcsCipher
.doFinal(Base64.encodeBase64(password.getBytes())));
return tcsEncryptPassword;
} else {
log.warn(ENCRPTY_FILE_NAME + " cannot be found!");
throw new Exception(ENCRPTY_FILE_NAME
+ " cannot be found!");
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static PublicKey getPublicKeyFromX509(String filename)
throws Exception {
InputStream fin = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(ENCRPTY_FILE_NAME);
CertificateFactory f = CertificateFactory.getInstance("X.509");
X509Certificate certificate = (X509Certificate) f
.generateCertificate(fin);
PublicKey pk = certificate.getPublicKey();
return pk;
}
}
java 加密
------解决方案--------------------
给你个例子吧,我自己封装的
package com.gus.encipherment;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import org.apache.commons.codec.binary.Hex;
/**
* 数字证书应用
* @author gus
* @since 2011/02/29
*/
public class DC {
/**
* 由密钥库获得私钥
* @param keyStorePath 密钥库路径
* @param passwd
* @param alias
* @return 16进制封装的私钥
* @throws KeyStoreException
* @throws IOException
* @throws CertificateException
* @throws NoSuchAlgorithmException
* @throws UnrecoverableKeyException