java.security.spec.EncodedKeySpec Java Examples

The following examples show how to use java.security.spec.EncodedKeySpec. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BCDHSuite.java    From zrtp-java with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public byte[] getDhResult(byte[] aMsg, int offset , boolean isLegacyClient) throws ZrtpException {
	try {
		int PV_LENGTH = keyType.pvLengthInWords * 4;
		byte[] encodedKey = new byte[keyType.pvLengthInWords * 4 + 1];
		encodedKey[0] = 4;
		System.arraycopy(aMsg, offset, encodedKey, 1, encodedKey.length - 1);
		EncodedKeySpec keySpec = getSpec(encodedKey, keyPair.getPublic());
		PublicKey pub = keyFactory.generatePublic(keySpec);
		KeyAgreement agreement = KeyAgreement.getInstance(algorithm, "ZBC");
		agreement.init(keyPair.getPrivate());
		agreement.doPhase(pub, true);
		byte[] secret = agreement.generateSecret();
		byte[] iDHResult = null;
		if(!isLegacyClient) {
		    iDHResult = new byte[secret.length];
		    System.arraycopy(secret, 0, iDHResult, 0, secret.length);    
		} else {
		    iDHResult = new byte[PV_LENGTH];
            System.arraycopy(secret, 0, iDHResult, iDHResult.length - secret.length, secret.length);    
		}
		return iDHResult;
	} catch (Exception e) {
		throw new ZrtpException(e);
	}
}
 
Example #2
Source File: DefaultSignatureValidatorTest.java    From pay-me with Apache License 2.0 6 votes vote down vote up
@Test public void shouldValidateTheSHA1WithRSASignature() throws Exception {
    // create a public/private key pair
    KeyFactory keyFactory   = KeyFactory.getInstance("RSA");
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    KeyPair pair = keyGen.generateKeyPair();
    EncodedKeySpec encoded = new X509EncodedKeySpec(pair.getPublic().getEncoded());
    PublicKey encodedPublic = keyFactory.generatePublic(encoded);
    String encodePublicBase64 = Base64.encodeToString(encodedPublic.getEncoded(), Base64.DEFAULT);

    // and sign some data with it
    Signature sig = Signature.getInstance("SHA1WithRSA");
    sig.initSign(pair.getPrivate());
    String data = "some sample data";
    sig.update(data.getBytes());

    String signature = Base64.encodeToString(sig.sign(), Base64.DEFAULT);

    SignatureValidator validator = new DefaultSignatureValidator(encodePublicBase64);
    assertThat(validator.validate(data, signature)).isTrue();
    assertThat(validator.validate(data+"extraData", signature)).isFalse();
}
 
Example #3
Source File: EncodedKeySpecTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that internal state of the object can not be modified using
 * returned value of <code>getEncoded()</code> method
 */
public final void testIsStatePreserved2() {

    byte[] encodedKey = new byte[] { (byte) 1, (byte) 2, (byte) 3, (byte) 4 };
    EncodedKeySpec meks = new MyEncodedKeySpec(encodedKey);

    /* Get encoded key */
    byte[] ek = meks.getEncoded();
    /* Modify returned value */
    ek[3] = (byte) 5;
    /* Get encoded key again */
    byte[] ek1 = meks.getEncoded();

    /* Check that byte value has not been changed */
    assertTrue(ek1[3] == (byte) 4);
}
 
Example #4
Source File: EncodedKeySpecTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that internal state of the object can not be modified by modifying
 * initial array value
 */
public final void testIsStatePreserved1() {
    /* Create initial byte array */
    byte[] encodedKey = new byte[] { (byte) 1, (byte) 2, (byte) 3, (byte) 4 };

    EncodedKeySpec meks = new MyEncodedKeySpec(encodedKey);

    /* Modify initial array's value */
    encodedKey[3] = (byte) 5;

    /* Get encoded key */
    byte[] ek = meks.getEncoded();

    /* Check that byte value has not been changed */
    assertTrue(ek[3] == (byte) 4);
}
 
