类java.security.spec.EncodedKeySpec源码实例Demo

下面列出了怎么用java.security.spec.EncodedKeySpec的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: Geyser   文件: EncryptionUtil.java

@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)
    );
}
 
源代码2 项目: http4e   文件: CryptUtils.java

/**
 * 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 };
}
 
源代码3 项目: j2objc   文件: EncodedKeySpecTest.java

/**
 * 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) {
        //
    }
}
 
源代码4 项目: j2objc   文件: EncodedKeySpecTest.java

/**
 * 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);
}
 
源代码5 项目: j2objc   文件: EncodedKeySpecTest.java

/**
 * 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);
}
 
源代码6 项目: j2objc   文件: EncodedKeySpecTest.java

/**
 * 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);
}
 

@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();
}
 
源代码8 项目: zrtp-java   文件: BCDHSuite.java

@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);
	}
}
 
源代码9 项目: SoloPi   文件: AdbCrypto.java

/**
 * 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;
}
 
源代码10 项目: hedera-mirror-node   文件: NodeAddress.java

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);
    }
}
 
源代码11 项目: TVRemoteIME   文件: AdbCrypto.java

/**
 * 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;
}
 
源代码12 项目: JWT4B   文件: AlgorithmLinker.java

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;
}
 
源代码13 项目: JWT4B   文件: AlgorithmLinker.java

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;
}
 
源代码14 项目: adblib   文件: AdbCrypto.java

/**
 * 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;
}
 
源代码15 项目: AppOpsX   文件: AdbCrypto.java

/**
 * 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;
}
 
源代码16 项目: kisso   文件: RSA.java

/**
 * 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);
    }
}
 
源代码17 项目: kisso   文件: RSA.java

/**
 * 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);
    }
}
 
源代码18 项目: http4e   文件: TestCrypt.java

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();
   }
}
 
源代码19 项目: BigApp_Discuz_Android   文件: Rsa.java

/**
 * 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;
    }
}
 
源代码20 项目: library   文件: SunECKeyLoader.java

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;
}
 
源代码21 项目: library   文件: ECDSAKeyLoader.java

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;
}
 
源代码22 项目: che   文件: SignatureKeyManager.java

/** 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()));
  }
}
 
源代码23 项目: zrtp-java   文件: BCDHSuite.java

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;
}
 
源代码24 项目: proxyee   文件: CertUtil.java

/**
 * 从文件加载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);
}
 
源代码25 项目: proxyee   文件: CertUtil.java

/**
 * 从文件加载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);
}
 
源代码26 项目: proxyee   文件: CertUtil.java

/**
 * 从文件加载RSA公钥 openssl rsa -in ca.key -pubout -outform DER -out ca_pub.der
 */
public static PublicKey loadPubKey(String path) throws Exception {
    EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(Files.readAllBytes(Paths.get(path)));
    return getKeyFactory().generatePublic(publicKeySpec);
}
 
源代码27 项目: lams   文件: RSA_SHA1.java

private PublicKey getPublicKeyFromDer(byte[] publicKeyObject)
        throws GeneralSecurityException {
    KeyFactory fac = KeyFactory.getInstance("RSA");
    EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(publicKeyObject);
    return fac.generatePublic(pubKeySpec);
}
 
源代码28 项目: lams   文件: RSA_SHA1.java

private PrivateKey getPrivateKeyFromDer(byte[] privateKeyObject)
        throws GeneralSecurityException {
    KeyFactory fac = KeyFactory.getInstance("RSA");
    EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(privateKeyObject);
    return fac.generatePrivate(privKeySpec);
}
 
源代码29 项目: http4e   文件: TestPublicPrivateKeys.java

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);

        }

    }
 
源代码30 项目: library   文件: ThroughputLatencyClient.java

public Client(int id, int numberOfOps, int requestSize, int interval, boolean readOnly, boolean verbose, int sign) {
    super("Client "+id);

    this.id = id;
    this.numberOfOps = numberOfOps;
    this.requestSize = requestSize;
    this.interval = interval;
    this.readOnly = readOnly;
    this.verbose = verbose;
    this.proxy = new ServiceProxy(id);
    this.request = new byte[this.requestSize];
    
    Random rand = new Random(System.nanoTime() + this.id);
    rand.nextBytes(request);
                        
    byte[] signature = new byte[0];
    Signature eng;
    
    try {

        if (sign > 0) {

            if (sign == 1) {
                eng = TOMUtil.getSigEngine();
                eng.initSign(proxy.getViewManager().getStaticConf().getPrivateKey());
            } else {

                eng = Signature.getInstance("SHA256withECDSA", "BC");

                //KeyFactory kf = KeyFactory.getInstance("EC", "BC");
                //Base64.Decoder b64 = Base64.getDecoder();
                //PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(b64.decode(ThroughputLatencyClient.privKey));
                //eng.initSign(kf.generatePrivate(spec));
                KeyFactory keyFactory = KeyFactory.getInstance("EC");
                EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(org.apache.commons.codec.binary.Base64.decodeBase64(privKey));
                PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
                eng.initSign(privateKey);

            }
            eng.update(request);
            signature = eng.sign();
        }

        ByteBuffer buffer = ByteBuffer.allocate(request.length + signature.length + (Integer.BYTES * 2));
        buffer.putInt(request.length);
        buffer.put(request);
        buffer.putInt(signature.length);
        buffer.put(signature);
        this.request = buffer.array();


    } catch (NoSuchAlgorithmException | SignatureException | NoSuchProviderException | InvalidKeyException | InvalidKeySpecException ex) {
        ex.printStackTrace();
        System.exit(0);
    }
    
}