Java Code Examples for java.security.PrivateKey

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project candlepin, under directory /src/main/java/org/candlepin/pki/.

Source file: PKIUtility.java

  42 
vote

public KeyPair decodeKeys(byte[] privKeyBits,byte[] pubKeyBits) throws InvalidKeySpecException, NoSuchAlgorithmException {
  KeyFactory keyFactory=KeyFactory.getInstance("RSA");
  PrivateKey privKey=keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privKeyBits));
  PublicKey pubKey=keyFactory.generatePublic(new X509EncodedKeySpec(pubKeyBits));
  return new KeyPair(pubKey,privKey);
}
 

Example 2

From project hudson-test-harness, under directory /src/test/java/hudson/model/.

Source file: UsageStatisticsTest.java

  38 
vote

/** 
 * Makes sure that the stat data can be decrypted safely.
 */
public void testRoundtrip() throws Exception {
  String privateKey="30820276020100300d06092a864886f70d0101010500048202603082025c0201000281810084cababdb38040f659c2cb07a36d758f46e84ebc3d6ba39d967aedf1d396b0788ed3ab868d45ce280b1102b434c2a250ddc3254defe1785ab4f94d7038cf69ecca16753d2de3f6ad8976b3f74902d8634111d730982da74e1a6e3fc0bc3523bba53e45b8a8cbfd0321b94efc9f7fefbe66ad85281e3d0323d87f4426ec51204f0203010001028180784deaacdea8bd31f2d44578601954be3f714b93c2d977dbd76efb8f71303e249ad12dbeb2d2a1192a1d7923a6010768d7e06a3597b3df83de1d5688eb0f0e58c76070eddd696682730c93890dc727564c65dc8416bfbde5aad4eb7a97ed923efb55a291daf3c00810c0e43851298472fd539aab355af8cedcf1e9a0cbead661024100c498375102b068806c71dec838dc8dfa5624fb8a524a49cffadc19d10689a8c9c26db514faba6f96e50a605122abd3c9af16e82f2b7565f384528c9f31ea5947024100aceafd31d7f4872a873c7e5fe88f20c2fb086a053c6970026b3ce364768e2033100efb1ad8f2010fe53454a29decedc23a8a0c8df347742b1f13e11bd3a284b9024100931321470cd0f6cd24d4278bf8e61f9d69b6ef2bf3163a944aa340f91c7ffdf33aeea22b18cc43514af6714a21bb148d6cdca14530a8fa65acd7a8f62bfc9b5f024067452059f8438dc61466488336fce3f00ec483ad04db638dce45daf850e5a8cd5635dc39b87f2fab32940247ec5167ddabe06e870858104500967ac687aa73e102407e3b7997503e18d8d0f094d5e0bd5d57cb93cb39a2fc42cec1ea9a1562786438b61139e45813204d72c919f5397e139ad051d98e4d0f8a06d237f42c0d8440fb";
  String publicKey="30819f300d06092a864886f70d010101050003818d003081890281810084cababdb38040f659c2cb07a36d758f46e84ebc3d6ba39d967aedf1d396b0788ed3ab868d45ce280b1102b434c2a250ddc3254defe1785ab4f94d7038cf69ecca16753d2de3f6ad8976b3f74902d8634111d730982da74e1a6e3fc0bc3523bba53e45b8a8cbfd0321b94efc9f7fefbe66ad85281e3d0323d87f4426ec51204f0203010001";
  String data=new UsageStatistics(publicKey).getStatData();
  System.out.println(data);
  KeyFactory keyFactory=KeyFactory.getInstance("RSA");
  PrivateKey priv=keyFactory.generatePrivate(new PKCS8EncodedKeySpec(Util.fromHexString(privateKey)));
  Cipher cipher=Cipher.getInstance("RSA");
  cipher.init(Cipher.DECRYPT_MODE,priv);
  byte[] cipherText=Base64.decode(data.toCharArray());
  InputStreamReader r=new InputStreamReader(new GZIPInputStream(new CombinedCipherInputStream(new ByteArrayInputStream(cipherText),cipher,"AES",1024)),"UTF-8");
  JSONObject o=JSONObject.fromObject(IOUtils.toString(r));
  System.out.println(o);
  assertEquals(1,o.getInt("stat"));
}
 

Example 3

From project openengsb-framework, under directory /components/util/src/test/java/org/openengsb/core/util/.

Source file: CipherUtilTest.java

  38 
vote

@Test public void testDecryptUsingPrivateKey_shouldResultInDecryptedText() throws Exception {
  PrivateKey key=CipherUtils.deserializePrivateKey(Base64.decodeBase64(PRIVATE_KEY_64),"RSA");
  byte[] data=CipherUtils.decrypt(Base64.decodeBase64(TEST_STRING_CIPHERED),key);
  String testString=new String(data);
  assertEquals(TEST_STRING,testString);
}
 

Example 4

From project gengweibo, under directory /src/net/oauth/signature/.

Source file: RSA_SHA1.java

  37 
vote

/** 
 * Load private key from various sources, including <ul> <li>A PrivateKey object <li>A string buffer for PEM <li>A byte array with PKCS#8 encoded key </ul>
 * @param privateKeyObject
 * @return The private key
 * @throws IOException
 * @throws GeneralSecurityException
 */
private PrivateKey loadPrivateKey(Object privateKeyObject) throws IOException, GeneralSecurityException {
  PrivateKey privateKey;
  if (privateKeyObject instanceof PrivateKey) {
    privateKey=(PrivateKey)privateKeyObject;
  }
 else   if (privateKeyObject instanceof String) {
    try {
      privateKey=getPrivateKeyFromPem((String)privateKeyObject);
    }
 catch (    IOException e) {
      privateKey=getPrivateKeyFromDer(decodeBase64((String)privateKeyObject));
    }
  }
 else   if (privateKeyObject instanceof byte[]) {
    privateKey=getPrivateKeyFromDer((byte[])privateKeyObject);
  }
 else {
    throw new IllegalArgumentException("Private key set through RSA_SHA1.PRIVATE_KEY must be of " + "type PrivateKey, String or byte[] and not " + privateKeyObject.getClass().getName());
  }
  return privateKey;
}
 

Example 5

From project apjp, under directory /APJP_LOCAL_JAVA/src/main/java/APJP/HTTPS/.

Source file: HTTPS.java

  36 
vote

public static synchronized SSLSocket createSSLSocket() throws HTTPSException {
  try {
    KeyStore defaultKeyStore=getDefaultKeyStore();
    PrivateKey privateKey=(PrivateKey)defaultKeyStore.getKey("APJP","APJP".toCharArray());
    Certificate certificateAuthority=defaultKeyStore.getCertificate("APJP");
    Certificate[] certificateArray=new Certificate[1];
    certificateArray[0]=certificateAuthority;
    KeyStore keyStore=KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(null,"APJP".toCharArray());
    keyStore.setCertificateEntry("APJP",certificateAuthority);
    keyStore.setKeyEntry("APJP",privateKey,"APJP".toCharArray(),certificateArray);
    SSLContext sslContext=SSLContext.getInstance("TLS");
    KeyManagerFactory keyManagerFactory=KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore,"APJP".toCharArray());
    TrustManagerFactory trustManagerFactory=TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keyStore);
    sslContext.init(keyManagerFactory.getKeyManagers(),trustManagerFactory.getTrustManagers(),null);
    SSLSocketFactory sslSocketFactory=(SSLSocketFactory)sslContext.getSocketFactory();
    return (SSLSocket)sslSocketFactory.createSocket();
  }
 catch (  Exception e) {
    logger.log(2,"HTTPS/CREATE_SSL_SOCKET: EXCEPTION",e);
    throw new HTTPSException("HTTPS/CREATE_SSL_SOCKET",e);
  }
}
 