Example #5
Source File: EncodedKeySpecTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that <code>getEncoded()</code> method returns valid byte array
 */
public final void testGetEncoded() {

    byte[] encodedKey = new byte[] { (byte) 1, (byte) 2, (byte) 3, (byte) 4 };
    EncodedKeySpec meks = new MyEncodedKeySpec(encodedKey);

    /* Get encoded key */
    byte[] ek = meks.getEncoded();

    /* Check returned array */
    boolean result = true;
    for (int i = 0; i < encodedKey.length; i++) {
        if (encodedKey[i] != ek[i]) {
            /* indicate failure */
            result = false;
        }
    }
    /* passed */
    assertTrue(result);
}
 
Example #6
Source File: EncodedKeySpecTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Tests for constructor <code>EncodedKeySpec(byte[])</code><br>
 */
public final void testEncodedKeySpec() {
    byte[] encodedKey = new byte[] { (byte) 1, (byte) 2, (byte) 3, (byte) 4 };
    EncodedKeySpec eks = new MyEncodedKeySpec(encodedKey);

    assertTrue("wrong encoded key was returned", Arrays.equals(encodedKey,
            eks.getEncoded()));
    assertEquals("wrong name of encoding format", "My", eks.getFormat());

    encodedKey = null;
    try {
        eks = new MyEncodedKeySpec(encodedKey);
        fail("expected NullPointerException");
    } catch (NullPointerException e) {
        //
    }
}
 
Example #7
Source File: EncryptionUtil.java    From Geyser with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T extends Key> T getKeyFromFile(Path fileLocation, Class<T> keyType) throws
        IOException, InvalidKeySpecException, NoSuchAlgorithmException {
    boolean isPublicKey = keyType == PublicKey.class;
    if (!isPublicKey && keyType != PrivateKey.class) {
        throw new RuntimeException("I can only read public and private keys!");
    }

    byte[] key = Files.readAllBytes(fileLocation);

    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    EncodedKeySpec keySpec = isPublicKey ? new X509EncodedKeySpec(key) : new PKCS8EncodedKeySpec(key);
    return (T) (isPublicKey ?
            keyFactory.generatePublic(keySpec) :
            keyFactory.generatePrivate(keySpec)
    );
}
 
Example #8
Source File: CryptUtils.java    From http4e with Apache License 2.0 6 votes vote down vote up
/**
 * Method convertes the bytes arrays back to private and public key objects
 */
public static Key[] bytesToPrivatePublicKeys( String algorithm, byte[] privKeyBytes, byte[] pubKeyBytes) throws Exception{
   PrivateKey privKey = null;
   PublicKey pubKey = null;
   KeyFactory keyFactory = KeyFactory.getInstance(algorithm);

   if (privKeyBytes != null) {
      EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privKeyBytes);
      privKey = keyFactory.generatePrivate(privateKeySpec);
   }

   if (pubKeyBytes != null) {
      EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pubKeyBytes);
      pubKey = keyFactory.generatePublic(publicKeySpec);
   }

   return new Key[] { privKey, pubKey };
}
 
Example #9
Source File: Rsa.java    From BigApp_Discuz_Android with Apache License 2.0 5 votes vote down vote up
/**
 * Generates Public Key from BASE64 encoded string
 * 
 * @param key
 *            BASE64 encoded string which represents the key
 * @return The PublicKey
 * @throws java.lang.Exception
 */
public static PublicKey getPublicKeyFromBase64String(String base64PublicKey) {
    try {
        KeyFactory keyFactory = KeyFactory.getInstance("Rsa");

        EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(Base64.decode(base64PublicKey));
        PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
        return publicKey;
    } catch (Exception ex) {
        Log.e(LOGTAG,ex.getMessage());
        return null;
    }
}
 
