List of usage examples for java.security.interfaces RSAPublicKey getEncoded
public byte[] getEncoded();
From source file:cn.util.RSAUtils.java
public static void main(String[] args) throws Exception { // TODO Auto-generated method stub // HashMap<String, Object> map = RSAUtils.getKeys(); // //??//from w ww .ja v a 2 s . com // RSAPublicKey publicKey = (RSAPublicKey) map.get("public"); // RSAPrivateKey privateKey = (RSAPrivateKey) map.get("private"); // String ming = "wow"; //?? RSAPublicKey pubKey = RSAUtils.getPublicKey(); RSAPrivateKey priKey = RSAUtils.getPrivateKey(); System.err.println(":" + Base64Util.encryptBASE64(pubKey.getEncoded())); System.err.println("?:" + Base64Util.encryptBASE64(priKey.getEncoded())); //? String mi = RSAUtils.encryptByPublicKey(ming); System.err.println("?:" + mi); //? //mi="aYlJTFE+cQjwsVkhmQrFnlwSPSidfPFbSaez8qw47xEfqwhPHX9na+7KoFwere3F2Incr0OoBhNt\nK8cqKwHtzuvJMW3/rz0X8n9Jld22lrsh9TOcEiq3Xwk3jTfNhGNnOEQIsOYVZs3Qqumdm0tAu7y6\nBHSE8kbfhRIPsqOys+0="; String[] mis = mi.split("#"); String ming1 = ""; for (String string : mis) { ming1 += RSAUtils.decryptByPrivateKey(string); } System.err.println("?:" + ming); System.err.println("?:" + ming1); // String a = "cVqjXrpazESBCFmZy5HxIy+C5o0PbYk9iCtBHBCGi8TMRPp2LpsVblrZIGrCw4s/fPEJp5pL7pBfZw4HDx412OfQpMCxezTltNNRWQBbFYCz/FHj6GeX7KAnkZhTC4hTZSHp1EyIa5EMsF6xdFtHuki98KS+75L3Z1Iln1efk2Y="; // System.out.println(RSAUtils.decryptByPrivateKey(a)); // System.out.println(RSAUtils.decryptByPrivateKey(null)); // RSAPrivateKey privateKey = getPrivateKey(); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, privateKey); // //int key_len = privateKey.getModulus().bitLength() / 8; String srcstring = "NKUsmMdJpSeAVFSk3hMwBoWsA7t/wOMc8hfzo2dwPIULOo1y0AUwPTDxVLw7AK1888rdyp/3U38y5eQUjuNQH68XN4jm7MHdRm+bnO6XUHuZLiXNFkLpVCAM5hVh6TTcOz3QIE9rhP+Up1WRxnq/PDuM/cXIeNWjBLbW4Iic9/w=#fRdhSf+a3xVktmJ6J0AJTW30wqpwQslN0Bxdyzpyr6u6VEj/Vo/5MpzZsVeIyBU/CzVvvkrvs5LKTagaA3M4thH3mz4gfMTrw746n4NhujZEUEehvNQIFdUBjKWPAI0XUtdcQQTtdUJbIWmuhTYxKParm0G8cNz5DSTRUTIw2fQ=#a9CaDtGkhVQNwgxHl0oJ8I/383pE3kE8yF76OyDtfeQsT50izuk44xQ34ersgzKkKSA8IB0W3SSw2bedsaj8A9dxrSf+S8S8w/Sg3G3/IA8pKaQqJD4idTCUFxjczf32aQbv+eUbs7fenAPKb3rpn+R+Q/c5y6jTEG5h+H27MsY=#N/dn52TTgJ+EoxTSp3weagZ+ggrIPl4rtKfzo0f/j2lMtXMfCQN7xgGiwDpv4Rele/58NV2X0ezDXjB3wtVugIA3nhKSNnsjEs/os1Zl2XO1EKuTnLGSJFSPS6yyr4o0wxHEeA52qA1UXaYS9clpjraXCDWuRrTpyQfONVDXGZ4=#P48NIZj+L8stk0CCNwAQmKZPH0/7GfOhhc9s/MONVPHBPRYo9N47Kb71PJszhrLsoEM2/VZD1Ech4HH8UmWhW6XPnVAWy/lS1nZDD/GEoTZvoN4Rw7oiWUGj2i+2SMyjcET9mnVPBUrgTmP8He5OFV6oIa1mAN95V4UkbXwYApw=#h79I/zTTAc2TA7j4k2wq5hrotElhskZudnuTViRvR2Ot9rAlFzdl1WasY0e+9pi7dCi40F5+2U7eVNuWLA9qvFKwgUSxA+z6FI++p0fAGsboJna9qwcplByYWh6DFPiPVFlRD2CTOZU+U/rfFn8wRT/qgLGyNI23/2el0fC1Bb0="; String stringarray[] = srcstring.split("#"); List<byte[]> srcArrays = new ArrayList<byte[]>(); for (String stemp : stringarray) { byte[] byte_temp = Base64Util.decryptBASE64(stemp); byte_temp = cipher.doFinal(byte_temp); srcArrays.add(byte_temp); } byte[] byte_sta = sysCopy(srcArrays); System.err.println(new String(byte_sta)); }
From source file:hh.learnj.test.license.test.rsa.RSATest.java
/** * ?/*from w w w .j a va 2 s .c o m*/ * * @throws Exception */ static void generatorKeyPair() throws Exception { KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(ALGORITHM_RSA); keyPairGen.initialize(1024); KeyPair keyPair = keyPairGen.generateKeyPair(); RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic(); byte[] keyBs = rsaPublicKey.getEncoded(); publicKey = encodeBase64(keyBs); System.out.println("?\r\n" + publicKey); RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate(); keyBs = rsaPrivateKey.getEncoded(); privateKey = encodeBase64(keyBs); System.out.println("??\r\n" + privateKey); }
From source file:org.nick.ghettounlock.GhettoTrustAgent.java
public static void setPublicKey(Context ctx, RSAPublicKey pubKey) { String pubKeyStr = pubKey == null ? null : Base64.encodeToString(pubKey.getEncoded(), Base64.DEFAULT); PreferenceManager.getDefaultSharedPreferences(ctx).edit().putString(PREF_PUB_KEY, pubKeyStr).commit(); }
From source file:com.security.ch08_rsa.RSACoderTextKey.java
/** * ?/*from w ww . j av a 2 s . c o m*/ * * @return Map Map * @throws Exception */ public static Map<String, String> initKey(UUID licenseCode) throws Exception { // ? KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM); // ?? // keyPairGen.initialize(KEY_SIZE); keyPairGen.initialize(KEY_SIZE, new SecureRandom(licenseCode.toString().getBytes(UTF_8))); // ? KeyPair keyPair = keyPairGen.generateKeyPair(); // RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); // ? RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); // ? Map<String, String> keyMap = new HashMap<String, String>(); keyMap.put(PUBLIC_KEY, Base64.encodeBase64String(publicKey.getEncoded())); keyMap.put(PRIVATE_KEY, Base64.encodeBase64String(privateKey.getEncoded())); keyMap.put(LICENSE_CODE, licenseCode.toString()); return keyMap; }
From source file:org.openbaton.nfvo.core.api.KeyManagement.java
@Override public String generateKey(String projectId, String name) throws IOException, NoSuchAlgorithmException { log.debug("Generating keypair"); KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048);/* w ww . ja v a2 s.c om*/ KeyPair keyPair = keyGen.genKeyPair(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); String publicKeyString = encodePublicKey(publicKey, name); Key key = new Key(); key.setName(name); key.setProjectId(projectId); key.setFingerprint(calculateFingerprint(publicKey.getEncoded())); key.setPublicKey(publicKeyString); log.debug(publicKeyString); keyRepository.save(key); log.info("Added new key: " + key); return parsePrivateKey(privateKey.getEncoded()); }
From source file:jenkins.plugins.mailer.tasks.MimeMessageBuilder.java
private void setJenkinsInstanceIdent(MimeMessage msg) throws MessagingException { if (Jenkins.getInstance() != null) { String encodedIdentity;/*from w w w . ja v a 2s .c o m*/ try { RSAPublicKey publicKey = InstanceIdentity.get().getPublic(); encodedIdentity = Base64.encode(publicKey.getEncoded()); } catch (Throwable t) { // Ignore. Just don't add the identity header. logError("Failed to set Jenkins Identity header on email.", t); return; } msg.setHeader("X-Instance-Identity", encodedIdentity); } }
From source file:com.kuzumeji.platform.standard.SecurityService.java
/** * RSA???/*from ww w . j a v a 2 s. co m*/ * <dl> * <dt>? * <dd>RSA??? * </dl> * @param name RSA??? * @param keyPair RSA? */ public void saveKeyPair(final String name, final KeyPair keyPair) { try { final Properties property = new PropertyService(PROPERTY_NAME).getProperty(); final RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); property.setProperty(String.format(KEY_PUBLIC_ENCODED, name), Hex.encodeHexString(publicKey.getEncoded())); final RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); property.setProperty(String.format(KEY_PRIVATE_ENCODED, name), Hex.encodeHexString(privateKey.getEncoded())); try (FileOutputStream stream = new FileOutputStream( Thread.currentThread().getContextClassLoader().getResource(PROPERTY_NAME).getPath());) { property.store(stream, "RSAPublicKey and RSAPrivateKey"); } } catch (final IOException e) { throw new RuntimeException(e); } }
From source file:hudson.TcpSlaveAgentListener.java
/** * Gets the Base64 encoded public key that forms part of this instance's identity keypair. * @return the Base64 encoded public key * @since 2.16/*from w w w .j av a 2 s.c o m*/ */ @Nullable public String getIdentityPublicKey() { RSAPublicKey key = InstanceIdentityProvider.RSA.getPublicKey(); return key == null ? null : new String(Base64.encodeBase64(key.getEncoded()), Charset.forName("UTF-8")); }
From source file:com.kuzumeji.platform.standard.SecurityServiceTest.java
@Test public void testKeyPair() { // RSA???/*from w w w . j ava2 s . com*/ final KeyPair keyPair = testee.generateKeyPair(); final RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); final RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); LOG.debug("?->{}", dumpKeyPair(publicKey)); LOG.debug("?->{}", dumpKeyPair(privateKey)); // RSA???/ testee.saveKeyPair("testee", keyPair); final KeyPair keyPair2 = testee.loadKeyPair("testee"); assertThat(keyPair2.getPublic().getAlgorithm(), is(publicKey.getAlgorithm())); assertThat(keyPair2.getPublic().getFormat(), is(publicKey.getFormat())); assertThat(keyPair2.getPublic().getEncoded(), is(publicKey.getEncoded())); assertThat(keyPair2.getPrivate().getAlgorithm(), is(privateKey.getAlgorithm())); assertThat(keyPair2.getPrivate().getFormat(), is(privateKey.getFormat())); assertThat(keyPair2.getPrivate().getEncoded(), is(privateKey.getEncoded())); // ???(??) final File file = testee.savePublicKeyFile(publicKey); LOG.debug("? : {}", file.getPath()); }
From source file:org.loklak.api.aaa.PublicKeyRegistrationService.java
@Override public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization authorization, final JSONObjectWithDefault permissions) throws APIException { if (post.get("register", null) == null && !post.get("create", false) && !post.get("getParameters", false)) { throw new APIException(400, "Accepted parameters: 'register', 'create' or 'getParameters'"); }// w w w. j a v a 2s. c o m JSONObject result = new JSONObject(); // return algorithm parameters and users for whom we are allowed to register a key if (post.get("getParameters", false)) { result.put("self", permissions.getBoolean("self", false)); result.put("users", permissions.getJSONObject("users")); result.put("userRoles", permissions.getJSONObject("userRoles")); JSONObject algorithms = new JSONObject(); JSONObject rsa = new JSONObject(); JSONArray keySizes = new JSONArray(); for (int i : allowedKeySizesRSA) { keySizes.put(i); } rsa.put("sizes", keySizes); rsa.put("defaultSize", defaultKeySizeRSA); algorithms.put("RSA", rsa); result.put("algorithms", algorithms); JSONArray formats = new JSONArray(); for (String format : allowedFormats) { formats.put(format); } result.put("formats", formats); return result; } // for which id? String id; if (post.get("id", null) != null) id = post.get("id", null); else id = authorization.getIdentity().getName(); // check if we are allowed register a key if (!id.equals(authorization.getIdentity().getName())) { // if we don't want to register the key for the current user // create Authentication to check if the user id is a registered user ClientCredential credential = new ClientCredential(ClientCredential.Type.passwd_login, id); Authentication authentication = new Authentication(credential, DAO.authentication); if (authentication.getIdentity() == null) { // check if identity is valid authentication.delete(); throw new APIException(400, "Bad request"); // do not leak if user exists or not } // check if the current user is allowed to create a key for the user in question boolean allowed = false; // check if the user in question is in 'users' if (permissions.getJSONObject("users", null).has(id) && permissions.getJSONObjectWithDefault("users", null).getBoolean(id, false)) { allowed = true; } else { // check if the user role of the user in question is in 'userRoles' Authorization auth = new Authorization(authentication.getIdentity(), DAO.authorization, DAO.userRoles); for (String key : permissions.getJSONObject("userRoles").keySet()) { if (key.equals(auth.getUserRole().getName()) && permissions.getJSONObject("userRoles").getBoolean(key)) { allowed = true; } } } if (!allowed) throw new APIException(400, "Bad request"); // do not leak if user exists or not } else { // if we want to register a key for this user, bad are not allowed to (for example anonymous users) if (!permissions.getBoolean("self", false)) throw new APIException(403, "You are not allowed to register a public key"); } // set algorithm. later, we maybe want to support other algorithms as well String algorithm = "RSA"; if (post.get("algorithm", null) != null) { algorithm = post.get("algorithm", null); } if (post.get("create", false)) { // create a new key pair on the server if (algorithm.equals("RSA")) { int keySize = 2048; if (post.get("key-size", null) != null) { int finalKeyLength = post.get("key-size", 0); if (!IntStream.of(allowedKeySizesRSA).anyMatch(x -> x == finalKeyLength)) { throw new APIException(400, "Invalid key size."); } keySize = finalKeyLength; } KeyPairGenerator keyGen; KeyPair keyPair; try { keyGen = KeyPairGenerator.getInstance(algorithm); keyGen.initialize(keySize); keyPair = keyGen.genKeyPair(); } catch (NoSuchAlgorithmException e) { throw new APIException(500, "Server error"); } registerKey(authorization.getIdentity(), keyPair.getPublic()); String pubkey_pem = null, privkey_pem = null; try { StringWriter writer = new StringWriter(); PemWriter pemWriter = new PemWriter(writer); pemWriter.writeObject(new PemObject("PUBLIC KEY", keyPair.getPublic().getEncoded())); pemWriter.flush(); pemWriter.close(); pubkey_pem = writer.toString(); } catch (IOException e) { } try { StringWriter writer = new StringWriter(); PemWriter pemWriter = new PemWriter(writer); pemWriter.writeObject(new PemObject("PRIVATE KEY", keyPair.getPrivate().getEncoded())); pemWriter.flush(); pemWriter.close(); privkey_pem = writer.toString(); } catch (IOException e) { } result.put("publickey_DER_BASE64", Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded())); result.put("privatekey_DER_BASE64", Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded())); result.put("publickey_PEM", pubkey_pem); result.put("privatekey_PEM", privkey_pem); result.put("keyhash", IO.getKeyHash(keyPair.getPublic())); try { result.put("keyhash_urlsave", URLEncoder.encode(IO.getKeyHash(keyPair.getPublic()), "UTF-8")); } catch (UnsupportedEncodingException e) { } result.put("key-size", keySize); result.put("message", "Successfully created and registered key. Make sure to copy the private key, it won't be saved on the server"); return result; } throw new APIException(400, "Unsupported algorithm"); } else if (post.get("register", null) != null) { if (algorithm.equals("RSA")) { String type = post.get("type", null); if (type == null) type = "DER"; RSAPublicKey pub; String encodedKey; try { encodedKey = URLDecoder.decode(post.get("register", null), "UTF-8"); } catch (Throwable e) { throw new APIException(500, "Server error"); } Log.getLog().info("Key (" + type + "): " + encodedKey); if (type.equals("DER")) { try { X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(encodedKey)); pub = (RSAPublicKey) KeyFactory.getInstance(algorithm).generatePublic(keySpec); } catch (Throwable e) { throw new APIException(400, "Public key not readable (DER)"); } } else if (type.equals("PEM")) { try { PemReader pemReader = new PemReader(new StringReader(encodedKey)); PemObject pem = pemReader.readPemObject(); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pem.getContent()); pub = (RSAPublicKey) KeyFactory.getInstance(algorithm).generatePublic(keySpec); } catch (Exception e) { throw new APIException(400, "Public key not readable (PEM)"); } } else { throw new APIException(400, "Invalid value for 'type'."); } // check key size (not really perfect yet) int keySize; int bitLength = pub.getModulus().bitLength(); if (bitLength <= 512) { keySize = 512; } else if (bitLength <= 1024) { keySize = 1024; } else if (bitLength <= 2048) { keySize = 2048; } else if (bitLength <= 4096) { keySize = 4096; } else { keySize = 8192; } if (!IntStream.of(allowedKeySizesRSA).anyMatch(x -> x == keySize)) { throw new APIException(400, "Invalid key length."); } registerKey(authorization.getIdentity(), pub); String pubkey_pem = null; try { StringWriter writer = new StringWriter(); PemWriter pemWriter = new PemWriter(writer); pemWriter.writeObject(new PemObject("PUBLIC KEY", pub.getEncoded())); pemWriter.flush(); pemWriter.close(); pubkey_pem = writer.toString(); } catch (IOException e) { } result.put("publickey_DER_BASE64", Base64.getEncoder().encodeToString(pub.getEncoded())); result.put("publickey_PEM", pubkey_pem); result.put("keyhash", IO.getKeyHash(pub)); try { result.put("keyhash_urlsave", URLEncoder.encode(IO.getKeyHash(pub), "UTF-8")); } catch (UnsupportedEncodingException e) { } result.put("message", "Successfully registered key."); return result; } throw new APIException(400, "Unsupported algorithm"); } throw new APIException(400, "Invalid parameter"); }