Example 6

From project backend-update-center2, under directory /src/main/java/org/jvnet/hudson/update_center/.

Source file: Signer.java

  36 
vote

/** 
 * Generates a canonicalized JSON format of the given object, and put the signature in it. Because it mutates the signed object itself, validating the signature needs a bit of work, but this enables a signature to be added transparently.
 * @return The same value passed as the argument so that the method can be used like a filter.
 */
public JSONObject sign(JSONObject o) throws GeneralSecurityException, IOException, CmdLineException {
  if (!isConfigured())   return o;
  JSONObject sign=new JSONObject();
  List<X509Certificate> certs=getCertificateChain();
  X509Certificate signer=certs.get(0);
  PrivateKey key=((KeyPair)new PEMReader(new FileReader(privateKey)).readObject()).getPrivate();
  SignatureGenerator sg=new SignatureGenerator(signer,key);
  o.writeCanonical(new OutputStreamWriter(sg.getOut(),"UTF-8"));
  sg.addRecord(sign,"");
  OutputStream raw=new NullOutputStream();
  if (canonical != null) {
    raw=new FileOutputStream(canonical);
  }
  sg=new SignatureGenerator(signer,key);
  o.writeCanonical(new OutputStreamWriter(new TeeOutputStream(sg.getOut(),raw),"UTF-8")).close();
  sg.addRecord(sign,"correct_");
  JSONArray a=new JSONArray();
  for (  X509Certificate cert : certs)   a.add(new String(Base64.encodeBase64(cert.getEncoded())));
  sign.put("certificates",a);
  o.put("signature",sign);
  return o;
}
 

Example 7

From project connectbot, under directory /src/sk/vx/connectbot/bean/.

Source file: PubkeyBean.java

  36 
vote

public boolean changePassword(String oldPassword,String newPassword) throws Exception {
  PrivateKey priv;
  try {
    priv=PubkeyUtils.decodePrivate(getPrivateKey(),getType(),oldPassword);
  }
 catch (  Exception e) {
    return false;
  }
  setPrivateKey(PubkeyUtils.getEncodedPrivate(priv,newPassword));
  setEncrypted(newPassword.length() > 0);
  return true;
}
 

Example 8

From project Cours-3eme-ann-e, under directory /Java/FerryInpres/src/identity_server/.

Source file: IdentityApplic.java

  36 
vote

public static SecretKey keyExchange(ObjectInputStream in,ObjectOutputStream out) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, IOException, ClassNotFoundException, NoSuchPaddingException {
  KeyPairGenerator gen=KeyPairGenerator.getInstance("RSA");
  gen.initialize(1024,new SecureRandom());
  KeyPair keys=gen.generateKeyPair();
  PublicKey publicKey=keys.getPublic();
  PrivateKey privateKey=keys.getPrivate();
  out.writeObject(new KeyExchangeClient(publicKey));
  out.flush();
  KeyExchangeServer response=(KeyExchangeServer)in.readObject();
  Cipher decryptor=Cipher.getInstance("RSA/ECB/PKCS1Padding");
  decryptor.init(Cipher.DECRYPT_MODE,privateKey);
  byte[] sessionKeyEncoded=decryptor.doFinal(response.getCryptedSessionKey());
  return new SecretKeySpec(sessionKeyEncoded,"DES");
}
 

Example 9

From project eucalyptus, under directory /clc/modules/image-manager/src/edu/ucsb/eucalyptus/cloud/ws/.

Source file: ImageManager.java

  36 
vote

private void verifyManifestIntegrity(final ImageInfo imgInfo) throws EucalyptusCloudException {
  String[] imagePathParts=imgInfo.getImageLocation().split("/");
  GetObjectResponseType reply=null;
  GetObjectType msg=new GetObjectType(imagePathParts[0],imagePathParts[1],true,false,true);
  msg.setUserId(EucalyptusProperties.NAME);
  msg.setEffectiveUserId(EucalyptusProperties.NAME);
  try {
    reply=(GetObjectResponseType)Messaging.send(WalrusProperties.WALRUS_REF,msg);
  }
 catch (  EucalyptusCloudException e) {
    LOG.error(e);
    LOG.debug(e,e);
    throw new EucalyptusCloudException("Invalid manifest reference: " + imgInfo.getImageLocation());
  }
  if (reply == null || reply.getBase64Data() == null)   throw new EucalyptusCloudException("Invalid manifest reference: " + imgInfo.getImageLocation());
  XMLParser parser=new XMLParser(reply.getBase64Data());
  String encryptedKey=parser.getValue("//ec2_encrypted_key");
  String encryptedIV=parser.getValue("//ec2_encrypted_iv");
  String signature=parser.getValue("//signature");
  String image=parser.getXML("image");
  String machineConfiguration=parser.getXML("machine_configuration");
  EntityWrapper<UserInfo> db=new EntityWrapper<UserInfo>();
  List<String> aliases=Lists.newArrayList();
  List<UserInfo> users=db.query(new UserInfo());
  for (  UserInfo user : users)   for (  CertificateInfo certInfo : user.getCertificates())   aliases.add(certInfo.getCertAlias());
  boolean found=false;
  for (  String alias : aliases)   found|=this.verifyManifestSignature(signature,alias,machineConfiguration + image);
  if (!found)   throw new EucalyptusCloudException("Invalid Manifest: Failed to verify signature.");
  try {
    PrivateKey pk=(PrivateKey)UserKeyStore.getInstance().getKey(EucalyptusProperties.NAME,EucalyptusProperties.NAME);
    Cipher cipher=Cipher.getInstance("RSA/ECB/PKCS1Padding");
    cipher.init(Cipher.DECRYPT_MODE,pk);
    cipher.doFinal(Hashes.hexToBytes(encryptedKey));
    cipher.doFinal(Hashes.hexToBytes(encryptedIV));
  }
 catch (  Exception ex) {
    throw new EucalyptusCloudException("Invalid Manifest: Failed to recover keys.");
  }
}
 

Example 10

From project Gibberbot, under directory /src/info/guardianproject/otr/.

Source file: OtrAndroidKeyManagerImpl.java

  36 
vote

public void generateLocalKeyPair(String accountID){
  OtrDebugLogger.log("generating local key pair for: " + accountID);
  KeyPair keyPair;
  try {
    KeyPairGenerator kpg=KeyPairGenerator.getInstance(KEY_ALG);
    kpg.initialize(KEY_SIZE);
    keyPair=kpg.genKeyPair();
  }
 catch (  NoSuchAlgorithmException e) {
    OtrDebugLogger.log("no such algorithm",e);
    return;
  }
  OtrDebugLogger.log("SUCCESS! generating local key pair for: " + accountID);
  PublicKey pubKey=keyPair.getPublic();
  X509EncodedKeySpec x509EncodedKeySpec=new X509EncodedKeySpec(pubKey.getEncoded());
  this.store.setProperty(accountID + ".publicKey",x509EncodedKeySpec.getEncoded());
  PrivateKey privKey=keyPair.getPrivate();
  PKCS8EncodedKeySpec pkcs8EncodedKeySpec=new PKCS8EncodedKeySpec(privKey.getEncoded());
  this.store.setProperty(accountID + ".privateKey",pkcs8EncodedKeySpec.getEncoded());
  try {
    String fingerprintString=new OtrCryptoEngineImpl().getFingerprint(pubKey);
    this.store.setPropertyHex(accountID + ".fingerprint",Hex.decode(fingerprintString));
  }
 catch (  OtrCryptoException e) {
    e.printStackTrace();
  }
}
 

Example 11

From project isohealth, under directory /Oauth/java/jmeter/jmeter/src/main/java/org/apache/jmeter/protocol/oauth/sampler/.

Source file: PrivateKeyReader.java

  36 