Example #10
Source File: BCDHSuite.java    From zrtp-java with GNU Affero General Public License v3.0 5 votes vote down vote up
private EncodedKeySpec getSpec(byte[] encodedKey, PublicKey pub)
		throws IOException, InvalidKeySpecException,
		NoSuchAlgorithmException {
	byte[] encc = pub.getEncoded();
	ASN1InputStream ap = new ASN1InputStream(encc);
	DERSequence der = (DERSequence) ap.readObject();
	DERSequence s1 = (DERSequence) der.getObjectAt(0);

	DERBitString bit = new DERBitString(encodedKey);
	DERSequence s2 = new DERSequence(new DERObject[] { s1, bit });
	byte[] enc = s2.getEncoded();
	X509EncodedKeySpec keySpec = new X509EncodedKeySpec(enc);
	ap.close();
	return keySpec;
}
 
Example #11
Source File: SignatureKeyManager.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
/** 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()));
  }
}
 
Example #12
Source File: ECDSAKeyLoader.java    From library with Apache License 2.0 5 votes vote down vote up
private PrivateKey getPrivateKeyFromString(String key)
		throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException {

	KeyFactory keyFactory = KeyFactory.getInstance("EC", "BC");
	EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(key));
	privateKey = keyFactory.generatePrivate(privateKeySpec);
	return privateKey;
}
 
Example #13
Source File: SunECKeyLoader.java    From library with Apache License 2.0 5 votes vote down vote up
private PrivateKey getPrivateKeyFromString(String key)
		throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException {

	KeyFactory keyFactory = KeyFactory.getInstance("EC", "SunEC");
	EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(key));
	privateKey = keyFactory.generatePrivate(privateKeySpec);
	return privateKey;
}
 
Example #14
Source File: TestCrypt.java    From http4e with Apache License 2.0 5 votes vote down vote up
private static void testPublicPrivateKeys(){
   try {
      String keyAlgorithm = "RSA";
      Key[] keys = CryptUtils.generatePrivatePublicKeys(keyAlgorithm, 1024);
      Key kPriv = keys[0];
      Key kPub = keys[1];
      byte[] kPubBytes = kPub.getEncoded();
      byte[] kPrivBytes = kPriv.getEncoded();
      System.out.println("--------------PublicKey----------------");
      System.out.println(kPub);
      System.out.println(kPub.getAlgorithm());
      System.out.println(kPub.getEncoded());
      System.out.println("--------------PrivateKey----------------");
      System.out.println(kPriv);
      System.out.println(kPriv.getAlgorithm());
      System.out.println(kPriv.getEncoded());

      // The bytes can be converted back to public and private key objects
      KeyFactory keyFactory = KeyFactory.getInstance(keyAlgorithm);
      EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(kPrivBytes);
      PrivateKey privateKey2 = keyFactory.generatePrivate(privateKeySpec);

      EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(kPubBytes);
      PublicKey publicKey2 = keyFactory.generatePublic(publicKeySpec);

      // The original and new keys are the same
      System.out.println("  Are both private keys equal? " + kPriv.equals(privateKey2));

      System.out.println("  Are both public keys equal? " + kPub.equals(publicKey2));
   } catch (Exception e) {
      e.printStackTrace();
   }
}
 
Example #15
Source File: RSA.java    From kisso with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a public key constructed from the given DER bytes.
 */
public static PublicKey publicKeyFrom(final byte[] derBytes) throws InvalidKeySpecException {
    try {
        final KeyFactory keyFactory = KeyFactory.getInstance(SSOConstants.RSA);
        final EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(derBytes);
        return keyFactory.generatePublic(publicKeySpec);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(e);
    }
}
 
Example #16
Source File: AdbCrypto.java    From AppOpsX with MIT License 5 votes vote down vote up
/**
 * Creates a new AdbCrypto object from a key pair loaded from files.
 * @param base64 Implementation of base 64 conversion interface required by ADB 
 * @param privateKey File containing the RSA private key
 * @param publicKey File containing the RSA public key
 * @return New AdbCrypto object
 * @throws IOException If the files cannot be read
 * @throws NoSuchAlgorithmException If an RSA key factory cannot be found
 * @throws InvalidKeySpecException If a PKCS8 or X509 key spec cannot be found
 */
