下面列出了java.security.spec.ECGenParameterSpec#java.security.spec.X509EncodedKeySpec 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 加密<br>
* 用公钥加密 encryptByPublicKey
*
* @param data 裸的原始数据
* @param key 经过base64加密的公钥
* @return 结果也采用base64加密
* @throws Exception
*/
public static String encryptRSA(String data, String key) {
try {
// 对公钥解密,公钥被base64加密过
byte[] keyBytes = decryptBASE64(key);
// 取得公钥
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_RSA);
Key publicKey = keyFactory.generatePublic(x509KeySpec);
// 对数据加密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return encryptBASE64(cipher.doFinal(data.getBytes(ENCODING)));
} catch (Exception e) {
throw DataXException.asDataXException(
FrameworkErrorCode.SECRET_ERROR, "rsa加密出错", e);
}
}
public static RSAPublicKey decodeRSAPublicKey(String key) throws RSAException {
if (key == null) {
throw ExceptionFactory.createException(RSAException.class, "Key parameter is null");
}
int offset = key.indexOf("\n") + 1;
int len = key.indexOf("-----END PUBLIC KEY-----") - offset;
// TODO: use standard decoders with Java 6+
byte[] certificateData = Base64Decoder.decode(key.getBytes(), offset, len);
X509EncodedKeySpec spec = new X509EncodedKeySpec(certificateData);
try {
KeyFactory kf = KeyFactory.getInstance("RSA");
return (RSAPublicKey) kf.generatePublic(spec);
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
throw ExceptionFactory.createException(RSAException.class, "Unable to decode public key", e);
}
}
public ElexisEnvironmentLoginDialog(Shell shell, String openidClientSecret, String keycloakUrl,
String realmPublicKey){
super(shell);
logger = LoggerFactory.getLogger(getClass());
oauthService = new ServiceBuilder(ElexisEnvironmentLoginContributor.OAUTH2_CLIENT_ID)
.apiSecret(openidClientSecret).defaultScope("openid").callback(CALLBACK_URL)
.build(KeycloakApi.instance(keycloakUrl, ElexisEnvironmentLoginContributor.REALM_ID));
KeyFactory kf;
try {
kf = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpecX509 =
new X509EncodedKeySpec(Base64.getDecoder().decode(realmPublicKey));
RSAPublicKey publicKey = (RSAPublicKey) kf.generatePublic(keySpecX509);
jwtParser = Jwts.parserBuilder().setSigningKey(publicKey).build();
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
logger.error("Initialization error", e);
}
}
private static PublicKey loadPublicKey() throws NoSuchAlgorithmException, InvalidKeySpecException, IOException {
String publicKeyPEM = FileUtils.readFileToString(new File(TransactionConstants.PUBLIC_KEY),
StandardCharsets.UTF_8);
// strip of header, footer, newlines, whitespaces.
publicKeyPEM = publicKeyPEM
.replace("-----BEGIN PUBLIC KEY-----", "")
.replace("-----END PUBLIC KEY-----", "")
.replaceAll("\\s", "");
// decode to get the binary DER representation.
byte[] publicKeyDER = Base64.getDecoder().decode(publicKeyPEM);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePublic(new X509EncodedKeySpec(publicKeyDER));
}
private void initEncodeCipher(String keyAlias, int mode) throws GeneralSecurityException {
PublicKey key = mKeyStore.getCertificate(keyAlias).getPublicKey();
// workaround for using public key
// from https://developer.android.com/reference/android/security/keystore/KeyGenParameterSpec.html#known-issues
PublicKey unrestricted = KeyFactory.getInstance(key.getAlgorithm())
.generatePublic(new X509EncodedKeySpec(key.getEncoded()));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// from https://code.google.com/p/android/issues/detail?id=197719
OAEPParameterSpec spec = new OAEPParameterSpec("SHA-256", "MGF1",
MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT);
mCipher.init(mode, unrestricted, spec);
} else {
mCipher.init(mode, unrestricted);
}
}
/**
* Generate a local key pair. Be careful. If there is already an key pair,
* it will override it
*
* @param sessionID
* the sessionID that is identified with the local machine
*/
public void generateLocalKeyPair(SessionID sessionID) {
if (sessionID == null)
return;
String accountID = sessionID.getAccountID();
KeyPair keyPair;
try {
keyPair = KeyPairGenerator.getInstance("DSA").genKeyPair();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return;
}
// Store Public Key.
PublicKey pubKey = keyPair.getPublic();
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(pubKey.getEncoded());
this.store.setProperty(accountID + ".publicKey", x509EncodedKeySpec.getEncoded());
// Store Private Key.
PrivateKey privKey = keyPair.getPrivate();
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privKey.getEncoded());
this.store.setProperty(accountID + ".privateKey", pkcs8EncodedKeySpec.getEncoded());
}
private void initEncodeCipher(Cipher cipher, String alias, KeyStore keyStore)
throws PFSecurityException {
try {
final PublicKey key = keyStore.getCertificate(alias).getPublicKey();
final PublicKey unrestricted = KeyFactory.getInstance(key.getAlgorithm()).generatePublic(
new X509EncodedKeySpec(key.getEncoded()));
final OAEPParameterSpec spec = new OAEPParameterSpec("SHA-256", "MGF1",
MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT);
cipher.init(Cipher.ENCRYPT_MODE, unrestricted, spec);
} catch (KeyStoreException | InvalidKeySpecException |
NoSuchAlgorithmException | InvalidKeyException |
InvalidAlgorithmParameterException e) {
throw new PFSecurityException(
"Can not initialize Encode Cipher:" + e.getMessage(),
PFSecurityUtilsErrorCodes.ERROR_INIT_ENDECODE_CIPHER
);
}
}
private static PublicKey getPublicKey(Context context) throws Throwable {
// Read public key
String sPublicKey = "";
InputStreamReader isr = new InputStreamReader(context.getAssets().open("XPrivacy_public_key.txt"), "UTF-8");
BufferedReader br = new BufferedReader(isr);
String line = br.readLine();
while (line != null) {
if (!line.startsWith("-----"))
sPublicKey += line;
line = br.readLine();
}
br.close();
isr.close();
// Create public key
byte[] bPublicKey = Base64.decode(sPublicKey, Base64.NO_WRAP);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec encodedPubKeySpec = new X509EncodedKeySpec(bPublicKey);
return keyFactory.generatePublic(encodedPubKeySpec);
}
@Override
protected PrivateKey engineGeneratePrivate(KeySpec keySpec)
throws InvalidKeySpecException {
//The KeySpec for Private Key is PKCS8
if (keySpec instanceof PKCS8EncodedKeySpec ) {
return new IosRSAKey.IosRSAPrivateKey(((PKCS8EncodedKeySpec) keySpec).getEncoded());
}
if (keySpec instanceof X509EncodedKeySpec) {
X509EncodedKeySpec x509Spec = (X509EncodedKeySpec) keySpec;
return new IosRSAKey.IosRSAPrivateKey(x509Spec.getEncoded());
} else if (keySpec instanceof RSAPrivateKeySpec) {
return new IosRSAKey.IosRSAPrivateKey((RSAPrivateKeySpec) keySpec);
}
throw new InvalidKeySpecException(
"Must use PKCS8EncodedKeySpec, X509EncodedKeySpec or RSAPrivateKeySpec; was "
+ keySpec.getClass().getName());
}
/**
* Generates a public key object from the provided key specification
* (key material).
*
* @param keySpec the specification (key material) of the public key
*
* @return the public key
*
* @exception InvalidKeySpecException if the given key specification
* is inappropriate for this key factory to produce a public key.
*/
protected PublicKey engineGeneratePublic(KeySpec keySpec)
throws InvalidKeySpecException
{
try {
if (keySpec instanceof DHPublicKeySpec) {
DHPublicKeySpec dhPubKeySpec = (DHPublicKeySpec)keySpec;
return new DHPublicKey(dhPubKeySpec.getY(),
dhPubKeySpec.getP(),
dhPubKeySpec.getG());
} else if (keySpec instanceof X509EncodedKeySpec) {
return new DHPublicKey
(((X509EncodedKeySpec)keySpec).getEncoded());
} else {
throw new InvalidKeySpecException
("Inappropriate key specification");
}
} catch (InvalidKeyException e) {
throw new InvalidKeySpecException
("Inappropriate key specification", e);
}
}
public static String rsaEncode(String publicCertificate, String text) {
try {
byte[] publicBytes = baseStrToByte(publicCertificate);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes);
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
PublicKey pubKey = keyFactory.generatePublic(keySpec);
// get an RSA cipher object and print the provider
final Cipher cipher = Cipher.getInstance(ALGORITHM);
// encrypt the plain text using the public key
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] cipherBytes = cipher.doFinal(text.getBytes(CHAR_SET));
return baseByteToStr(cipherBytes);
} catch (Exception e) {
logger.error("publicCertificate:{} \r\n text:{}", publicCertificate, text, e);
}
return null;
}
private static PublicKey getPublicKeyFromString(String pubKey) throws AuthenticationException {
PublicKey key;
try {
//init keyfactory
KeyFactory kf = KeyFactory.getInstance(ALGORITHM);
//decode the key into a byte array
byte[] keyBytes = Base64.decode(pubKey, Base64.NO_WRAP);
//create spec
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
//generate public key
key = kf.generatePublic(spec);
} catch (InvalidKeySpecException | NoSuchAlgorithmException e) {
throw new AuthenticationException("Invalid public key: " + e.getMessage());
}
return key;
}
/**
* This specific doesn't verify in combination with its document, so
* I wanted to look at its contents. As RSASSA-PSS does not allow to
* read the original hash from the decrypted signature bytes, this
* did not help at all.
*/
@Test
public void testDecryptSLMBC_PSS_Test1() throws IOException, CMSException, GeneralSecurityException
{
Cipher cipherNoPadding = Cipher.getInstance("RSA/ECB/NoPadding");
KeyFactory rsaKeyFactory = KeyFactory.getInstance("RSA");
try ( InputStream resource = getClass().getResourceAsStream("SLMBC-PSS-Test1.cms") )
{
CMSSignedData cmsSignedData = new CMSSignedData(resource);
for (SignerInformation signerInformation : (Iterable<SignerInformation>)cmsSignedData.getSignerInfos().getSigners())
{
Collection<X509CertificateHolder> x509CertificateHolders = cmsSignedData.getCertificates().getMatches(signerInformation.getSID());
if (x509CertificateHolders.size() != 1)
{
Assert.fail("Cannot uniquely determine signer certificate.");
}
X509CertificateHolder x509CertificateHolder = x509CertificateHolders.iterator().next();
PublicKey publicKey = rsaKeyFactory.generatePublic(new X509EncodedKeySpec(x509CertificateHolder.getSubjectPublicKeyInfo().getEncoded()));
cipherNoPadding.init(Cipher.DECRYPT_MODE, publicKey);
byte[] bytes = cipherNoPadding.doFinal(signerInformation.getSignature());
Files.write(new File(RESULT_FOLDER, "SLMBC-PSS-Test1-signature-decoded").toPath(), bytes);
}
}
}
public PublicKey getPublicKey(
String provider)
throws NoSuchAlgorithmException, NoSuchProviderException,
InvalidKeyException
{
SubjectPublicKeyInfo subjectPKInfo = reqInfo.getSubjectPublicKeyInfo();
try
{
X509EncodedKeySpec xspec = new X509EncodedKeySpec(new DERBitString(subjectPKInfo).getBytes());
AlgorithmIdentifier keyAlg = subjectPKInfo.getAlgorithmId ();
return KeyFactory.getInstance(keyAlg.getObjectId().getId (), provider).generatePublic(xspec);
}
catch (InvalidKeySpecException e)
{
throw new InvalidKeyException("error encoding public key");
}
}
/**
* Generates a public key object from the provided key specification
* (key material).
*
* @param keySpec the specification (key material) of the public key
*
* @return the public key
*
* @exception InvalidKeySpecException if the given key specification
* is inappropriate for this key factory to produce a public key.
*/
protected PublicKey engineGeneratePublic(KeySpec keySpec)
throws InvalidKeySpecException
{
try {
if (keySpec instanceof DHPublicKeySpec) {
DHPublicKeySpec dhPubKeySpec = (DHPublicKeySpec)keySpec;
return new DHPublicKey(dhPubKeySpec.getY(),
dhPubKeySpec.getP(),
dhPubKeySpec.getG());
} else if (keySpec instanceof X509EncodedKeySpec) {
return new DHPublicKey
(((X509EncodedKeySpec)keySpec).getEncoded());
} else {
throw new InvalidKeySpecException
("Inappropriate key specification");
}
} catch (InvalidKeyException e) {
throw new InvalidKeySpecException
("Inappropriate key specification", e);
}
}
/**
* Generates a public key object from the provided key specification
* (key material).
*
* @param keySpec the specification (key material) of the public key
*
* @return the public key
*
* @exception InvalidKeySpecException if the given key specification
* is inappropriate for this key factory to produce a public key.
*/
protected PublicKey engineGeneratePublic(KeySpec keySpec)
throws InvalidKeySpecException {
try {
if (keySpec instanceof DSAPublicKeySpec) {
DSAPublicKeySpec dsaPubKeySpec = (DSAPublicKeySpec)keySpec;
return new DSAPublicKeyImpl(dsaPubKeySpec.getY(),
dsaPubKeySpec.getP(),
dsaPubKeySpec.getQ(),
dsaPubKeySpec.getG());
} else if (keySpec instanceof X509EncodedKeySpec) {
return new DSAPublicKeyImpl
(((X509EncodedKeySpec)keySpec).getEncoded());
} else {
throw new InvalidKeySpecException
("Inappropriate key specification");
}
} catch (InvalidKeyException e) {
throw new InvalidKeySpecException
("Inappropriate key specification: " + e.getMessage());
}
}
protected PublicKey engineGeneratePublic(
KeySpec keySpec)
throws InvalidKeySpecException
{
if (keySpec instanceof X509EncodedKeySpec)
{
try
{
return JDKKeyFactory.createPublicKeyFromDERStream(
new ByteArrayInputStream(((X509EncodedKeySpec)keySpec).getEncoded()));
}
catch (Exception e)
{
throw new InvalidKeySpecException(e.toString());
}
}
else if (keySpec instanceof ECPublicKeySpec)
{
return new JCEECPublicKey(algorithm, (ECPublicKeySpec)keySpec);
}
throw new InvalidKeySpecException("Unknown KeySpec type.");
}
@Override
protected KeyWrapper loadKey(RealmModel realm, ComponentModel model) {
String privateEcdsaKeyBase64Encoded = model.getConfig().getFirst(GeneratedEcdsaKeyProviderFactory.ECDSA_PRIVATE_KEY_KEY);
String publicEcdsaKeyBase64Encoded = model.getConfig().getFirst(GeneratedEcdsaKeyProviderFactory.ECDSA_PUBLIC_KEY_KEY);
String ecInNistRep = model.getConfig().getFirst(GeneratedEcdsaKeyProviderFactory.ECDSA_ELLIPTIC_CURVE_KEY);
try {
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(Base64.decode(privateEcdsaKeyBase64Encoded));
KeyFactory kf = KeyFactory.getInstance("EC");
PrivateKey decodedPrivateKey = kf.generatePrivate(privateKeySpec);
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(Base64.decode(publicEcdsaKeyBase64Encoded));
PublicKey decodedPublicKey = kf.generatePublic(publicKeySpec);
KeyPair keyPair = new KeyPair(decodedPublicKey, decodedPrivateKey);
return createKeyWrapper(keyPair, ecInNistRep);
} catch (Exception e) {
logger.warnf("Exception at decodeEcdsaPublicKey. %s", e.toString());
return null;
}
}
/**
* Generates a public key object from the provided key specification
* (key material).
*
* @param keySpec the specification (key material) of the public key
*
* @return the public key
*
* @exception InvalidKeySpecException if the given key specification
* is inappropriate for this key factory to produce a public key.
*/
protected PublicKey engineGeneratePublic(KeySpec keySpec)
throws InvalidKeySpecException
{
try {
if (keySpec instanceof DHPublicKeySpec) {
DHPublicKeySpec dhPubKeySpec = (DHPublicKeySpec)keySpec;
return new DHPublicKey(dhPubKeySpec.getY(),
dhPubKeySpec.getP(),
dhPubKeySpec.getG());
} else if (keySpec instanceof X509EncodedKeySpec) {
return new DHPublicKey
(((X509EncodedKeySpec)keySpec).getEncoded());
} else {
throw new InvalidKeySpecException
("Inappropriate key specification");
}
} catch (InvalidKeyException e) {
throw new InvalidKeySpecException
("Inappropriate key specification", e);
}
}
/**
* Get the public key details (value and issuer) for CSP API
*/
private void populatePublicKeyDetails() {
final PublicKeyResponse response = restTemplate.getForObject(config.getCspAuthUrl(), PublicKeyResponse.class);
publicKeyIssuer = response.getIssuer();
final String rawPublicKey = response.getValue();
String pem = rawPublicKey.replaceAll("-----BEGIN (.*)-----", "")
.replaceAll("-----END (.*)----", "")
.replaceAll("\n", "");
try {
publicKey = KeyFactory.getInstance(KEYS_ALGORITHM)
.generatePublic(new X509EncodedKeySpec(Base64.getDecoder()
.decode(pem)));
} catch (Exception e) {
LOGGER.error("Failed to generate public key");
}
}
/**
* ECDSA公钥签名校验
*
* @param info 待签名字符串
* @param sign 签名值
* @param publicKeyStr 公钥字符串内容
* @param encode 编码
* @return 校验结果
*/
public boolean verifyByStr(String info, String sign, String publicKeyStr, @Nullable String encode) {
try {
KeyFactory keyFactory = KeyFactory.getInstance("EC");
PublicKey publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(Base64.decodeBase64(publicKeyStr)));
Signature signature = Signature.getInstance(SIGN_ALGORITHMS);
signature.initVerify(publicKey);
if (encode == null) {
signature.update(info.getBytes());
} else {
signature.update(info.getBytes(encode));
}
return signature.verify(Base64.decodeBase64(sign));
} catch (NoSuchAlgorithmException | InvalidKeySpecException | InvalidKeyException | SignatureException | UnsupportedEncodingException e) {
e.printStackTrace();
}
return false;
}
private PublicKey initializePublicKey(String data) {
try {
data = StringUtils.remove(data, "-----BEGIN PUBLIC KEY-----");
data = StringUtils.remove(data, "-----END PUBLIC KEY-----");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.decodeBase64(data));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePublic(keySpec);
}
catch (Exception e) {
throw new IllegalArgumentException("Invalid public key: ", e);
}
}
public static String getObjectToSign(String ApplicationParam, String ChallengeParam, String kh, String PublicKey) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException {
byte[] constant = {(byte) 0x00};
int constantL = constant.length;
byte[] Challenge = Base64.decodeBase64(ChallengeParam);
int ChanllengeL = Challenge.length;
byte[] Application = Base64.decodeBase64(ApplicationParam);
int ApplicationL = Application.length;
byte[] keyHandle = Base64.decodeBase64(kh);
int keyHandleL = keyHandle.length;
byte[] publicKey = Base64.decodeBase64(PublicKey);
int publicKeyL = publicKey.length;
/////////
//Convert back to publicKey
KeyFactory kf = KeyFactory.getInstance("ECDSA", "BCFIPS");
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(publicKey);
PublicKey pub = kf.generatePublic(pubKeySpec);
int pukL = CSConstants.EC_P256_PUBLICKKEYSIZE;
//Create byte[] Object to sign
byte[] ob2Sign = new byte[constantL + ChanllengeL + ApplicationL + keyHandleL + pukL];
//copy constant
int tot = 0;
System.arraycopy(constant, 0, ob2Sign, tot, constantL);
tot += constantL;
System.arraycopy(Application, 0, ob2Sign, tot, ApplicationL);
tot += ApplicationL;
System.arraycopy(Challenge, 0, ob2Sign, tot, ChanllengeL);
tot += ChanllengeL;
System.arraycopy(keyHandle, 0, ob2Sign, tot, keyHandleL);
tot += keyHandleL;
System.arraycopy(publicKey, 0, ob2Sign, tot, pukL);
tot += pukL;
return Base64.encodeBase64String(ob2Sign);
}
public void bad8a() throws Exception {
new DESKeySpec(null); // should not be reported
byte[] key = {1, 2, 3, 4, 5, 6, 7, 8};
DESKeySpec spec = new DESKeySpec(key);
KeySpec spec2 = new DESedeKeySpec(key);
KerberosKey kerberosKey = new KerberosKey(null, key, 0, 0);
System.out.println(spec.getKey()[0] + kerberosKey.getKeyType());
new SecretKeySpec(key, "alg");
new SecretKeySpec(key, 0, 0, "alg");
new X509EncodedKeySpec(key);
new PKCS8EncodedKeySpec(key);
new KeyRep(null, "alg", "format", key);
new KerberosTicket(null, null, null, key, 0, null, null, null, null, null, null);
new DSAPublicKeyImpl(key);
}
/** Returns key spec by key format and encoded data. */
private EncodedKeySpec getKeySpec(SignatureKey key) {
switch (key.getFormat()) {
case PKCS_8:
return new PKCS8EncodedKeySpec(key.getEncoded());
case X_509:
return new X509EncodedKeySpec(key.getEncoded());
default:
throw new IllegalArgumentException(
String.format("Unsupported key spec '%s' for signature keys", key.getFormat()));
}
}
public static byte[] encrypt(byte[] srcBytes) throws Exception {
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
KeyFactory kf = KeyFactory.getInstance(algorithm);
PublicKey keyPublic = kf.generatePublic(keySpec);
Cipher cipher;
cipher = Cipher.getInstance(algorithm,
new org.bouncycastle.jce.provider.BouncyCastleProvider());
cipher.init(Cipher.ENCRYPT_MODE, keyPublic);
int blockSize = cipher.getBlockSize();
int outputSize = cipher.getOutputSize(srcBytes.length);
int leavedSize = srcBytes.length % blockSize;
int blocksSize = leavedSize != 0 ? srcBytes.length / blockSize + 1
: srcBytes.length / blockSize;
byte[] raw = new byte[outputSize * blocksSize];
int i = 0;
while (srcBytes.length - i * blockSize > 0) {
if (srcBytes.length - i * blockSize > blockSize)
cipher.doFinal(srcBytes, i * blockSize, blockSize, raw, i
* outputSize);
else
cipher.doFinal(srcBytes, i * blockSize, srcBytes.length - i
* blockSize, raw, i * outputSize);
i++;
}
return raw;
}
private static void testPublic(KeyFactory kf, PublicKey key) throws Exception {
System.out.println("Testing public key...");
PublicKey key2 = (PublicKey)kf.translateKey(key);
KeySpec keySpec = kf.getKeySpec(key, ECPublicKeySpec.class);
PublicKey key3 = kf.generatePublic(keySpec);
KeySpec x509Spec = kf.getKeySpec(key, X509EncodedKeySpec.class);
PublicKey key4 = kf.generatePublic(x509Spec);
KeySpec x509Spec2 = new X509EncodedKeySpec(key.getEncoded());
PublicKey key5 = kf.generatePublic(x509Spec2);
testKey(key, key);
testKey(key, key2);
testKey(key, key3);
testKey(key, key4);
testKey(key, key5);
}
private static PublicKey getPublicKey() {
try {
return KeyFactory.getInstance("DSA")
.generatePublic(new X509EncodedKeySpec(JoH.hexStringToByteArray(OTA_FILE_SIGNING_PUBLIC_KEY)));
} catch (Exception e) {
UserError.Log.e(TAG, "Failed to get public key: " + e);
return null;
}
}
private PublicKey getPublicKeyFromString(String key)
throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException {
KeyFactory keyFactory = KeyFactory.getInstance("EC", "BC");
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(key));
PublicKey publicKey = keyFactory.generatePublic(pubKeySpec);
return publicKey;
}
/**
* Create PublicKey from a .DER file
*/
public static PublicKey getX509PublicKey(byte[] buf)
throws InvalidKeySpecException {
X509EncodedKeySpec spec = new X509EncodedKeySpec(buf);
try {
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(spec);
} catch (NoSuchAlgorithmException e) {
throw new AssertionError("JVM spec is required to support RSA", e);
}
}