vote

/** 
 * Get a Private Key for the file.
 * @return Private key
 * @throws IOException
 */
public PrivateKey getPrivateKey() throws IOException {
  PrivateKey key=keyCache.get(fileName);
  if (key != null) {
    log.debug("Key file " + fileName + " found in cache");
    return key;
  }
  server.reserveFile(fileName,"UTF-8",fileName);
  key=read();
  server.closeFile(fileName);
  keyCache.put(fileName,key);
  log.debug("Key file " + fileName + " loaded in cache");
  return key;
}
 

Example 12

From project JavaStory, under directory /Core/src/main/java/javastory/client/.

Source file: LoginCrypto.java

  36 
vote

public static String decryptRSA(final String EncryptedPassword){
  try {
    final Cipher cipher=Cipher.getInstance("RSA/NONE/OAEPPadding","BC");
    final BigInteger modulus=new BigInteger("107657795738756861764863218740655861479186575385923787150128619142132921674398952720882614694082036467689482295621654506166910217557126105160228025353603544726428541751588805629215516978192030682053419499436785335057001573080195806844351954026120773768050428451512387703488216884037312069441551935633523181351");
    final BigInteger privateExponent=new BigInteger("5550691850424331841608142211646492148529402295329912519344562675759756203942720314385192411176941288498447604817211202470939921344057999440566557786743767752684118754789131428284047255370747277972770485804010629706937510833543525825792410474569027516467052693380162536113699974433283374142492196735301185337");
    final RSAPrivateKeySpec privKey1=new RSAPrivateKeySpec(modulus,privateExponent);
    final PrivateKey privKey=RSAKeyFactory.generatePrivate(privKey1);
    final byte[] bytes=Hex.decode(EncryptedPassword);
    cipher.init(Cipher.DECRYPT_MODE,privKey);
    return new String(cipher.doFinal(bytes));
  }
 catch (  final InvalidKeyException ike) {
    System.err.println("[LoginCrypto] Error initalizing the encryption cipher.  Make sure you're using the Unlimited Strength cryptography jar files.");
  }
catch (  final NoSuchProviderException nspe) {
    System.err.println("[LoginCrypto] Security provider not found");
  }
catch (  final Exception e) {
    System.err.println("[LoginCrypto] Error occured with RSA password decryption.");
  }
  return "";
}
 

Example 13

From project jclouds-chef, under directory /core/src/main/java/org/jclouds/chef/config/.

Source file: BaseChefRestClientModule.java

  36 
vote

@Provides @Singleton @Validator public Optional<PrivateKey> provideValidatorCredential(Crypto crypto,Injector injector) throws InvalidKeySpecException, IOException {
  Key<String> key=Key.get(String.class,Names.named(CHEF_VALIDATOR_CREDENTIAL));
  try {
    String validatorCredential=injector.getInstance(key);
    PrivateKey validatorKey=crypto.rsaKeyFactory().generatePrivate(Pems.privateKeySpec(InputSuppliers.of(validatorCredential)));
    return Optional.<PrivateKey>of(validatorKey);
  }
 catch (  ConfigurationException ex) {
    return Optional.<PrivateKey>absent();
  }
}
 

Example 14

From project JGlobus, under directory /ssl-proxies/src/test/java/org/globus/gsi/.

Source file: OpenSSLKeyTest.java

  36 
vote

@Test public void testOpenSSLKeyCreation() throws Exception {
  OpenSSLKey opensslkey=new BouncyCastleOpenSSLKey(file.getAbsoluteFilename());
  byte[] encoded=opensslkey.getEncoded();
  OpenSSLKey byteStreamInit=new BouncyCastleOpenSSLKey("RSA",encoded);
  assertThat(opensslkey.getEncoded(),is(byteStreamInit.getEncoded()));
  PrivateKey privateKey=opensslkey.getPrivateKey();
  OpenSSLKey privateKeyInit=new BouncyCastleOpenSSLKey(privateKey);
  assertThat(opensslkey.getEncoded(),is(privateKeyInit.getEncoded()));
  opensslkey.encrypt("password");
  assertThat(opensslkey.getEncoded(),is(not(encoded)));
  byteStreamInit.encrypt("password");
  opensslkey=new BouncyCastleOpenSSLKey(opensslkey.getPrivateKey());
  opensslkey.decrypt("password");
  byteStreamInit=new BouncyCastleOpenSSLKey(byteStreamInit.getPrivateKey());
  byteStreamInit.decrypt("password");
  assertThat(opensslkey.getEncoded(),is(byteStreamInit.getEncoded()));
}
 

Example 15

From project nsi-minlog, under directory /functional-tests/src/test/java/dk/nsi/minlog/test/utils/.

Source file: SoapHeaders.java

  36 
vote

public static String getSamlAssertion() throws Exception {
  String alias="sosi:alias_system";
  PrivateKey key=(PrivateKey)vault.getKeyStore().getKey(alias,keystorePassword.toCharArray());
  X509Certificate cert=(X509Certificate)vault.getKeyStore().getCertificate(alias);
  PersonAndCertificate personAndCertificate=new PersonAndCertificate("Muhamad","Danielsen","muhamad@somedomain.dk","2006271866",orgUsingID.getValue(),cert,key);
  return getSosiIdCard(personAndCertificate);
}
 

Example 16

From project picketbox-keystore, under directory /src/main/java/org/picketbox/keystore/.

Source file: PicketBoxDBKeyStore.java

  36 
vote

private static void generateCSR(PicketBoxDBKeyStore ks,String alias,char[] keyPass,FileOutputStream fos) throws Exception {
  CertificateUtil util=new CertificateUtil();
  Certificate cert=ks.engineGetCertificate(alias);
  PrivateKey privateKey=(PrivateKey)ks.engineGetKey(alias,keyPass);
  KeyPair keyPair=new KeyPair(cert.getPublicKey(),privateKey);
  X509Certificate x509=(X509Certificate)cert;
  byte[] csr=util.createCSR(x509.getSubjectDN().getName(),keyPair);
  String pem=util.getPEM(csr);
  fos.write(pem.getBytes());
  System.out.println("CSR stored");
}
 

Example 17

From project Sage-Mobile-Calc, under directory /src/org/connectbot/bean/.

Source file: PubkeyBean.java

  36 
vote

public boolean changePassword(String oldPassword,String newPassword) throws Exception {
  PrivateKey priv;
  try {
    priv=PubkeyUtils.decodePrivate(getPrivateKey(),getType(),oldPassword);
  }
 catch (  Exception e) {
    return false;
  }
  setPrivateKey(PubkeyUtils.getEncodedPrivate(priv,newPassword));
  setEncrypted(newPassword.length() > 0);
  return true;
}
 

Example 18

From project security, under directory /external/src/test/java/org/jboss/seam/security/externaltest/module/.

Source file: SamlSignatureUtilForPostBindingTest.java

  36 
vote

@Before public void setup() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException {
  samlSignatureUtilForPostBinding=new SamlSignatureUtilForPostBinding();
  InputStream keyStoreStream=getClass().getClassLoader().getResourceAsStream("test_keystore.jks");
  KeyStore keyStore=KeyStore.getInstance(KeyStore.getDefaultType());
  keyStore.load(keyStoreStream,"store456".toCharArray());
  X509Certificate certificate=(X509Certificate)keyStore.getCertificate("servercert");
  PublicKey publicKey=certificate.getPublicKey();
  PrivateKey privateKey=(PrivateKey)keyStore.getKey("servercert","pass456".toCharArray());
  keyPair=new KeyPair(publicKey,privateKey);
}
 

Example 19

From project SPaTo_Visual_Explorer, under directory /deploy/.

Source file: SPaTo_Update_Builder.java

  36 
vote