public static AdbCrypto loadAdbKeyPair(AdbBase64 base64, File privateKey, File publicKey) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException
{
	AdbCrypto crypto = new AdbCrypto();
	
	int privKeyLength = (int)privateKey.length();
	int pubKeyLength = (int)publicKey.length();
	byte[] privKeyBytes = new byte[privKeyLength];
	byte[] pubKeyBytes = new byte[pubKeyLength];
	
	FileInputStream privIn = new FileInputStream(privateKey);
	FileInputStream pubIn = new FileInputStream(publicKey);
	
	privIn.read(privKeyBytes);
	pubIn.read(pubKeyBytes);
	
	privIn.close();
	pubIn.close();
	
	KeyFactory keyFactory = KeyFactory.getInstance("RSA");
	EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privKeyBytes);
	EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pubKeyBytes);
	
	crypto.keyPair = new KeyPair(keyFactory.generatePublic(publicKeySpec),
			keyFactory.generatePrivate(privateKeySpec));
	crypto.base64 = base64;
	
	return crypto;
}
 
Example #17
Source File: AdbCrypto.java    From SoloPi with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new AdbCrypto object from a key pair loaded from files.
 * @param base64 Implementation of base 64 conversion interface required by ADB 
 * @param privateKey File containing the RSA private key
 * @param publicKey File containing the RSA public key
 * @return New AdbCrypto object
 * @throws IOException If the files cannot be read
 * @throws NoSuchAlgorithmException If an RSA key factory cannot be found
 * @throws InvalidKeySpecException If a PKCS8 or X509 key spec cannot be found
 */
public static AdbCrypto loadAdbKeyPair(AdbBase64 base64, File privateKey, File publicKey) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException
{
	AdbCrypto crypto = new AdbCrypto();
	
	int privKeyLength = (int)privateKey.length();
	int pubKeyLength = (int)publicKey.length();
	byte[] privKeyBytes = new byte[privKeyLength];
	byte[] pubKeyBytes = new byte[pubKeyLength];
	
	FileInputStream privIn = new FileInputStream(privateKey);
	FileInputStream pubIn = new FileInputStream(publicKey);
	
	privIn.read(privKeyBytes);
	pubIn.read(pubKeyBytes);
	
	privIn.close();
	pubIn.close();
	
	KeyFactory keyFactory = KeyFactory.getInstance("RSA");
	EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privKeyBytes);
	EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pubKeyBytes);
	
	crypto.keyPair = new KeyPair(keyFactory.generatePublic(publicKeySpec),
			keyFactory.generatePrivate(privateKeySpec));
	crypto.base64 = base64;
	
	return crypto;
}
 
Example #18
Source File: NodeAddress.java    From hedera-mirror-node with Apache License 2.0 5 votes vote down vote up
public PublicKey getPublicKeyAsObject() {
    try {
        byte[] bytes = Hex.decodeHex(publicKey);
        EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(bytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(publicKeySpec);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #19
Source File: AdbCrypto.java    From TVRemoteIME with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a new AdbCrypto object from a key pair loaded from files.
 * @param base64 Implementation of base 64 conversion interface required by ADB 
 * @param privateKey File containing the RSA private key
 * @param publicKey File containing the RSA public key
 * @return New AdbCrypto object
 * @throws IOException If the files cannot be read
 * @throws NoSuchAlgorithmException If an RSA key factory cannot be found
 * @throws InvalidKeySpecException If a PKCS8 or X509 key spec cannot be found
 */
public static AdbCrypto loadAdbKeyPair(AdbBase64 base64, File privateKey, File publicKey) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException
{
	AdbCrypto crypto = new AdbCrypto();
	
	int privKeyLength = (int)privateKey.length();
	int pubKeyLength = (int)publicKey.length();
	byte[] privKeyBytes = new byte[privKeyLength];
	byte[] pubKeyBytes = new byte[pubKeyLength];
	
	FileInputStream privIn = new FileInputStream(privateKey);
	FileInputStream pubIn = new FileInputStream(publicKey);
	
	privIn.read(privKeyBytes);
	pubIn.read(pubKeyBytes);
	
	privIn.close();
	pubIn.close();
	
	KeyFactory keyFactory = KeyFactory.getInstance("RSA");
	EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privKeyBytes);
	EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pubKeyBytes);
	
	crypto.keyPair = new KeyPair(keyFactory.generatePublic(publicKeySpec),
			keyFactory.generatePrivate(privateKeySpec));
	crypto.base64 = base64;
	
	return crypto;
}
 
Example #20
Source File: AlgorithmLinker.java    From JWT4B with GNU General Public License v3.0 5 votes vote down vote up
private static PublicKey generatePublicKeyFromString(String key, String algorithm) {
	PublicKey publicKey = null;
	if(key.length()>1){
		key = cleanKey(key);
		byte[] keyByteArray = java.util.Base64.getDecoder().decode(key);
		try {
			KeyFactory kf = KeyFactory.getInstance(algorithm);
			EncodedKeySpec keySpec = new X509EncodedKeySpec(keyByteArray);
			publicKey = kf.generatePublic(keySpec);
		} catch (Exception e) {
			Output.outputError(e.getMessage());
		}
	}
	return publicKey;
}
 
Example #21
Source File: RSA.java    From kisso with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a private key constructed from the given DER bytes in PKCS#8 format.
 */
public static PrivateKey privateKeyFromPKCS8(final byte[] pkcs8) throws InvalidKeySpecException {
    try {
        final EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(pkcs8);
        final KeyFactory keyFactory = KeyFactory.getInstance(SSOConstants.RSA);
        return keyFactory.generatePrivate(privateKeySpec);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(e);
    }
}
 
Example #22
Source File: AdbCrypto.java    From adblib with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Creates a new AdbCrypto object from a key pair loaded from files.
 *
 * @param base64     Implementation of base 64 conversion interface required by ADB
 * @param privateKey File containing the RSA private key
 * @param publicKey  File containing the RSA public key
 * @return New AdbCrypto object
 * @throws IOException              If the files cannot be read
 * @throws NoSuchAlgorithmException If an RSA key factory cannot be found
 * @throws InvalidKeySpecException  If a PKCS8 or X509 key spec cannot be found
 */
public static AdbCrypto loadAdbKeyPair(AdbBase64 base64, File privateKey, File publicKey) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    AdbCrypto crypto = new AdbCrypto();

    int privKeyLength = (int) privateKey.length();
    int pubKeyLength = (int) publicKey.length();
    byte[] privKeyBytes = new byte[privKeyLength];
    byte[] pubKeyBytes = new byte[pubKeyLength];

    FileInputStream privIn = new FileInputStream(privateKey);
    FileInputStream pubIn = new FileInputStream(publicKey);

    privIn.read(privKeyBytes);
    pubIn.read(pubKeyBytes);

    privIn.close();
    pubIn.close();

    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privKeyBytes);
    EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pubKeyBytes);

    crypto.keyPair = new KeyPair(keyFactory.generatePublic(publicKeySpec),
            keyFactory.generatePrivate(privateKeySpec));
    crypto.base64 = base64;

    return crypto;
}
 
Example #23
Source File: AlgorithmLinker.java    From JWT4B with GNU General Public License v3.0 5 votes vote down vote up
private static PrivateKey generatePrivateKeyFromString(String key, String algorithm) {
	PrivateKey privateKey = null;
	if(key.length()>1){
		key = cleanKey(key);
		try {
			byte[] keyByteArray = Base64.decode(key);
			KeyFactory kf = KeyFactory.getInstance(algorithm);
			EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyByteArray);
			privateKey = kf.generatePrivate(keySpec);
		} catch (Exception e) {
			Output.outputError("Error generating private key with input string '"+key+"' and algorithm '"+algorithm+"' - "+e.getMessage()+" - ");
		}
	}
	return privateKey;
}
 
Example #24
Source File: CertUtil.java    From proxyee with MIT License 4 votes vote down vote up
/**
 * 从文件加载RSA公钥 openssl rsa -in ca.key -pubout -outform DER -out ca_pub.der
 */