public static void main(String args[]){
  try {
    PrivateKey privKey=getPrivateKey(fixPath("deploy/keystore"),"spato.update",(args.length > 0) ? args[0] : null);
    XMLElement xmlRelease=getReleaseInfo(fixPath("docs/release-notes/RELEASE_NOTES.xml"));
    String dstdir=fixPath("build/update");
    processIndex(fixPath("deploy/INDEX.linux"),fixPath("build/linux/SPaTo Visual Explorer"),dstdir,xmlRelease,privKey);
    processIndex(fixPath("deploy/INDEX.macosx"),fixPath("build/macosx/SPaTo Visual Explorer.app"),dstdir,xmlRelease,privKey);
    processIndex(fixPath("deploy/INDEX.windows"),fixPath("build/windows/SPaTo Visual Explorer"),dstdir,xmlRelease,privKey);
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
}
 

Example 20

From project android_build, under directory /tools/signapk/.

Source file: SignApk.java

  35 
vote

/** 
 * Read a PKCS 8 format private key. 
 */
private static PrivateKey readPrivateKey(File file) throws IOException, GeneralSecurityException {
  DataInputStream input=new DataInputStream(new FileInputStream(file));
  try {
    byte[] bytes=new byte[(int)file.length()];
    input.read(bytes);
    KeySpec spec=decryptPrivateKey(bytes,file);
    if (spec == null) {
      spec=new PKCS8EncodedKeySpec(bytes);
    }
    try {
      return KeyFactory.getInstance("RSA").generatePrivate(spec);
    }
 catch (    InvalidKeySpecException ex) {
      return KeyFactory.getInstance("DSA").generatePrivate(spec);
    }
  }
  finally {
    input.close();
  }
}
 

Example 21

From project DTE, under directory /src/cl/nic/dte/examples/.

Source file: EnviaDocumento.java

  35 
vote

/** 
 * @param args
 */
public static void main(String[] args) throws Exception {
  CmdLineParser parser=new CmdLineParser();
  CmdLineParser.Option certOpt=parser.addStringOption('c',"cert");
  CmdLineParser.Option passOpt=parser.addStringOption('s',"password");
  CmdLineParser.Option compaOpt=parser.addStringOption('f',"compania");
  try {
    parser.parse(args);
  }
 catch (  CmdLineParser.OptionException e) {
    printUsage();
    System.exit(2);
  }
  String certS=(String)parser.getOptionValue(certOpt);
  String passS=(String)parser.getOptionValue(passOpt);
  String compaS=(String)parser.getOptionValue(compaOpt);
  if (certS == null || passS == null || compaS == null) {
    printUsage();
    System.exit(2);
  }
  String[] otherArgs=parser.getRemainingArgs();
  if (otherArgs.length != 1) {
    printUsage();
    System.exit(2);
  }
  ConexionSii con=new ConexionSii();
  KeyStore ks=KeyStore.getInstance("PKCS12");
  ks.load(new FileInputStream(certS),passS.toCharArray());
  String alias=ks.aliases().nextElement();
  System.out.println("Usando certificado " + alias + " del archivo PKCS12: "+ certS);
  X509Certificate x509=(X509Certificate)ks.getCertificate(alias);
  PrivateKey pKey=(PrivateKey)ks.getKey(alias,passS.toCharArray());
  String token=con.getToken(pKey,x509);
  System.out.println("Token: " + token);
  String enviadorS=Utilities.getRutFromCertificate(x509);
  RECEPCIONDTEDocument recp=con.uploadEnvioCertificacion(enviadorS,compaS,new File(otherArgs[0]),token);
  System.out.println(recp.xmlText());
}
 

Example 22

From project dungbeetle, under directory /src/edu/stanford/mobisocial/dungbeetle/.

Source file: DBHelper.java

  35 
vote

private void generateAndStorePersonalInfo(SQLiteDatabase db){
  String email=getUserEmail();
  String name=email;
  KeyPair keypair=DBIdentityProvider.generateKeyPair();
  PrivateKey privateKey=keypair.getPrivate();
  PublicKey publicKey=keypair.getPublic();
  String pubKeyStr=FastBase64.encodeToString(publicKey.getEncoded());
  String privKeyStr=FastBase64.encodeToString(privateKey.getEncoded());
  ContentValues cv=new ContentValues();
  cv.put(MyInfo.PUBLIC_KEY,pubKeyStr);
  cv.put(MyInfo.PRIVATE_KEY,privKeyStr);
  cv.put(MyInfo.NAME,name);
  cv.put(MyInfo.EMAIL,email);
  db.insertOrThrow(MyInfo.TABLE,null,cv);
  Log.d(TAG,"Generated public key: " + pubKeyStr);
  Log.d(TAG,"Generated priv key: **************");
}
 

Example 23

From project ODE-X, under directory /runtime/src/main/java/org/apache/ode/runtime/exec/platform/.

Source file: NodeImpl.java

  35 
vote

@PostConstruct public void init(){
  try {
    encKey=clusterConfig.getSecurity().getEncKey();
    KeyStore ks=KeyStore.getInstance("PKCS12");
    ks.load(new ByteArrayInputStream(clusterConfig.getSecurity().getEncKeyStore()),clusterConfig.getSecurity().getEncKeyStorePass().toCharArray());
    PrivateKey privateKey=(PrivateKey)ks.getKey(clusterConfig.getSecurity().getKeyAlias(),clusterConfig.getSecurity().getEncKeyPass().toCharArray());
    if (privateKey == null) {
      throw new Exception(String.format("Can't find private key alias %s in cluster config keystore",clusterConfig.getSecurity().getKeyAlias()));
    }
    java.security.cert.Certificate cert=ks.getCertificate(clusterConfig.getSecurity().getKeyAlias());
    if (cert == null) {
      throw new Exception(String.format("Can't find public key alias %s in cluster config keystore",clusterConfig.getSecurity().getKeyAlias()));
    }
    PublicKey publicKey=cert.getPublicKey();
    clusterKey=new KeyPair(publicKey,privateKey);
  }
 catch (  Exception e) {
    log.log(Level.SEVERE,"",e);
  }
}
 

Example 24

From project OpenID-Connect-Java-Spring-Server, under directory /openid-connect-common/src/test/java/org/mitre/jwe/encryption/impl/.

Source file: RsaEncrypterDecrypterTest.java

  35 
vote

@Test public void encryptDecryptTest() throws JsonIOException, JsonSyntaxException, IOException, NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, InvalidKeySpecException {
  JsonParser parser=new JsonParser();
  JsonObject jweHeaderObject=parser.parse(new BufferedReader(new InputStreamReader(jweHeaderUrl.openStream()))).getAsJsonObject();
  KeyPairGenerator keyGen=KeyPairGenerator.getInstance("RSA");
  keyGen.initialize(4096);
  KeyPair pair=keyGen.generateKeyPair();
  PublicKey publicKey=pair.getPublic();
  PrivateKey privateKey=pair.getPrivate();
  Jwe jwe=new Jwe(new JweHeader(jweHeaderObject),null,jwePlaintextString.getBytes(),null);
  RsaEncrypter rsaEncrypter=new RsaEncrypter();
  rsaEncrypter.setPublicKey(publicKey);
  rsaEncrypter.setPrivateKey(privateKey);
  jwe=rsaEncrypter.encryptAndSign(jwe);
  RsaDecrypter rsaDecrypter=new RsaDecrypter();
  rsaDecrypter.setPublicKey(publicKey);
  rsaDecrypter.setPrivateKey(privateKey);
  String encryptedJweString=jwe.toString();
  jwe=rsaDecrypter.decrypt(encryptedJweString);
  String jweDecryptedCleartext=new String(jwe.getCiphertext());
  assertEquals(jweDecryptedCleartext,jwePlaintextString);
  assertEquals(jwe.getHeader().getAlgorithm(),jweHeaderObject.get("alg").getAsString());
  assertEquals(jwe.getHeader().getEncryptionMethod(),jweHeaderObject.get("enc").getAsString());
  assertEquals(jwe.getHeader().getIntegrity(),jweHeaderObject.get("int").getAsString());
  assertEquals(jwe.getHeader().getInitializationVector(),jweHeaderObject.get("iv").getAsString());
}
 

Example 25

From project OWASP-WebScarab, under directory /src/org/owasp/webscarab/plugin/proxy/.

Source file: SSLSocketFactoryFactory.java

  35 
vote

private X509KeyManager loadKeyMaterial(String host) throws GeneralSecurityException, IOException {
  X509Certificate[] certs=null;
  Certificate[] chain=keystore.getCertificateChain(host);
  if (chain != null) {
    certs=cast(chain);
  }
 else {
    throw new GeneralSecurityException("Internal error: certificate chain for " + host + " not found!");
  }
  PrivateKey pk=(PrivateKey)keystore.getKey(host,password);
  if (pk == null) {
    throw new GeneralSecurityException("Internal error: private key for " + host + " not found!");
  }
  return new HostKeyManager(host,pk,certs);
}
 

Example 26

From project platform_packages_apps_browser, under directory /src/com/android/browser/.

Source file: KeyChainLookup.java

  35 
vote

@Override protected Void doInBackground(Void... params){
  PrivateKey privateKey;
  X509Certificate[] certificateChain;
  try {
    privateKey=KeyChain.getPrivateKey(mContext,mAlias);
    certificateChain=KeyChain.getCertificateChain(mContext,mAlias);
  }
 catch (  InterruptedException e) {
    mHandler.ignore();
    return null;
  }
catch (  KeyChainException e) {
    mHandler.ignore();
    return null;
  }
  mHandler.proceed(privateKey,certificateChain);
  return null;
}
 

Example 27

From project playframework-oauthprovider, under directory /app/net/oauth/signature/.

Source file: RSA_SHA1.java

  35 
vote

/** 
 * Load private key from various sources, including <ul> <li>A PrivateKey object <li>A string buffer for PEM <li>A byte array with PKCS#8 encoded key </ul>
 * @param privateKeyObject
 * @return The private key
 * @throws IOException
 * @throws GeneralSecurityException
 */
private PrivateKey loadPrivateKey(Object privateKeyObject) throws IOException, GeneralSecurityException {
  PrivateKey privateKey;
  if (privateKeyObject instanceof PrivateKey) {
    privateKey=(PrivateKey)privateKeyObject;
  }
 else   if (privateKeyObject instanceof String) {
    try {
      privateKey=getPrivateKeyFromPem((String)privateKeyObject);
    }
 catch (    IOException e) {
      privateKey=getPrivateKeyFromDer(decodeBase64((String)privateKeyObject));
    }
  }
 else   if (privateKeyObject instanceof byte[]) {
    privateKey=getPrivateKeyFromDer((byte[])privateKeyObject);
  }
 else {
    throw new IllegalArgumentException("Private key set through RSA_SHA1.PRIVATE_KEY must be of " + "type PrivateKey, String or byte[] and not " + privateKeyObject.getClass().getName());
  }
  return privateKey;
}
 

Example 28

From project smsc-server, under directory /core/src/main/java/org/apache/smscserver/ssl/impl/.

Source file: AliasKeyManager.java

  35 
vote

/** 
 * Returns this key manager's server key alias that was provided in the constructor.
 * @param keyType The key algorithm type name
 * @param issuers The list of acceptable CA issuer subject names, or null if it does not matter which issuers are used (ignored)
 * @param socket The socket to be used for this connection. This parameter can be null, in which case this method will return the most generic alias to use (ignored)
 * @return Alias name for the desired key
 */
public String chooseServerAlias(String keyType,Principal[] issuers,Socket socket){
  if (this.serverKeyAlias != null) {
    PrivateKey key=this.delegate.getPrivateKey(this.serverKeyAlias);
    if (key != null) {
      if (key.getAlgorithm().equals(keyType)) {
        return this.serverKeyAlias;
      }
 else {
        return null;
      }
    }
 else {
      return null;
    }
  }
 else {
    return this.delegate.chooseServerAlias(keyType,issuers,socket);
  }
}
 

Example 29

From project spring-crypto-utils, under directory /src/main/java/com/springcryptoutils/core/key/.

Source file: PrivateKeyRegistryByAliasImpl.java

  35 
vote

/** 
 * Returns the selected private key or null if not found.
 * @param keyStoreChooser          the keystore chooser
 * @param privateKeyChooserByAlias the private key chooser by alias
 * @return the selected private key or null if not found
 */
public PrivateKey get(KeyStoreChooser keyStoreChooser,PrivateKeyChooserByAlias privateKeyChooserByAlias){
  CacheKey cacheKey=new CacheKey(keyStoreChooser.getKeyStoreName(),privateKeyChooserByAlias.getAlias());
  PrivateKey retrievedPrivateKey=cache.get(cacheKey);
  if (retrievedPrivateKey != null) {
    return retrievedPrivateKey;
  }
  KeyStore keyStore=keyStoreRegistry.get(keyStoreChooser);
  if (keyStore != null) {
    PrivateKeyFactoryBean factory=new PrivateKeyFactoryBean();
    factory.setKeystore(keyStore);
    factory.setAlias(privateKeyChooserByAlias.getAlias());
    factory.setPassword(privateKeyChooserByAlias.getPassword());
    try {
      factory.afterPropertiesSet();
      PrivateKey privateKey=(PrivateKey)factory.getObject();
      if (privateKey != null) {
        cache.put(cacheKey,privateKey);
      }
      return privateKey;
    }
 catch (    Exception e) {
      throw new PrivateKeyException("error initializing private key factory bean",e);
    }
  }
  return null;
}
 

Example 30

From project sshj, under directory /src/main/java/net/schmizz/sshj/userauth/method/.

Source file: KeyedAuthMethod.java

  35 
vote

protected SSHPacket putSig(SSHPacket reqBuf) throws UserAuthException {
  PrivateKey key;
  try {
    key=kProv.getPrivate();
  }
 catch (  IOException ioe) {
    throw new UserAuthException("Problem getting private key from " + kProv,ioe);
  }
  final String kt=KeyType.fromKey(key).toString();
  Signature sigger=Factory.Named.Util.create(params.getTransport().getConfig().getSignatureFactories(),kt);
  if (sigger == null)   throw new UserAuthException("Could not create signature instance for " + kt + " key");
  sigger.init(null,key);
  sigger.update(new Buffer.PlainBuffer().putString(params.getTransport().getSessionID()).putBuffer(reqBuf).getCompactData());
  reqBuf.putSignature(kt,sigger.sign());
  return reqBuf;
}
 

Example 31

From project tinfoil-sms, under directory /branches/crypto-dev/ECCKeyGeneration/src/com/tinfoil/sms/.

Source file: ECCKeyGenerationActivity.java

  35 
vote

public void encryption_test(KeyPairGenerator generator){
  try {
    KeyPair aKeyPair=generator.generateKeyPair();
    PublicKey aPub=aKeyPair.getPublic();
    PrivateKey aPriv=aKeyPair.getPrivate();
    Toast.makeText(getApplicationContext(),"Generated ECC Keypair A",Toast.LENGTH_SHORT).show();
    KeyPair bKeyPair=generator.generateKeyPair();
    PublicKey bPub=bKeyPair.getPublic();
    PrivateKey bPriv=bKeyPair.getPrivate();
    Toast.makeText(getApplicationContext(),"Generated ECC Keypair B",Toast.LENGTH_SHORT).show();
    Cipher c1=Cipher.getInstance("ECIES","SC");
    Cipher c2=Cipher.getInstance("ECIES","SC");
    IEKeySpec c1Key=new IEKeySpec(aPriv,bPub);
    IEKeySpec c2Key=new IEKeySpec(bPriv,aPub);
    byte[] d=new byte[]{1,2,3,4,5,6,7,8};
    byte[] e=new byte[]{8,7,6,5,4,3,2,1};
    IESParameterSpec param=new IESParameterSpec(d,e,128);
    c1.init(Cipher.ENCRYPT_MODE,c1Key,param);
    c2.init(Cipher.DECRYPT_MODE,c2Key,param);
    byte[] message="requirements are in my blood says the ramiro, this is great!".getBytes();
    Toast.makeText(getApplicationContext(),"Original Message: " + new String(message),Toast.LENGTH_LONG).show();
    byte[] out1=c1.doFinal(message,0,message.length);
    Toast.makeText(getApplicationContext(),"Encrypted Message: " + new String(out1),Toast.LENGTH_LONG).show();
    byte[] out2=c2.doFinal(out1,0,out1.length);
    Toast.makeText(getApplicationContext(),"Decrypted Message: " + new String(out2),Toast.LENGTH_LONG).show();
    if (!same_as(out2,message)) {
      Toast.makeText(getApplicationContext(),"Stream cipher test FAILED",Toast.LENGTH_SHORT).show();
    }
 else {
      Toast.makeText(getApplicationContext(),"Stream cipher test PASSED",Toast.LENGTH_SHORT).show();
    }
  }
 catch (  Exception ex) {
    Toast.makeText(getApplicationContext(),"stream cipher test exception " + ex.toString(),Toast.LENGTH_SHORT).show();
  }
}
 

Example 32

From project BombusLime, under directory /src/org/xbill/DNS/.

Source file: SIG0.java

  33 
vote

/** 
 * Sign a message with SIG(0). The DNS key and private key must refer to the same underlying cryptographic key.
 * @param message The message to be signed
 * @param key The DNSKEY record to use as part of signing
 * @param privkey The PrivateKey to use when signing
 * @param previous If this message is a response, the SIG(0) from the query
 */
public static void signMessage(Message message,KEYRecord key,PrivateKey privkey,SIGRecord previous) throws DNSSEC.DNSSECException {
  int validity=Options.intValue("sig0validity");
  if (validity < 0)   validity=VALIDITY;
  long now=System.currentTimeMillis();
  Date timeSigned=new Date(now);
  Date timeExpires=new Date(now + validity * 1000);
  SIGRecord sig=DNSSEC.signMessage(message,previous,key,privkey,timeSigned,timeExpires);
  message.addRecord(sig,Section.ADDITIONAL);
}
 

Example 33

From project capedwarf-blue, under directory /appidentity/src/main/java/org/jboss/capedwarf/appidentity/.

Source file: JBossAppIdentityService.java

  33 
vote

private byte[] sign(byte[] bytes,PrivateKey privateKey){
  try {
    Signature dsa=Signature.getInstance("SHA256WithRSA","BC");
    dsa.initSign(privateKey);
    dsa.update(bytes);
    return dsa.sign();
  }
 catch (  NoSuchAlgorithmException e) {
    throw new AppIdentityServiceFailureException("Cannot sign: " + e);
  }
catch (  NoSuchProviderException e) {
    throw new AppIdentityServiceFailureException("Cannot sign: " + e);
  }
catch (  InvalidKeyException e) {
    throw new AppIdentityServiceFailureException("Cannot sign: " + e);
  }
catch (  SignatureException e) {
    throw new AppIdentityServiceFailureException("Cannot sign: " + e);
  }
}
 

Example 34

From project cas, under directory /cas-server-core/src/main/java/org/jasig/cas/authentication/principal/.

Source file: GoogleAccountsService.java

  33 
vote

protected GoogleAccountsService(final String id,final String originalUrl,final String artifactId,final String relayState,final String requestId,final PrivateKey privateKey,final PublicKey publicKey,final String alternateUserName){
  super(id,originalUrl,artifactId,null);
  this.relayState=relayState;
  this.privateKey=privateKey;
  this.publicKey=publicKey;
  this.requestId=requestId;
  this.alternateUserName=alternateUserName;
}
 

Example 35

From project Citizens, under directory /src/core/net/citizensnpcs/resources/npclib/.

Source file: NPCNetworkManager.java

  33 
vote

public NPCNetworkManager(Socket paramSocket,String paramString,NetHandler paramNetHandler,PrivateKey key) throws IOException {
  super(paramSocket,paramString,paramNetHandler,key);
  if (THREAD_STOPPER != null) {
    try {
      THREAD_STOPPER.set(this,false);
    }
 catch (    Exception e) {
    }
  }
}
 

Example 36

From project cogroo4, under directory /lang/pt_br/cogroo-addon/src/org/cogroo/addon/util/.

Source file: SecurityUtil.java

  33 
vote

/** 
 * Encrypt data using an key encrypted with a private key.
 * @param privateKey the private key to decrypt the secret key
 * @param encryptedSecretKey a encrypted secret key
 * @param data the data to encrypt
 * @return the encrypted data
 * @throws InvalidKeyException one of the keys is invalid
 */
public byte[] encrypt(PrivateKey privateKey,byte[] encryptedSecretKey,String data) throws InvalidKeyException {
  byte[] encryptedData=null;
  try {
    byte[] chave=privateKey.getEncoded();
    Cipher rsacf=Cipher.getInstance("RSA");
    rsacf.init(Cipher.DECRYPT_MODE,privateKey);
    byte[] secretKey=rsacf.doFinal(encryptedSecretKey);
    encryptedData=encrypt(secretKey,data);
  }
 catch (  Exception e) {
    LOG.log(Level.SEVERE,"Exception encrypting data",e);
  }
  return encryptedData;
}
 

Example 37

From project dnieprov, under directory /src/org/dnieprov/jce/provider/.

Source file: DnieSignature.java

  33 
vote

@Override protected void engineInitSign(PrivateKey privateKey) throws InvalidKeyException {
  if (!(privateKey instanceof DniePrivateKey)) {
    throw new InvalidKeyException("Key not found in driver");
  }
  DniePrivateKey tmpDnieKey=(DniePrivateKey)privateKey;
  Enumeration<DnieCard> cards=driver.getCards();
  boolean found=false;
  while (cards.hasMoreElements()) {
    DnieCard card=cards.nextElement();
    if (tmpDnieKey.inCard(card)) {
      found=true;
      this.dnieKey=tmpDnieKey;
    }
  }
  if (!found) {
    throw new InvalidKeyException("Key not found in driver");
  }
}
 

Example 38

From project freemind, under directory /freemind/plugins/script/.

Source file: SignedScriptHandler.java

  33 
vote

public String signScript(String pScript,TextTranslator pTranslator,FreeMindMain pFrame){
  ScriptContents content=new ScriptContents(pScript);
  EnterPasswordDialog pwdDialog=new EnterPasswordDialog(pFrame.getJFrame(),pTranslator,false);
  pwdDialog.setModal(true);
  pwdDialog.setVisible(true);
  if (pwdDialog.getResult() == EnterPasswordDialog.CANCEL) {
    return content.mScript;
  }
  char[] password=pwdDialog.getPassword().toString().toCharArray();
  initializeKeystore(password);
  try {
    Signature instance=Signature.getInstance("SHA1withDSA");
    String keyName=FREEMIND_SCRIPT_KEY_NAME;
    String propertyKeyName=Resources.getInstance().getProperty(FreeMind.RESOURCES_SCRIPT_USER_KEY_NAME_FOR_SIGNING);
    if (content.mKeyName != null) {
      keyName=content.mKeyName;
    }
 else     if (propertyKeyName != null && propertyKeyName.length() > 0) {
      content.mKeyName=propertyKeyName;
      keyName=content.mKeyName;
    }
    instance.initSign((PrivateKey)mKeyStore.getKey(keyName,password));
    instance.update(content.mScript.getBytes());
    byte[] signature=instance.sign();
    content.mSignature=Tools.toBase64(signature);
    return content.toString();
  }
 catch (  Exception e) {
    Resources.getInstance().logException(e);
    pFrame.getController().errorMessage(e.getLocalizedMessage());
  }
  return content.mScript;
}
 

Example 39

From project IOCipherServer, under directory /src/info/guardianproject/iocipher/server/.

Source file: KeyStoreGenerator.java

  33 
vote

public static X509Certificate makeCertificate(PrivateKey issuerPrivateKey,PublicKey subjectPublicKey,String cn,String o,String ou,String l,String st,String c) throws Exception {
  final org.spongycastle.asn1.x509.X509Name issuerDN=new org.spongycastle.asn1.x509.X509Name("CN=" + cn + ", OU="+ ou+ ", O="+ o+ ", L="+ l+ ", ST="+ st+ ", C="+ c);
  final org.spongycastle.asn1.x509.X509Name subjectDN=new org.spongycastle.asn1.x509.X509Name("CN=" + cn + ", OU="+ ou+ ", O="+ o+ ", L="+ l+ ", ST="+ st+ ", C="+ c);
  final int daysTillExpiry=10 * 365;
  final Calendar expiry=Calendar.getInstance();
  expiry.add(Calendar.DAY_OF_YEAR,daysTillExpiry);
  final org.spongycastle.x509.X509V3CertificateGenerator certificateGenerator=new org.spongycastle.x509.X509V3CertificateGenerator();
  certificateGenerator.setSerialNumber(java.math.BigInteger.valueOf(System.currentTimeMillis()));
  certificateGenerator.setIssuerDN(issuerDN);
  certificateGenerator.setSubjectDN(subjectDN);
  certificateGenerator.setPublicKey(subjectPublicKey);
  certificateGenerator.setNotBefore(new Date());
  certificateGenerator.setNotAfter(expiry.getTime());
  certificateGenerator.setSignatureAlgorithm("MD5WithRSA");
  return certificateGenerator.generate(issuerPrivateKey);
}
 

Example 40

From project jentrata-msh, under directory /Commons/src/main/java/hk/hku/cecid/piazza/commons/security/.

Source file: KeyStoreKeyManager.java

  33 
vote

/** 
 * Gets the key associated with the given alias.
 * @param alias the alias name.
 * @return the private key.
 * @throws RuntimeException if unable to retrieve the private key. 
 * @see javax.net.ssl.X509KeyManager#getPrivateKey(java.lang.String)
 */
public PrivateKey getPrivateKey(String alias){
  try {
    return (PrivateKey)keyStore.getKey(alias,keyPass);
  }
 catch (  Exception e) {
    throw new RuntimeException("Unable to retrieve private key",e);
  }
}
 

Example 41

From project karaf, under directory /jaas/config/src/main/java/org/apache/karaf/jaas/config/impl/.

Source file: ResourceKeystoreInstance.java

  33 
vote

public PrivateKey getPrivateKey(String alias){
  if (!loadKeystoreData()) {
    return null;
  }
  try {
    if (isKeyLocked(alias)) {
      return null;
    }
    Key key=keystore.getKey(alias,(char[])keyPasswords.get(alias));
    if (key instanceof PrivateKey) {
      return (PrivateKey)key;
    }
  }
 catch (  KeyStoreException e) {
    logger.error("Unable to read private key from keystore",e);
  }
catch (  NoSuchAlgorithmException e) {
    logger.error("Unable to read private key from keystore",e);
  }
catch (  UnrecoverableKeyException e) {
    logger.error("Unable to read private key from keystore",e);
  }
  return null;
}
 

Example 42

From project Maimonides, under directory /src/com/codeko/apps/maimonides/dnie/.

Source file: DNIe.java

  33 
vote

public boolean autentificar(){
  boolean result=false;
  try {
    firePropertyChange("message",null,"Verficando clave de DNIe");
    Certificate c=getCertificadoAutentificacion();
    if (c != null) {
      if (!(c instanceof X509Certificate)) {
        throw new Exception("Los datos no corresponden a un certificado v?lido");
      }
      X509Certificate x509=(X509Certificate)c;
      System.out.println(x509.getSubjectDN());
      x509.checkValidity();
      boolean flags[]=x509.getKeyUsage();
      if (!flags[0]) {
        throw new Exception("El certificado no es v?lido para autenticaci?n");
      }
      byte[] challenge=new byte[8];
      for (int n=0; n < 8; n++) {
        challenge[n]=new Double(256.0 * Math.random()).byteValue();
      }
      Key prkey=getKeyStore().getKey(certAlias,getPin().toCharArray());
      if (!(prkey instanceof PrivateKey)) {
        throw new Exception("El certificado no tiene asociada una clave privada");
      }
      Signature sig=Signature.getInstance("SHA1withRSA");
      sig.initSign((PrivateKey)prkey);
      sig.update(challenge);
      byte signature[]=sig.sign();
      sig=Signature.getInstance("SHA1withRSA");
      sig.initVerify(c);
      sig.update(challenge);
      result=sig.verify(signature);
    }
  }
 catch (  Exception e) {
    Logger.getLogger(DNIe.class.getName()).log(Level.SEVERE,null,e);
    firePropertyChange("message",null,"Clave de DNIe no v?lida");
  }
  return result;
}
 

Example 43

From project masa, under directory /plugins/maven-apkbuilder-plugin/src/main/java/org/jvending/masa/plugin/apkbuilder/.

Source file: ApkBuilderMojo.java

  33 
vote

private SigningInfo(PrivateKey key,X509Certificate certificate){
  if (key == null && certificate == null) {
    throw new IllegalArgumentException("key and certificate cannot both be null");
  }
  this.key=key;
  this.certificate=certificate;
}
 

Example 44

From project maven-wagon, under directory /wagon-providers/wagon-ssh-common-test/src/main/java/org/apache/maven/wagon/providers/ssh/.

Source file: TestPublickeyAuthenticator.java

  33 
vote

public static byte[] decrypt(byte[] text,PrivateKey key) throws Exception {
  byte[] dectyptedText=null;
  Cipher cipher=Cipher.getInstance("RSA/ECB/PKCS1Padding");
  cipher.init(Cipher.DECRYPT_MODE,key);
  dectyptedText=cipher.doFinal(text);
  return dectyptedText;
}
 

Example 45

From project mina-sshd, under directory /sshd-core/src/main/java/org/apache/sshd/common/signature/.

Source file: AbstractSignature.java

  33 
vote

public void init(PublicKey pubkey,PrivateKey prvkey) throws Exception {
  signature=SecurityUtils.getSignature(algorithm);
  if (pubkey != null) {
    signature.initVerify(pubkey);
  }
  if (prvkey != null) {
    signature.initSign(prvkey);
  }
}
 

Example 46

From project narya, under directory /core/src/main/java/com/threerings/presents/net/.

Source file: PublicKeyCredentials.java

  33 
vote

/** 
 * Decodes the secret.
 */
public byte[] getSecret(PrivateKey key){
  if (_secret == null) {
    _secret=SecureUtil.decryptBytes(key,_encodedSecret,_salt);
  }
  return _secret;
}
 

Example 47

From project Ohmage_Phone, under directory /src/edu/ucla/cens/pdc/libpdc/core/.

Source file: PDCKeyManager.java

  33 
vote

private static PrivateKey producePrivateKey(SystemState.AsyncKey ak_state) throws ConfigurationException {
  try {
    final KeyFactory key_factory=KeyFactory.getInstance(ak_state.getAlgorithm().name());
    final PKCS8EncodedKeySpec key_spec=new PKCS8EncodedKeySpec(ak_state.getPrivateKey().toByteArray());
    return key_factory.generatePrivate(key_spec);
  }
 catch (  NoSuchAlgorithmException ex) {
    throw new ConfigurationException("Unsupported algorithm for private key",ex);
  }
catch (  InvalidKeySpecException ex) {
    throw new ConfigurationException("Unable to restore the private key",ex);
  }
}
 

Example 48

From project Ohmage_Server_2, under directory /src/edu/ucla/cens/pdc/libpdc/core/.

Source file: PDCKeyManager.java

  33 
vote

private static PrivateKey producePrivateKey(SystemState.AsyncKey ak_state) throws ConfigurationException {
  try {
    final KeyFactory key_factory=KeyFactory.getInstance(ak_state.getAlgorithm().name());
    final PKCS8EncodedKeySpec key_spec=new PKCS8EncodedKeySpec(ak_state.getPrivateKey().toByteArray());
    return key_factory.generatePrivate(key_spec);
  }
 catch (  NoSuchAlgorithmException ex) {
    throw new ConfigurationException("Unsupported algorithm for private key",ex);
  }
catch (  InvalidKeySpecException ex) {
    throw new ConfigurationException("Unable to restore the private key",ex);
  }
}
 

Example 49

From project pdftk, under directory /java/com/lowagie/text/pdf/.

Source file: PdfSigGenericPKCS.java

  33 
vote

/** 
 * Sets the crypto information to sign.
 * @param privKey the private key
 * @param certChain the certificate chain
 * @param crlList the certificate revocation list. It can be <CODE>null</CODE>
 */
public void setSignInfo(PrivateKey privKey,Certificate[] certChain,CRL[] crlList){
  try {
    pkcs=new PdfPKCS7(privKey,certChain,crlList,hashAlgorithm,provider,PdfName.ADBE_PKCS7_SHA1.equals(get(PdfName.SUBFILTER)));
    pkcs.setExternalDigest(externalDigest,externalRSAdata,digestEncryptionAlgorithm);
    if (PdfName.ADBE_X509_RSA_SHA1.equals(get(PdfName.SUBFILTER))) {
      ByteArrayOutputStream bout=new ByteArrayOutputStream();
      for (int k=0; k < certChain.length; ++k) {
        bout.write(certChain[k].getEncoded());
      }
      bout.close();
      setCert(bout.toByteArray());
      setContents(pkcs.getEncodedPKCS1());
    }
 else     setContents(pkcs.getEncodedPKCS7());
    name=PdfPKCS7.getSubjectFields(pkcs.getSigningCertificate()).getField("CN");
    if (name != null)     put(PdfName.NAME,new PdfString(name,PdfObject.TEXT_UNICODE));
    pkcs=new PdfPKCS7(privKey,certChain,crlList,hashAlgorithm,provider,PdfName.ADBE_PKCS7_SHA1.equals(get(PdfName.SUBFILTER)));
    pkcs.setExternalDigest(externalDigest,externalRSAdata,digestEncryptionAlgorithm);
  }
 catch (  Exception e) {
    throw new ExceptionConverter(e);
  }
}
 

Example 50

From project Pitbull, under directory /pitbull-core/src/main/java/org/jboss/pitbull/internal/crypto/.

Source file: DerUtils.java

  33 
vote

public static PrivateKey decodePrivateKey(InputStream is) throws Exception {
  DataInputStream dis=new DataInputStream(is);
  byte[] keyBytes=new byte[dis.available()];
  dis.readFully(keyBytes);
  dis.close();
  PKCS8EncodedKeySpec spec=new PKCS8EncodedKeySpec(keyBytes);
  KeyFactory kf=KeyFactory.getInstance("RSA","BC");
  return kf.generatePrivate(spec);
}
 

Example 51

From project spring-security-oauth, under directory /spring-security-oauth/src/main/java/org/springframework/security/oauth/common/signature/.

Source file: RSAKeySecret.java

  33 
vote

/** 
 * Creates a private key from the PKCS#8-encoded value of the given bytes.
 * @param privateKey The PKCS#8-encoded private key bytes.
 * @return The private key.
 */
public static PrivateKey createPrivateKey(byte[] privateKey){
  if (privateKey == null) {
    return null;
  }
  try {
    KeyFactory fac=KeyFactory.getInstance("RSA");
    EncodedKeySpec spec=new PKCS8EncodedKeySpec(privateKey);
    return fac.generatePrivate(spec);
  }
 catch (  NoSuchAlgorithmException e) {
    throw new IllegalStateException(e);
  }
catch (  InvalidKeySpecException e) {
    throw new IllegalStateException(e);
  }
}
 

Example 52

From project thumbslug, under directory /src/main/java/org/candlepin/thumbslug/ssl/.

Source file: PEMx509KeyManager.java

  33 
vote

private PrivateKey getPrivateKeyFromPem(String pem) throws GeneralSecurityException, IOException {
  InputStream stream=new ByteArrayInputStream(pem.getBytes("UTF-8"));
  PEMReader reader=new PEMReader(stream);
  byte[] bytes=reader.getDerBytes();
  KeySpec keySpec;
  if (PEMReader.PRIVATE_PKCS1_MARKER.equals(reader.getBeginMarker())) {
    keySpec=(new PKCS1EncodedKeySpec(bytes)).getKeySpec();
  }
 else   if (PEMReader.PRIVATE_PKCS8_MARKER.equals(reader.getBeginMarker())) {
    keySpec=new PKCS8EncodedKeySpec(bytes);
  }
 else {
    throw new IOException("Invalid PEM file: Unknown marker " + "for private key " + reader.getBeginMarker());
  }
  KeyFactory fac=KeyFactory.getInstance("RSA");
  return fac.generatePrivate(keySpec);
}
 

Example 53

From project TomP2P, under directory /src/main/java/net/tomp2p/message/.

Source file: ProtocolChunkedInput.java

  33 
vote

public ProtocolChunkedInput(ChannelHandlerContext ctx,PrivateKey privateKey) throws NoSuchAlgorithmException, InvalidKeyException {
  this.ctx=ctx;
  if (privateKey != null) {
    signature=Signature.getInstance("SHA1withDSA");
    signature.initSign(privateKey);
  }
 else {
    signature=null;
  }
}
 

Example 54

From project Vega, under directory /platform/com.subgraph.vega.http.proxy/src/com/subgraph/vega/internal/http/proxy/ssl/.

Source file: CertificateCreator.java

  33 
vote

private X509Certificate generateCertificate(X500Principal subject,PublicKey subjectPublic,X500Principal issuer,PublicKey issuerPublicKey,PrivateKey issuerPrivateKey,boolean isCaCert) throws CertificateException {
  try {
    final Date notBefore=new Date();
    final Date notAfter=new Date(notBefore.getTime() + DEFAULT_VALIDITY);
    final X500Signer signer=createCertificateSigner(issuer,issuerPrivateKey);
    final CertificateValidity validity=new CertificateValidity(notBefore,notAfter);
    final X509CertInfo info=createCertificateInfo(subject,subjectPublic,issuer,issuerPublicKey,validity,signer);
    final CertificateExtensions extensions=(isCaCert) ? (getCACertificateExtensions()) : (getCertificateExtensions(subjectPublic,issuerPublicKey));
    info.set(X509CertInfo.EXTENSIONS,extensions);
    final X509CertImpl cert=new X509CertImpl(info);
    cert.sign(issuerPrivateKey,SIGNATURE_ALGORITHM);
    return cert;
  }
 catch (  Exception e) {
    throw new CertificateException("Failed to generate certificate: " + e.getMessage(),e);
  }
}