public static PublicKey loadPubKey(byte[] bts) throws Exception {
    EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(bts);
    return getKeyFactory().generatePublic(publicKeySpec);
}
 
Example #25
Source File: CertUtil.java    From incubator-retired-wave with Apache License 2.0 4 votes vote down vote up
public static PrivateKey getPrivateKeyFromBytes(byte[] derKey) throws GeneralSecurityException {
  KeyFactory fac = KeyFactory.getInstance("RSA");
  EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(derKey);
  return fac.generatePrivate(privKeySpec);
}
 
Example #26
Source File: EncryptionHelper.java    From gocd with Apache License 2.0 4 votes vote down vote up
private static PublicKey getRSAPublicKeyFrom(String content) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    PemReader reader = new PemReader(new StringReader(content));
    EncodedKeySpec spec = new X509EncodedKeySpec(reader.readPemObject().getContent());
    return KeyFactory.getInstance("RSA").generatePublic(spec);
}
 
Example #27
Source File: RSA_SHA1.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
private PrivateKey getPrivateKeyFromDer(byte[] privateKeyObject)
        throws GeneralSecurityException {
    KeyFactory fac = KeyFactory.getInstance("RSA");
    EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(privateKeyObject);
    return fac.generatePrivate(privKeySpec);
}
 
Example #28
Source File: RSA_SHA1.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
private PublicKey getPublicKeyFromDer(byte[] publicKeyObject)
        throws GeneralSecurityException {
    KeyFactory fac = KeyFactory.getInstance("RSA");
    EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(publicKeyObject);
    return fac.generatePublic(pubKeySpec);
}
 
Example #29
Source File: TestPublicPrivateKeys.java    From http4e with Apache License 2.0 4 votes vote down vote up
private static void generateKeys(  String keyAlgorithm, int    numBits) {

        try {
            // Get the public/private key pair
            KeyPairGenerator keyGen = KeyPairGenerator.getInstance(keyAlgorithm);
            keyGen.initialize(numBits);
            KeyPair keyPair = keyGen.genKeyPair();
            PrivateKey privateKey = keyPair.getPrivate();
            PublicKey  publicKey  = keyPair.getPublic();
            
            System.out.println(
                    "\n" +
                    "Generating key/value pair using " +
                    privateKey.getAlgorithm() +
                    " algorithm");

            // Get the bytes of the public and private keys
            byte[] privateKeyBytes = privateKey.getEncoded();
            byte[] publicKeyBytes  = publicKey.getEncoded();

            // Get the formats of the encoded bytes
            String formatPrivate = privateKey.getFormat(); // PKCS#8
            String formatPublic  = publicKey.getFormat(); // X.509

            System.out.println("  Private Key Format : " + formatPrivate);
            System.out.println("  Public Key Format  : " + formatPublic);

            // The bytes can be converted back to public and private key objects
            KeyFactory keyFactory = KeyFactory.getInstance(keyAlgorithm);
            EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
            PrivateKey privateKey2 = keyFactory.generatePrivate(privateKeySpec);

            EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes);
            PublicKey publicKey2 = keyFactory.generatePublic(publicKeySpec);

            // The original and new keys are the same
            System.out.println(
                "  Are both private keys equal? " + privateKey.equals(privateKey2));

            System.out.println(
                "  Are both public keys equal? " + publicKey.equals(publicKey2));
            
        } catch (InvalidKeySpecException specException) {

            System.out.println("Exception");
            System.out.println("Invalid Key Spec Exception");
           
        } catch (NoSuchAlgorithmException e) {

            System.out.println("Exception");
            System.out.println("No such algorithm: " + keyAlgorithm);

        }

    }
 
Example #30
Source File: CertUtil.java    From proxyee with MIT License 4 votes vote down vote up
/**
 * 从文件加载RSA私钥 openssl pkcs8 -topk8 -nocrypt -inform PEM -outform DER -in ca.key -out
 * ca_private.der
 */
public static PrivateKey loadPriKey(byte[] bts)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(bts);
    return getKeyFactory().generatePrivate(privateKeySpec);
}